/
ir-hlc.bas
4131 lines (3487 loc) · 116 KB
/
ir-hlc.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
''
'' "high level" IR interface for emitting C code
''
'' The C backend is called "high level" in comparison to the ASM backend, but
'' actually produces pretty low-level, ABI-dependant C code, using gcc as the
'' "assembler". It works with mostly the same low-level operations that would
'' be sent to the ASM backend (for example: labels and jumps instead of if/else
'' blocks).
''
'' - Some math operations are transparently implemented using gcc __builtin_*()
'' functions. For others, we let the AST know that we can't handle them here,
'' and it will call RTL functions instead.
''
'' - Float to int conversions need special treatment to achieve FB's rounding
'' behaviour. Simple C casting as in '(int)floatvar' cannot be used because it
'' just truncates instead of rounding to nearest. Thus we use 4 helper
'' routines (float|double -> int32|int64) that are implemented in x86 ASM
'' (as done by the ASM backend) or using __builtin_nearbyint[f]().
''
'' - Field accesses, pointer indexing, struct layout/field alignment, etc. is
'' all still calculated on the FB side, i.e. the generated C code is
'' ABI-dependant. sizeof()/offsetof() are evaluated purely on the FB side,
'' it's impossible to pass all constant expressions on to the C backend.
'' (constants, array bounds, fixstr lengths, multi-dim indexing, ...)
''
'' - va_* vararg macros can't be supported with the C backend, they are too
'' different from C's va_*() macros.
'' 1. For example, FB's va_first/va_arg can be called repeatedly, that's not
'' possible with C's va_start/va_arg. Acccessing the current arg and
'' advancing to the next is two separate functions in FB, but combined in
'' one in C. It's impossible to reliably & automatically translate from one
'' to the other.
'' 2. It's not possible to implement va_first() as "address-of last named
'' parameter" as done for the ASM backend, because gcc sometimes puts
'' parameters into temp vars, and then addrof on that parameter returns the
'' temp var, not the parameter.
'' 3. On x86 va_list is just a pointer (exactly what's needed for va_first())
'' but for x86_64 it's not that easy. Varargs may be passed in registers.
'' 4. It'd be "nice" to be able to read out all var args into a buffer and
'' allow that to be accessed through FB's va_* macros, but that's not
'' possible because there's no way to know how many varargs there are.
''
'' - Calling conventions/name mangling:
''
'' * We sometimes make use of gcc's asm("nameToUseInAsm") feature which is
'' similar to ALIAS.
''
'' * Cdecl and Stdcall (stdcall with @N) are easily emitted for GCC on
'' individual functions.
''
'' * Special case for stdcall + functions returning UDTs, where we already
'' had to "lower the AST on the FB-side" to use a hidden pointer parameter
'' and pointer result, instead of plain UDT result (see hGetReturnType()):
''
'' gcc doesn't know that the "hidden" result parameter is special and thus
'' calculates it into the @N suffix. We need to use an asm() alias to avoid
'' that.
''
'' * StdcallMs (stdcall without @N) is not directly supported by gcc, only at
'' the linker level through ld --kill-at etc. We need it for individual
'' functions though, not the entire executable/DLL. We can achieve that by
'' using asm() aliases.
''
'' Because gcc inserts these asm() names into DLL export tables as-is,
'' without stripping the underscore prefix, we must emit the exports
'' manually using inline ASM instead of __attribute__((dllexport)) to get
'' them to work correctly.
''
'' * Pascal is like StdcallMs except that arguments are pushed left-to-right
'' (same order as written in code, not reversed like Cdecl/Stdcall). The
'' symbGetProc*Param() macros take care of changing the order when cycling
'' through parameters of Pascal functions, and by together with such
'' functions being emitted as Stdcall this results in a double-reverse
'' resulting in the proper ABI.
''
'' * For non-x86, there's no need to emit cdecl/stdcall/... at all because
'' they don't exist (on x86_64 or ARM etc.) and gcc ignores the attributes.
''
'' - "boolean" is implemented as int8, instead of C99's _Bool type (even though
'' FB's boolean is supposed to be compatible with C's _Bool), because that way
'' we can avoid undefined behaviour if values other than 0/1 are stored in the
'' boolean, and get the same behaviour as with the ASM backend. Of course that
'' also means we have to add code for converting int/float to 0/1 when casting
'' them to boolean.
''
'' - Avoiding C's undefined behaviour where possible. This is important because
'' otherwise we can't rely on gcc to generate meaningful code when
'' "optimizations" are enabled. As a (hopefully nice-to-have) side-effect,
'' some of the FB features/behaviour that originates from the x86 ASM backend
'' are guaranteed to work just the same with the C backend, no matter what
'' architecture.
'' - using gcc's -fwrapv to get well-defined signed integer overflow
'' - emitting the extra AND mask operation on the rhs of SHL/SHR, to ensure
'' that the shift amount is in the range 0..sizeof(lhs)*8-1.
'' (astNewBOP() already handles this for constant shift amounts)
'' - relying on gcc to provide well-defined signed shl on negative integers
'' (https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html)
''
#include once "fb.bi"
#include once "fbint.bi"
#include once "ir.bi"
#include once "rtl.bi"
#include once "flist.bi"
#include once "lex.bi"
#include once "ir-private.bi"
'' The stack of nested sections allows us to go back and emit text to
'' the headers of parent sections, while already working on emitting
'' something else in an inner section.
'' (most commonly used for UDT declarations, which are only emitted
'' when they're needed by something else that's being emitted)
''
'' index 0 is the "toplevel" section,
'' index 1 is the "body" where procedures are emitted into,
'' the rest is used for nested procedure/scope blocks.
''
'' "body" is separate from "toplevel" to allow adding declarations to
'' "toplevel", while the procedures are appended to "body", one after
'' another. Then, once all procedures are emitted, "body" is closed,
'' and is appended to "toplevel". At that point we're done emitting
'' anyways and don't need to add stuff to toplevel's header anymore.
''
'' This kind of container/body pair is not currently needed for procs/scopes,
'' because there we emit declarations "in line" instead of moving all to the
'' top of the scope. For the toplevel emitting all at once makes sense because
'' it is more efficient to check the symbol tables for called procedures only
'' once during _emitEnd() instead of once during every _emitProcBegin().
'' Note that _emitBegin() is called before parsing has even started,
'' so the global declarations can't be emitted from there already.
const MAX_SECTIONS = FB_MAXSCOPEDEPTH + 1
type SECTIONENTRY
text as string
old as integer '' old junk text (that is only kept around to keep the string allocated)?
indent as integer '' current indendation level to be used when emitting lines into this section
end type
enum
EXPRCLASS_TEXT = 0
EXPRCLASS_IMM
EXPRCLASS_SYM
EXPRCLASS_CAST
EXPRCLASS_UOP
EXPRCLASS_BOP
EXPRCLASS_MACRO
end enum
type EXPRNODE
class as integer '' EXPRCLASS_*
'' This expression's type, to determine whether CASTs are needed or not
dtype as integer
subtype as FBSYMBOL ptr
l as EXPRNODE ptr '' CAST/UOP/BOP
r as EXPRNODE ptr '' BOP
union
text as zstring ptr '' TEXT
val as FBVALUE '' IMM
sym as FBSYMBOL ptr '' SYM
op as integer '' UOP/BOP
end union
end type
type EXPRCACHENODE
'' Each cache entry associates an expression tree with a vreg id,
'' allowing expressions to be looked up for certain vreg accesses,
'' instead of having to be emitted as #defines or temp vars.
''
'' Having a separate list for the cache is faster than cycling through
'' the whole ctx.exprnodes list. Often there will be only 1 (UOPs) or
'' 2 (BOPs) expression trees cached, since the AST usually accesses
'' expression results right when emitting the next expression/statement.
vregid as integer
expr as EXPRNODE ptr
end type
enum
BUILTIN_F2I = (1 shl 0)
BUILTIN_F2L = (1 shl 1)
BUILTIN_F2UL = (1 shl 2)
BUILTIN_D2I = (1 shl 3)
BUILTIN_D2L = (1 shl 4)
BUILTIN_D2UL = (1 shl 5)
BUILTIN_STATICASSERT = (1 shl 6)
end enum
type IRHLCCTX
sections(0 to MAX_SECTIONS-1) as SECTIONENTRY
section as integer '' Current section to write to
sectiongosublevel as integer
linenum as integer
escapedinputfilename as string
usedbuiltins as uinteger '' BUILTIN_*
anonstack as TLIST '' stack of nested anonymous structs/unions in a struct/union
varini as string
variniscopelevel as integer
fbctinf as string
exports as string
exprnodes as TLIST '' EXPRNODE
exprtext as string '' buffer used by exprFlush() to build the final text
exprcache as TLIST '' EXPRCACHENODE
globalvarpass as integer '' Global var emitting is done in 2 passes; this allows the callbacks to identify the current pass.
end type
declare function hEmitType _
( _
byval dtype as integer, _
byval subtype as FBSYMBOL ptr _
) as string
declare sub hEmitStruct( byval s as FBSYMBOL ptr, byval is_ptr as integer )
declare sub _emitDBG _
( _
byval op as integer, _
byval proc as FBSYMBOL ptr, _
byval lnum as integer, _
ByVal filename As zstring ptr = 0 _
)
declare sub exprFreeNode( byval n as EXPRNODE ptr )
#if __FB_DEBUG__
declare sub exprDump( byval n as EXPRNODE ptr )
#endif
'' globals
dim shared as IRHLCCTX ctx
'' same order as FB_DATATYPE
dim shared as const zstring ptr dtypeName(0 to FB_DATATYPES-1) = _
{ _
@"void" , _ '' void
@"boolean" , _ '' boolean
@"int8" , _ '' byte
@"uint8" , _ '' ubyte
@"char" , _ '' char
@"int16" , _ '' short
@"uint16" , _ '' ushort
NULL , _ '' wchar
NULL , _ '' integer
NULL , _ '' uinteger
NULL , _ '' enum
@"int32" , _ '' long
@"uint32" , _ '' ulong
@"int64" , _ '' longint
@"uint64" , _ '' ulongint
@"float" , _ '' single
@"double" , _ '' double
@"FBSTRING" , _ '' string
NULL , _ '' fix-len string
@"__builtin_va_list" , _ '' va_list
NULL , _ '' struct
NULL , _ '' namespace
NULL , _ '' function
@"void" , _ '' fwdref (needed for any un-resolved fwdrefs)
NULL _ '' pointer
}
private sub _init( )
irhlInit( )
listInit( @ctx.anonstack, 8, sizeof( FBSYMBOL ptr ), LIST_FLAGS_NOCLEAR )
listInit( @ctx.exprnodes, 32, sizeof( EXPRNODE ), LIST_FLAGS_CLEAR )
listInit( @ctx.exprcache, 8, sizeof( EXPRCACHENODE ), LIST_FLAGS_NOCLEAR )
irSetOption( IR_OPT_FPUIMMEDIATES or IR_OPT_MISSINGOPS )
if( fbIs64bit( ) ) then
dtypeName(FB_DATATYPE_INTEGER) = dtypeName(FB_DATATYPE_LONGINT)
dtypeName(FB_DATATYPE_UINT ) = dtypeName(FB_DATATYPE_ULONGINT)
else
dtypeName(FB_DATATYPE_INTEGER) = dtypeName(FB_DATATYPE_LONG)
dtypeName(FB_DATATYPE_UINT ) = dtypeName(FB_DATATYPE_ULONG)
end if
end sub
private sub _end( )
listEnd( @ctx.exprcache )
listEnd( @ctx.exprnodes )
listEnd( @ctx.anonstack )
irhlEnd( )
end sub
'' "Begin/end" to be used to opening/closing sections whenever opening/closing
'' procs/scopes and also for the special sections 0 (header) and 1 (body).
private sub sectionBegin( )
ctx.section += 1
assert( ctx.section < MAX_SECTIONS )
'' Tell next hWriteLine() to overwrite instead of appending,
'' to overwrite pre-existing string data, keeping the string allocated
with( ctx.sections(ctx.section) )
.old = TRUE
if( ctx.section > 0 ) then
'' Use at least the parent section's indentation
'' (some emitting functions will temporarily increase
'' it for code nested inside {} etc.)
.indent = ctx.sections(ctx.section-1).indent
else
'' Start indendation at zero TAB's
.indent = 0
end if
end with
end sub
'' Write line to current section (indentation & newline are automatically added)
private sub sectionWriteLine( byref s as string )
with( ctx.sections(ctx.section) )
if( .old ) then
if( .indent > 0 ) then
.text = string( .indent, TABCHAR )
.text += s
else
.text = s
end if
.old = FALSE
else
if( .indent > 0 ) then
.text += string( .indent, TABCHAR )
end if
.text += s
end if
.text += NEWLINE
end with
end sub
private sub sectionIndent( )
ctx.sections(ctx.section).indent += 1
end sub
private sub sectionUnindent( )
assert( ctx.sections(ctx.section).indent > 0 )
ctx.sections(ctx.section).indent -= 1
end sub
private function sectionInsideProc( ) as integer
'' 0 and 1 are toplevel, 2+ means inside proc
function = (ctx.section >= 2)
end function
private sub sectionEnd( )
dim as SECTIONENTRY ptr parent = any, child = any
assert( ctx.section >= 0 )
if( ctx.section > 0 ) then
'' Append to parent section, if anything was written
parent = @ctx.sections(ctx.section-1)
child = @ctx.sections(ctx.section)
if( child->old = FALSE ) then
if( parent->old ) then
parent->text = child->text
parent->old = FALSE
else
parent->text += child->text
end if
end if
end if
ctx.section -= 1
end sub
'' "Gosub" for temporarily writing to another section than the current one
private function sectionGosub( byval section as integer ) as integer
assert( (section >= 0) and (section <= ctx.section) )
function = ctx.section
ctx.section = section
ctx.sectiongosublevel += 1
end function
'' "Return" to restore the previous current section
private sub sectionReturn( byval section as integer )
assert( ctx.sectiongosublevel > 0 )
ctx.sectiongosublevel -= 1
ctx.section = section
end sub
'' Main emitting function
'' Writes out line of code to current section, and adds #line's
private sub hWriteLine( byref s as string, byval noline as integer = FALSE )
static as string ln
if( env.clopt.debuginfo and (noline = FALSE) ) then
ln = "#line " + str( ctx.linenum )
ln += " """ + ctx.escapedinputfilename + """"
sectionWriteLine( ln )
end if
sectionWriteLine( s )
end sub
private sub hUpdateCurrentFileName( byval filename as zstring ptr )
ctx.escapedinputfilename = hReplace( filename, "\", $"\\" )
end sub
private sub hWriteStaticAssert( byref expr as string )
dim as integer section = any
if( (ctx.usedbuiltins and BUILTIN_STATICASSERT) = 0 ) then
ctx.usedbuiltins or= BUILTIN_STATICASSERT
'' Emit the #define into the header section, not inside procedures,
'' and above the 1st use (can't be emitted from _emitEnd() because
'' then it could appear behind struct declarations...)
section = sectionGosub( 0 )
hWriteLine( "#define __FB_STATIC_ASSERT( expr ) extern int __$fb_structsizecheck[(expr) ? 1 : -1]", TRUE )
sectionReturn( section )
end if
hWriteLine( "__FB_STATIC_ASSERT( " + expr + " );" )
end sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
enum EMITPROC_OPTIONS
EMITPROC_ISPROTO = &h1
EMITPROC_ISPROCPTR = &h2
end enum
private sub hAppendCtorAttrib _
( _
byref ln as string, _
byval proc as FBSYMBOL ptr, _
byval in_front as integer _
)
dim as integer priority = any
if( proc->stats and (FB_SYMBSTATS_GLOBALCTOR or FB_SYMBSTATS_GLOBALDTOR) ) then
if( in_front = FALSE ) then
ln += " "
end if
ln += "__attribute__(( "
if( proc->stats and FB_SYMBSTATS_GLOBALCTOR ) then
ln += "constructor"
else
ln += "destructor"
end if
priority = symbGetProcPriority( proc )
if( priority <> 0 ) then
ln += "( " + str( priority ) + " )"
end if
ln += " ))"
if( in_front ) then
ln += " "
end if
end if
end sub
'' Helper function to add underscore prefix or @N stdcall suffix to mangled
'' procedure names (because symb-mangling doesn't do it for -gen gcc), for use
'' in inline ASM and such.
private function hGetMangledNameForASM _
( _
byval sym as FBSYMBOL ptr, _
byval underscore_prefix as integer _
) as string
dim as string mangled
'' rtlib mangling? Just use the alias if one was given
if( (symbGetMangling( sym ) = FB_MANGLING_RTLIB) andalso _
(sym->id.alias <> NULL) ) then
mangled = *sym->id.alias
else
mangled = *symbGetMangledName( sym )
end if
if( underscore_prefix and env.underscoreprefix ) then
mangled = "_" + mangled
end if
'' Add the @N suffix for x86 STDCALL
if( (fbGetCpuFamily( ) = FB_CPUFAMILY_X86) and symbIsProc( sym ) ) then
if( symbGetProcMode( sym ) = FB_FUNCMODE_STDCALL ) then
mangled += "@"
mangled += str( symbProcCalcStdcallSuffixN( sym ) )
end if
end if
function = mangled
end function
private function hNeedAlias( byval proc as FBSYMBOL ptr ) as integer
function = FALSE
'' rtlib mangling? Expect we always need the asm alias
if( symbGetMangling( proc ) = FB_MANGLING_RTLIB ) then
function = TRUE
exit function
end if
'' Only on systems where gcc would use the @N suffix
if( fbGetCpuFamily( ) <> FB_CPUFAMILY_X86 ) then
exit function
end if
select case( env.clopt.target )
case FB_COMPTARGET_WIN32, FB_COMPTARGET_CYGWIN, _
FB_COMPTARGET_XBOX
if( symbGetProcMode( proc ) = FB_FUNCMODE_FASTCALL ) then
exit function
end if
case else
exit function
end select
select case( symbGetProcMode( proc ) )
'' stdcallms/pascal must be emitted as stdcall and need the alias to
'' avoid the @N suffix.
case FB_FUNCMODE_STDCALL_MS, FB_FUNCMODE_PASCAL
function = TRUE
'' For stdcall with @N suffix, if the function has a hidden UDT result
'' pointer parameter, or UDT's passed byval, we need the alias to get
'' the correct @N suffix. (gcc could calculate the wrong value into the
'' @N suffix, since it doesn't known about the special result parameter
'' or byval UDTs). It should be safe to always generate the alias
'' ourselves since we already must control for the special cases.
case FB_FUNCMODE_STDCALL
function = TRUE
end select
end function
private function hEmitProcHeader _
( _
byval proc as FBSYMBOL ptr, _
byval options as EMITPROC_OPTIONS _
) as string
dim as string ln, mangled
dim as integer dtype = any
dim as FBSYMBOL ptr subtype = any
if( options = 0 ) then
'' ctor/dtor flags on bodies
hAppendCtorAttrib( ln, proc, TRUE )
end if
if( (options and EMITPROC_ISPROCPTR) = 0 ) then
if( symbIsPrivate( proc ) ) then
ln += "static "
end if
end if
'' Function result type (is 'void' for subs)
ln += hEmitType( symbGetProcRealType( proc ), _
symbGetProcRealSubtype( proc ) )
'' Calling convention if needed (for function pointers it's usually not
'' put in this place, but should work nonetheless)
if( fbGetCpuFamily( ) = FB_CPUFAMILY_X86 ) then
select case( symbGetProcMode( proc ) )
case FB_FUNCMODE_STDCALL, FB_FUNCMODE_STDCALL_MS, FB_FUNCMODE_PASCAL
select case( env.clopt.target )
case FB_COMPTARGET_WIN32, FB_COMPTARGET_XBOX
'' MinGW recognizes this shorter & prettier version
ln += " __stdcall"
case else
'' Linux GCC only accepts this
ln += " __attribute__((stdcall))"
end select
case FB_FUNCMODE_THISCALL
select case( env.clopt.target )
case FB_COMPTARGET_WIN32, FB_COMPTARGET_XBOX
ln += " __thiscall"
case else
ln += " __attribute__((thiscall))"
end select
case FB_FUNCMODE_FASTCALL
select case( env.clopt.target )
case FB_COMPTARGET_WIN32, FB_COMPTARGET_XBOX
ln += " __fastcall"
case else
ln += " __attribute__((fastcall))"
end select
end select
end if
ln += " "
mangled = *symbGetMangledName( proc )
'' Identifier
if( options and EMITPROC_ISPROCPTR ) then
ln += "(*"
ln += mangled
ln += ")"
else
ln += mangled
end if
'' Parameter list
ln += "( "
'' If returning a struct, there's an extra parameter
dim as FBSYMBOL ptr hidden = NULL
if( symbProcReturnsOnStack( proc ) ) then
if( options and EMITPROC_ISPROTO ) then
hidden = symbGetSubType( proc )
ln += hEmitType( typeAddrOf( symbGetType( hidden ) ), hidden )
else
hidden = proc->proc.ext->res
ln += hEmitType( typeAddrOf( symbGetType( hidden ) ), symbGetSubtype( hidden ) )
ln += " " + *symbGetMangledName( hidden )
end if
if( symbGetProcParams( proc ) > 0 ) then
ln += ", "
end if
end if
var param = symbGetProcLastParam( proc )
if( (hidden = NULL) and (param = NULL) ) then
ln += "void"
end if
while( param )
if( symbGetParamMode( param ) = FB_PARAMMODE_VARARG ) then
ln += "..."
else
'' Emit clang-compatible datatype for main()'s argv,
'' clang is very strict about this...
if( param->stats and FB_SYMBSTATS_ARGV ) then
ln += "char**"
else
symbGetRealParamDtype( param, dtype, subtype )
ln += hEmitType( dtype, subtype )
end if
if( (options and EMITPROC_ISPROTO) = 0 ) then
ln += " " + *symbGetMangledName( symbGetParamVar( param ) )
end if
end if
param = symbGetProcPrevParam( proc, param )
if( param ) then
ln += ", "
end if
wend
ln += " )"
if( ((options and EMITPROC_ISPROCPTR) = 0) and _
((options and EMITPROC_ISPROTO) <> 0) ) then
'' Add asm("mangledname") alias if needed.
'' asm() can only be be used on prototypes.
if( hNeedAlias( proc ) ) then
ln += " asm(""" + hGetMangledNameForASM( proc, TRUE ) + """)"
end if
'' ctor/dtor flags on prototypes
hAppendCtorAttrib( ln, proc, FALSE )
end if
function = ln
end function
private function hGetUdtTag( byval sym as FBSYMBOL ptr ) as string
if( symbIsStruct( sym ) ) then
if( symbGetUDTIsUnion( sym ) ) then
function = "union "
else
function = "struct "
end if
end if
end function
private function hGetUdtId( byval sym as FBSYMBOL ptr ) as string
if( typeGetMangleDt( symbGetFullType( sym ) ) = FB_DATATYPE_VA_LIST ) then
'' gcc's __builtin_va_list needs an exact name
select case symbGetValistType( symbGetFullType( sym ), symbGetSubtype( sym ) )
case FB_CVA_LIST_BUILTIN_C_STD, FB_CVA_LIST_BUILTIN_AARCH64, FB_CVA_LIST_BUILTIN_ARM
function = *sym->id.alias
exit function
end select
end if
'' Prefixing the mangled name with a $ because it may start with a
'' number which isn't allowed in C.
function = "$" + *symbGetMangledName( sym )
end function
private function hGetUdtName( byval sym as FBSYMBOL ptr ) as string
function = hGetUdtTag( sym ) + hGetUdtId( sym )
end function
private sub hEmitUDT( byval s as FBSYMBOL ptr, byval is_ptr as integer )
dim as integer section = any
if( s = NULL ) then
return
end if
if( symbGetIsEmitted( s ) ) then
return
end if
if( symbIsLocal( s ) ) then
'' Write declaration to corresponding scope
'' (FB_MAINSCOPE=0 maps to section index 1)
section = 1 + symbGetScope( s )
'' Local to FB main? Convert to explicit main() function...
'' (should only happen while emitting main(), since we won't
'' see main's locals from elsewhere)
if( symbGetScope( s ) = FB_MAINSCOPE ) then
section += 1
'' global namespace due the implicit MAIN?
elseif( symbGetNamespace( s ) = @symbGetGlobalNamespc( ) ) then
section += 1
end if
'' Switching from a parent to a child scope isn't allowed,
'' the UDT declaration will be forced to be emitted in the
'' parent scope anyways, since apparently that's where we
'' need it. (used by _procAllocStaticVars())
if( section > ctx.section ) then
section = ctx.section
end if
else
'' Write to toplevel
section = 0
end if
section = sectionGosub( section )
select case as const symbGetClass( s )
case FB_SYMBCLASS_ENUM
symbSetIsEmitted( s )
'' no subtype, to avoid infinite recursion
hWriteLine( "typedef " + hEmitType( FB_DATATYPE_ENUM, NULL ) + " " + hGetUdtName( s ) + ";" )
case FB_SYMBCLASS_STRUCT
hEmitStruct( s, is_ptr )
'' We're emitting procptr subtypes as typedefs, instead of expanding them in-place,
'' because that way we can keep doing the "type id" syntax for local vars, parameters, etc.,
'' while when expanding procptrs it would become more complicated ("returntype (*id)(parameters)").
case FB_SYMBCLASS_PROC
if( symbGetIsFuncPtr( s ) ) then
'' While emitting a procptr typedef, we may emit a UDT that references this procptr typedef.
'' For example:
'' type FBSYMBOL_ as FBSYMBOL
'' type FBRTLCALLBACK as function(byval as FBSYMBOL_ ptr) as integer
'' type FBSYMBOL
'' callback as FBRTLCALLBACK
'' end type
'' dim callback as FBRTLCALLBACK
'' In a case like that, we should take care not to emit the typedef twice, because that
'' isn't allowed by older gcc versions.
'' 1. Build the procedure declaration and emit its dependencies...
var decl = hEmitProcHeader( s, EMITPROC_ISPROTO or EMITPROC_ISPROCPTR )
'' 2. Emit this procptr typedef if it wasn't emitted by step 1
if( symbGetIsEmitted( s ) = FALSE ) then
hWriteLine( "typedef " + decl + ";" )
symbSetIsEmitted( s )
end if
end if
end select
sectionReturn( section )
end sub
'' Returns "[N]" (N = array size) if the symbol is an array or a fixlen string.
private function hEmitArrayDecl( byval sym as FBSYMBOL ptr ) as string
dim as string s
'' even dllimport'ed arrays are emitted as pointers, not arrays
if( symbIsImport( sym ) ) then
exit function
end if
'' Emit all array dimensions individually
'' (This lets array initializers rely on gcc to fill uninitialized
'' elements with zeroes)
select case( symbGetClass( sym ) )
case FB_SYMBCLASS_VAR, FB_SYMBCLASS_FIELD
if( symbGetIsDynamic( sym ) = FALSE ) then
for i as integer = 0 to symbGetArrayDimensions( sym ) - 1
'' elements = ubound( array, d ) - lbound( array, d ) + 1
s += "[" + str( symbArrayUbound( sym, i ) - symbArrayLbound( sym, i ) + 1 ) + "]"
next
end if
end select
if( symbIsRef( sym ) = FALSE ) then
'' If it's a fixed-length string, add an extra array dimension
'' (zstring * 5 becomes char[5])
dim as longint length = 0
select case( symbGetType( sym ) )
case FB_DATATYPE_FIXSTR, FB_DATATYPE_CHAR
length = symbGetStrLen( sym )
case FB_DATATYPE_WCHAR
length = symbGetWstrLen( sym )
end select
if( length > 0 ) then
s += "[" + str( length ) + "]"
end if
end if
function = s
end function
private sub hEmitVarDecl _
( _
byval use_extern as integer, _
byval sym as FBSYMBOL ptr, _
byval varini as zstring ptr _
)
dim as string ln
if( use_extern ) then
ln += "extern "
elseif( symbIsStatic( sym ) and ((symbGetAttrib( sym ) and (FB_SYMBATTRIB_COMMON or FB_SYMBATTRIB_PUBLIC or FB_SYMBATTRIB_EXTERN)) = 0) ) then
ln += "static "
end if
dim dtype as integer
dim subtype as FBSYMBOL ptr
symbGetRealType( sym, dtype, subtype )
ln += hEmitType( dtype, sym->subtype )
ln += " " + *symbGetMangledName( sym )
ln += hEmitArrayDecl( sym )
'' dllimport's are handled manually, emitted as pointers and deref'ed
'' where needed, as with the ASM backend, as opposed to using
'' __attribute__((dllimport)). The _imp__ prefix will be added by fbc's
'' name mangling.
if( symbIsCommon( sym ) and (not use_extern) ) then
ln += " __attribute__((common))"
end if
if( varini ) then
ln += " = " + *varini
end if
ln += ";"
hWriteLine( ln )
end sub
private sub hMaybeEmitLocalVar( byval sym as FBSYMBOL ptr )
assert( symbIsLocal( sym ) )
'' Fake dynamic array symbol? Descriptor will be emitted instead
'' TODO: Skip unused STATICs
if( symbGetIsDynamic( sym ) ) then
exit sub
end if
if( (symbGetTypeIniTree( sym ) <> NULL) and symbIsStatic( sym ) ) then
irhlFlushStaticInitializer( sym )
else
hEmitVarDecl( FALSE, sym, NULL )
end if
end sub
private sub hAllocGlobalVar( byval sym as FBSYMBOL ptr )
if( symbGetTypeIniTree( sym ) ) then
'' Unused private global? Don't bother emitting it
if( (not symbIsPublic( sym )) and (not symbGetIsAccessed( sym )) ) then
exit sub
end if
irhlFlushStaticInitializer( sym )
else
hEmitVarDecl( FALSE, sym, NULL )
end if
end sub
private sub hMaybeEmitGlobalVar( byval sym as FBSYMBOL ptr )
assert( symbIsLocal( sym ) = FALSE )
'' String literals? Emitted inline instead of as global vars
'' Unused EXTERN? Don't bother emitting it
'' TODO: Skip all unused private globals, not just initialized ones below
'' Fake dynamic array symbol? Descriptor will be emitted instead
if( symbGetIsLiteral( sym ) or _
(symbIsExtern( sym ) and (not symbGetIsAccessed( sym ))) or _
symbGetIsDynamic( sym ) ) then
exit sub
end if
select case( ctx.globalvarpass )
case 1
if( symbGetAttrib( sym ) and (FB_SYMBATTRIB_COMMON or FB_SYMBATTRIB_PUBLIC or FB_SYMBATTRIB_EXTERN) ) then
'' Emit externs as prototypes only for now;
'' their initializers may reference other not-yet-emitted globals
hEmitVarDecl( TRUE, sym, NULL )
else
'' Emitted other globals normally
hAllocGlobalVar( sym )
end if
case 2
'' Emit allocated externs
if( symbGetAttrib( sym ) and (FB_SYMBATTRIB_COMMON or FB_SYMBATTRIB_PUBLIC) ) then
hAllocGlobalVar( sym )
end if
end select
end sub
private sub hMaybeEmitGlobalVarExceptDataStmt( byval sym as FBSYMBOL ptr )
'' DATA descriptor? Handled by irForEachDataStmt()
if( symbIsDataDesc( sym ) ) then
exit sub
end if
hMaybeEmitGlobalVar( sym )
end sub
private sub hMaybeEmitProcProto( byval s as FBSYMBOL ptr )
dim as integer section = any
if( symbGetIsFuncPtr( s ) or (not symbGetIsAccessed( s )) ) then
exit sub
end if
if( symbGetMangledName( s ) = NULL ) then
exit sub
end if
'' All procedure declarations go into the toplevel header
section = sectionGosub( 0 )
hWriteLine( hEmitProcHeader( s, EMITPROC_ISPROTO ) + ";" )
sectionReturn( section )
end sub
private sub hEmitFieldTypes( byval udt as FBSYMBOL ptr )
dim as FBSYMBOL ptr fld = any
fld = symbUdtGetFirstField( udt )
while( fld )
hEmitUDT( symbGetSubtype( fld ), typeIsPtr( symbGetType( fld ) ) )
fld = symbUdtGetNextField( fld )
wend
end sub
private function hFindParentAnonAlreadyOnStack _
( _
byval fld as FBSYMBOL ptr _
) as FBSYMBOL ptr ptr
dim as FBSYMBOL ptr ptr anonnode = any
dim as FBSYMBOL ptr parent = any
'' For each parent, starting with the inner-most...
parent = fld->parent
do
'' Check whether it's already on the stack...
anonnode = listGetTail( @ctx.anonstack )
while( anonnode )
if( *anonnode = parent ) then
return anonnode
end if
anonnode = listGetPrev( anonnode )
wend
parent = parent->parent
loop while( parent )
function = NULL
end function
private sub hPushAnonParents _
( _
byval baseparent as FBSYMBOL ptr, _
byval parent as FBSYMBOL ptr _
)
if( parent = baseparent ) then
exit sub
end if
'' Recurse
hPushAnonParents( baseparent, parent->parent )
'' Push parents in top-down order
assert( symbIsStruct( parent ) )
if( symbGetUDTIsUnion( parent ) ) then