-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathllvm_jit.das
More file actions
8069 lines (7542 loc) · 402 KB
/
Copy pathllvm_jit.das
File metadata and controls
8069 lines (7542 loc) · 402 KB
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
options gen2
options indenting = 4
options no_unused_block_arguments = false
options no_unused_function_arguments = false
options strict_smart_pointers = false
options relaxed_pointer_const
options unsafe_table_lookup = false
options no_global_variables = false
options stack = 4_194_304 // On huge files we need huge stack for jit
module llvm_jit shared private
require llvm/daslib/llvm_boost
require llvm/daslib/llvm_jit_intrin
require llvm/daslib/llvm_jit_common
require llvm/daslib/llvm_jit_code
require llvm/daslib/llvm_user_modules // nolint:STYLE030 — side-effect require: [llvm_code] generator modules must be in THIS module's closure so their [init] registration runs in the context that reads the registry
require llvm/daslib/llvm_dll_utils
require daslib/ast_boost
require daslib/templates_boost
require daslib/macro_boost
require daslib/safe_addr
require daslib/strings_boost
require daslib/defer
require daslib/lpipe
require daslib/rtti
require math
require jit
require daslib/fio
// uncomment to enable debug
/*
options debugger
require daslib/debug
require daslib/ast_debug
require llvm/llvm_debug
*/
var active_filenames : table<string>
// nolint:STYLE014
// Packed-find codegen for STRING keys (the only key type that still packs; non-string keys are
// open-addressed at every capacity — see build_workhorse_table_find). Early-out wins for strings:
// 8xi64 SIMD is 512 bits -> 2x vpcmpeqq + mask reduction (heavy), while the scalar early-out exits
// on the first hit and needs no size guard. json_find -35%. Flip + bump CODEGEN_VERSION to re-A/B.
let JIT_PACKED_FIND_STR_EARLY_OUT = true
[macro_function]
def private get_expr_ptr(expr : ExpressionPtr) {
return expr
}
struct private IteBlock {
if_true : LLVMOpaqueBasicBlock?
if_false : LLVMOpaqueBasicBlock?
if_end : LLVMOpaqueBasicBlock?
phi_true : LLVMOpaqueBasicBlock?
phi_false : LLVMOpaqueBasicBlock?
if_true_terminates, if_false_terminates : bool
}
struct private LoopBlock {
loop_start : LLVMOpaqueBasicBlock?
loop_body : LLVMOpaqueBasicBlock?
loop_end : LLVMOpaqueBasicBlock?
loop_continue : LLVMOpaqueBasicBlock?
need_loop : LLVMOpaqueValue?
parent_while : ExprWhile? // set in preVisitExprWhile; null for ExprFor — used by preVisitExprContinue
}
struct SLabel {
index : int
blk : LLVMOpaqueBasicBlock?
}
def public set_private_linkage(value : LLVMOpaqueValue?) {
LLVMSetLinkage(value, LLVMLinkage.LLVMPrivateLinkage)
LLVMSetUnnamedAddress(value, LLVMUnnamedAddr.LLVMGlobalUnnamedAddr);
}
// Use internal linkage without unnamed address so symbol names are preserved in the
// object file's .symtab, making backtraces and debuggers (lldb/gdb) readable.
def set_debug_linkage(value : LLVMOpaqueValue?) {
LLVMSetLinkage(value, LLVMLinkage.LLVMInternalLinkage)
}
def set_public_linkage(value : LLVMOpaqueValue?) {
LLVMSetLinkage(value, LLVMLinkage.LLVMDLLExportLinkage)
LLVMSetDLLStorageClass(value, LLVMDLLStorageClass.LLVMDLLExportStorageClass)
}
[macro_function]
def get_file_info_global(_g_builder : LLVMOpaqueBuilder?; types : PrimitiveTypes?; name : string) : LLVMOpaqueValue? {
let sz = typeinfo sizeof(type<FileInfo>)
let file_info_type = LLVMArrayType(types.t_int8, uint(sz))
let filename_var = "fileinfo_{name}"
var fileInfo = LLVMGetNamedGlobal(g_mod, filename_var)
if (fileInfo == null) {
fileInfo = LLVMAddGlobal(g_mod, file_info_type, filename_var)
set_private_linkage(fileInfo)
var zero = LLVMConstInt(types.t_int8, 0 |> uint64(), 0)
var zeros : array<LLVMValueRef>
zeros |> reserve(sz)
for (_ in range(sz)) {
zeros |> push(zero)
}
let zeroInitializer = LLVMConstArray(types.t_int8, array_data_ptr(zeros), sz |> uint())
LLVMSetInitializer(fileInfo, zeroInitializer)
active_filenames |> insert(name)
}
return fileInfo
}
/*
* Initialize all file info names, fileInfo content still empty.
* @names for all names will be create FileInfo ptr with correct filename
*/
[macro_function]
def generate_fileinfo_ctor_dtor(types : PrimitiveTypes; names : table<string>; jit_mode : bool) {
var ctor_builder = LLVMCreateBuilderInContext(g_ctx)
var dtor_builder = LLVMCreateBuilderInContext(g_ctx)
defer() {
LLVMDisposeBuilder(ctor_builder)
LLVMDisposeBuilder(dtor_builder)
}
let functionType = jit_fn_type($() : void {})
let constructor = LLVMAddFunctionWithType(g_mod, "fileinfo_constructor", functionType)
let destructor = LLVMAddFunctionWithType(g_mod, "fileinfo_destructor", functionType)
if (!jit_mode) {
set_private_linkage(constructor)
set_private_linkage(destructor)
} else {
set_public_linkage(constructor)
set_public_linkage(destructor)
}
let entry_ctor = LLVMAppendBasicBlockInContext(g_ctx, constructor, "entry_ctor")
LLVMPositionBuilderAtEnd(ctor_builder, entry_ctor)
let entry_dtor = LLVMAppendBasicBlockInContext(g_ctx, destructor, "entry_dtor")
LLVMPositionBuilderAtEnd(dtor_builder, entry_dtor)
let void_ptr = types.LLVMVoidPtrType()
// void jit_initialize_fileinfo ( void * fileInfo, char * filename ); void jit_free_fileinfo ( void * fileInfo )
var initializeFuncType = jit_fn_type($(fileInfo, filename : void?) : void {})
var freeFuncType = jit_fn_type($(fileInfo : void?) : void {})
var initializeFunc = LLVMAddFunctionWithType(g_mod, "jit_initialize_fileinfo", initializeFuncType)
var freeFunc = LLVMAddFunctionWithType(g_mod, "jit_free_fileinfo", freeFuncType)
LLVMAddGlobalMapping(g_engine, initializeFunc, get_jit_initialize_fileinfo())
LLVMAddGlobalMapping(g_engine, freeFunc, get_jit_free_fileinfo())
g_fn_types["jit_initialize_fileinfo"] = initializeFuncType
g_fn_types["jit_free_fileinfo"] = freeFuncType
for (name in keys(names)) {
var variable = LLVMGetNamedGlobal(g_mod, "fileinfo_{name}")
assert(variable != null)
var callCtorArgs = array<LLVMValueRef>(
ctor_builder |> LLVMBuildPointerCast(variable, void_ptr, ""),
get_string_constant_ptr(ctor_builder, name)
)
LLVMBuildCall2(ctor_builder, initializeFuncType, initializeFunc, callCtorArgs, "")
var callDtorArgs = array<LLVMValueRef>(
dtor_builder |> LLVMBuildPointerCast(variable, void_ptr, ""),
)
LLVMBuildCall2(dtor_builder, freeFuncType, freeFunc, callDtorArgs, "")
}
LLVMBuildRetVoid(ctor_builder)
LLVMBuildRetVoid(dtor_builder)
return (constructor, destructor)
}
[macro_function]
def get_function_addr(var ctx : Context?; func : Function?) {
let mangled_name = get_mangled_name(func)
let MNH = hash(mangled_name)
// return unsafe(reinterpret<void?>(get_function_address(MNH, *ctx)))
let MNH_ADDR = get_function_address(MNH, *ctx)
if (MNH_ADDR == 0 |> uint64) {
failed("missing function pointer for {func.name}")
}
return unsafe(reinterpret<void?>(MNH_ADDR))
}
// Check if a function is a late-bound dasbind function (null builtin address, resolvable at runtime)
[macro_function]
def is_dasbind_late(func : Function?) : bool {
if (func == null || !func.flags.builtIn || func._module.name != "dasbind") return false
var hit = false
peek(func.name) $(s) {
hit = starts_with(s, "__dasbind__")
}
return hit
}
// Codegen mode: how function/global symbols are emitted. Distinct from the run_jit output concern
// (DLL cache vs in-memory vs wasm), which all share JIT symbol emission.
enum public LlvmJitMode {
JIT //!< in-process JIT / DLL cache: bake host addresses, public symbols
EXE //!< standalone exe: private symbols; globals null, resolved by initialize_modules at startup
LLVM_AOT //!< offline AOT object: private symbols; globals null, re-resolved by a load ctor (host owns modules)
}
bitfield public LlvmJitFlags {
// Whether prologue should be forced for every function.
emit_prologue,
// Is debug info needed. Debug info not fully supported and not tested yet.
need_di,
}
// Non-string workhorse key types that get the inline open-addressed find/at (build_workhorse_*):
// the integer family plus bool / float / double. Everything else routes to the C++ table find/at.
def public is_workhorse_table_key(t : Type) : bool {
return (t == Type.tInt || t == Type.tUInt || t == Type.tInt64 || t == Type.tUInt64
|| t == Type.tInt8 || t == Type.tUInt8 || t == Type.tInt16 || t == Type.tUInt16
|| t == Type.tBool || t == Type.tFloat || t == Type.tDouble)
}
// Per-source state of an inline `keys(tab)` / `values(tab)` slot walk over a workhorse-keyed table:
// set up by first(), advanced by next(), torn down by emit_iterator_close. Non-string keys are
// open-addressed at every capacity (1-byte CTRL), so the walk is a flat `ctrl[slot] > TOMBSTONE` scan.
struct TableWalkState {
slot : LLVMOpaqueValue? // alloca i64 — current slot cursor
cap : LLVMOpaqueValue? // i64 capacity, loaded once at first()
ctrlPtr : LLVMOpaqueValue? // i8* — open-addressed control bytes
basePtr : LLVMOpaqueValue? // typed keys* (keys lane) / i8* data (values lane)
origin : LLVMOpaqueValue? // raw KEYS/DATA at first() — modified-during-iteration check
tabPtr : LLVMOpaqueValue? // Table* — unlock + the origin recheck at close
isKeys : bool
stride : int // value stride in bytes (values lane; keys GEP by element type)
}
[macro]
class public LlvmJitVisitor : AstVisitor {
adapter : VisitorAdapter?
e2v : table<Expression?; LLVMOpaqueValue?>
// nolint:STYLE014
// makeArrayOnHeap literals: stack of arr.data buffer bases for heap make-arrays currently being
// built. getE(expr) holds the Array struct (the expression result); the top of this stack is where
// element make-local cmres writes go, mirroring interp's abiCMRES redirect in SimNode_MakeArrayHeap.
// LIFO matches visitor recursion, so nested `[[..],[..]]` just push/pop (no per-expr bookkeeping).
heapMkaData : array<LLVMOpaqueValue?>
v2v : table<Variable?; LLVMOpaqueValue?>
v2t : table<LLVMOpaqueValue?; LLVMOpaqueType?>
call2cmres : table<Expression?; LLVMOpaqueValue?>
ffunc, wfunc : LLVMOpaqueValue?
ite2blocks : table<Expression?; IteBlock>
thisFunc : Function?
uid : UidNodes? // function counter. Use it to create uid's for different names in dll.
thisBlock : ExprBlock?
subblocks : table<LLVMOpaqueBasicBlock?; LLVMOpaqueBasicBlock?>
loop_stack : array<LoopBlock>
block_stack : array<ExprBlock?>
jit_context : Context?
function_entry : LLVMOpaqueBasicBlock?
function_body : LLVMOpaqueBasicBlock?
monad2block : table<Expression?; LLVMOpaqueBasicBlock?>
prologue : LLVMOpaqueValue?
labels : table<int; LLVMOpaqueBasicBlock?>
sortedLabels : array<SLabel>
finallyBlocks : table<ExprBlock?; LLVMOpaqueBasicBlock?>
afterFinallyBlocks : table<ExprBlock?; array<LLVMOpaqueBasicBlock?>>
forBodyToExpr : table<ExprBlock?; ExprFor?> // for-loop body block -> ExprFor (for iterator close on return path)
skipCall : table<ExprCall?>
range2 : table<Expression?; LLVMOpaqueValue?> // for loop - range - where to
tableWalk : table<Expression?; TableWalkState> // for loop - inline table slot-walk sources
callBlock : LLVMOpaqueValue?
g_builder : LLVMOpaqueBuilder?
g_di_builder : LLVMOpaqueDIBuilder?
di_file_location : table<string; LLVMOpaqueMetadata?>
di_function : LLVMOpaqueMetadata?
types : PrimitiveTypes -const? -const
option_no_range_check : bool = false
option_no_alias : bool = false
option_no_capture : bool = false
// True once any ExprCall to a builtIn function has been emitted, i.e. this
// function pulls in libDaScript_runtime.
has_externals : bool = false
flags : LlvmJitFlags
mode : LlvmJitMode
own_di : bool = false
ldu_hint : bool
attributes : Attributes?
def LlvmJitVisitor(ctx : Context?; types_ : PrimitiveTypes?; uids : UidNodes?; flags_ : LlvmJitFlags; mode_ : LlvmJitMode; dib : LLVMOpaqueDIBuilder?; attrs : Attributes?) {
jit_context = ctx
types = types_
g_builder = LLVMCreateBuilderInContext(g_ctx)
g_di_builder = dib
flags = flags_
mode = mode_
attributes = attrs
uid = uids
if (flags.need_di) {
own_di = true
g_di_builder = LLVMCreateDIBuilder(g_mod)
// One CU per DIBuilder (LLVM asserts on a second). DIBuilder remembers it and
// stamps `unit:` on every subprogram definition; per-function DIFiles carry the
// real .das paths, so the CU's own file name is just a label.
let cu_name = "das-jit"
let producer = "daslang jit"
let cu_file = LLVMDIBuilderCreateFile(g_di_builder, cu_name, uint64(long_length(cu_name)), "", 0ul)
LLVMDIBuilderCreateCompileUnit(g_di_builder, LLVMDWARFSourceLanguage.C, cu_file,
producer, uint64(long_length(producer)), 0, "", 0ul, 0u, "", 0ul,
LLVMDWARFEmissionKind.LLVMDWARFEmissionFull, 0u, 0, 0, "", 0ul, "", 0ul)
}
}
def finalize {
if (own_di && g_di_builder != null) {
LLVMDIBuilderFinalize(g_di_builder)
LLVMDisposeDIBuilder(g_di_builder)
}
LLVMDisposeBuilder(g_builder)
}
// Debug info
def const debug_info_enabled() {
return g_di_builder != null
}
def debug_before_function(fun : FunctionPtr) {
if (debug_info_enabled()) {
clear_builder_location()
let unit = get_debug_file_location(fun.at)
let implName = uid.get_dll_fn_name(fun).impl()
// Untyped subroutine (no param/return DI types yet) — enough for line tables.
var ty = LLVMDIBuilderCreateSubroutineType(
g_di_builder, unit, null, 0u, LLVMDIFlags.LLVMDIFlagZero)
di_function = LLVMDIBuilderCreateFunction(g_di_builder, unit,
implName, uint64(long_length(implName)), "", 0ul, unit, fun.at.line,
ty, 1, 1, fun.at.line, LLVMDIFlags.LLVMDIFlagZero, 0)
LLVMSetSubprogram(ffunc, di_function)
}
}
def debug_after_function {
clear_builder_location()
}
def set_globalvar_linkage(value : LLVMOpaqueValue?) {
if (flags.need_di) {
set_debug_linkage(value)
} else {
set_private_linkage(value)
}
}
def get_debug_file_location(at : LineInfo) : LLVMOpaqueMetadata? {
if (debug_info_enabled()) {
let filename = at.fileInfo != null ? string(at.fileInfo.name) : ""
return get_debug_file_location_by_name(filename)
} else {
return null
}
}
def get_debug_file_location_by_name(filename : string) : LLVMOpaqueMetadata? {
var meta & = unsafe(di_file_location[filename])
if (meta == null) {
// filename already carries its path; a non-empty directory would make CodeView
// consumers print the dir twice (dir/dir/file) when they join the two fields
meta = LLVMDIBuilderCreateFile(g_di_builder, filename, uint64(long_length(filename)), "", 0ul)
}
return meta
}
def get_debug_location(at : LineInfo) : LLVMOpaqueMetadata? {
if (debug_info_enabled()) {
let file_meta = get_debug_file_location(at)
return LLVMDIBuilderCreateDebugLocation(g_ctx, at.line, at.column, di_function, null)
} else {
return null
}
}
def set_builder_location(at : LineInfo) {
if (debug_info_enabled()) {
if (di_function != null) {
LLVMSetCurrentDebugLocation2(g_builder, get_debug_location(at))
}
}
}
def clear_builder_location {
if (debug_info_enabled()) {
LLVMSetCurrentDebugLocation2(g_builder, null)
}
}
// Expression
def override preVisitExpression(expr : ExpressionPtr) : void {
set_builder_location(expr.at)
}
// Function
def build_noalias_list(annotations : AnnotationList) : tuple<noalias : table<string>; nocapture : table<string>> {
var noalias : table<string>
var nocapture : table<string>
// Skip user hints entirely on wasm32 — host-LLVM wasm codegen has had
// miscompiles around them. Tracked alongside the alwaysinline gotcha.
if (g_target_is_wasm) return <- (noalias <- noalias, nocapture <- nocapture)
for (ann in annotations) {
if (ann.annotation.name == "hint") {
for (arg in ann.arguments) {
if (arg.name == "noalias") {
if (arg.basicType == Type.tString) {
noalias |> insert(string(arg.sValue))
}
} elif (arg.name == "nocapture") {
if (arg.basicType == Type.tString) {
nocapture |> insert(string(arg.sValue))
}
}
}
}
}
return <- (noalias <- noalias, nocapture <- nocapture)
}
def append_basic_block(name : string) {
return LLVMAppendBasicBlockInContext(g_ctx, ffunc, name)
}
def process_function_hints(annotations : AnnotationList; var arguments : dasvector`ptr`Variable) {
var alwaysInline = false
var noInline = false
var optNone = false
var hot = false
var cold = false
var mustProgress = false
var minSize = false
var noFree = false
var noRecurse = false
option_no_range_check = false
option_no_alias = false
option_no_capture = false
// Bypass user hints on wasm — keeps option_no_* flags false (= safe
// defaults: bounds checks on, no alias/capture assumption) and skips
// every LLVMAddAttributeToFunction call below. See g_target_is_wasm.
if (g_target_is_wasm) return
for (ann in annotations) {
if (ann.annotation.name == "hint") {
for (arg in ann.arguments) {
if (arg.name == "alwaysinline") {
alwaysInline = true
}
if (arg.name == "noinline") {
noInline = true
} elif (arg.name == "optnone") {
optNone = true
} elif (arg.name == "hot") {
hot = true
} elif (arg.name == "cold") {
cold = true
} elif (arg.name == "mustprogress") {
mustProgress = true
} elif (arg.name == "minsize") {
minSize = true
} elif (arg.name == "nofree") {
noFree = true
} elif (arg.name == "norecurse") {
noRecurse = true
} elif (arg.name == "unsafe_range_check") {
option_no_range_check = true
} elif (arg.name == "unsafe_alias") {
option_no_alias = true
} elif (arg.name == "unsafe_capture") {
option_no_capture = true
} elif (arg.name == "align16" && arg.basicType == Type.tString) {
for (a, ai in arguments, ucount()) {
if (a.name == arg.sValue) {
LLVMSetParamAlignment(LLVMGetParam(ffunc, ai), 16u)
}
}
} elif (arg.name == "vec3_ldu") {
LLVM_JIT_ALLOW_UNALIGNED_VECTOR_READ_OUT_OF_BOUNDS = arg.bValue
}
}
}
}
if (alwaysInline) {
LLVMAddAttributeToFunction(ffunc, attributes.alwaysinline)
} elif (noInline) {
LLVMAddAttributeToFunction(ffunc, attributes.noinline)
}
if (hot) {
LLVMAddAttributeToFunction(ffunc, attributes.hot)
}
if (cold) {
LLVMAddAttributeToFunction(ffunc, attributes.cold)
}
if (mustProgress) {
LLVMAddAttributeToFunction(ffunc, attributes.mustprogress)
}
if (minSize) {
LLVMAddAttributeToFunction(ffunc, attributes.minsize)
}
if (noFree) {
LLVMAddAttributeToFunction(ffunc, attributes.nofree)
}
if (noRecurse) {
LLVMAddAttributeToFunction(ffunc, attributes.norecurse)
}
if (optNone) {
if (alwaysInline) {
failed("Attribute 'optnone' can't be mixed with 'alwaysinline'!")
}
LLVMAddAttributeToFunction(ffunc, attributes.optnone)
LLVMAddAttributeToFunction(ffunc, attributes.noinline)
}
}
def process_finally(expr : ExpressionPtr) {
var blk <- collect_finally(expr, false)
sort(blk) <| $(a, b) => uid.get_block_name_ptr(a).publ() < uid.get_block_name_ptr(b).publ()
for (bl in blk) {
finallyBlocks[bl] = append_basic_block("finally_block_at_{int(bl.at.line)}_")
}
if (!empty(blk)) {
at_function_entry() {
callBlock = LLVMBuildAlloca(g_builder, LLVMPointerType(types.t_int8, 0u), "call_block")
LLVMBuildStore(g_builder, LLVMConstNull(LLVMPointerType(types.t_int8, 0u)), callBlock)
}
}
}
def process_labels(expr : ExpressionPtr) {
var lls <- collect_labels(expr)
sort(lls)
for (ll in lls) {
labels[ll] = append_basic_block("label_{ll}_")
}
sortedLabels |> reserve(length(labels))
for (k, v in keys(labels), values(labels)) {
sortedLabels |> push(SLabel(index = k, blk = v))
}
sort(sortedLabels) $(a, b) {
return a.index < b.index
}
}
def build_llvm_function_pair(fun_name : DllName; isCmres : bool; arguments : dasvector`ptr`Variable; result : TypeDeclPtr; captureType : LLVMOpaqueType?; annotations : AnnotationList) {
var inscope nat <- build_noalias_list(annotations)
// implementation function
var fun_args <- [for (a in arguments); type_to_llvm_abi_type(a._type)]
if (captureType != null) {
fun_args |> push(LLVMPointerType(captureType, 0u)) // capture
}
fun_args |> push(types.LLVMVoidPtrType()) // context
var fun_type : LLVMOpaqueType?
if (isCmres) {
fun_args |> push(types.LLVMVoidPtrType()) // CMRES
fun_type = LLVMFunctionType(types.t_void, fun_args)
} else {
fun_type = LLVMFunctionType(type_to_llvm_abi_type(result), fun_args)
}
if (LLVMGetNamedFunction(g_mod, fun_name.impl()) != null) {
to_log(LOG_ERROR, "LLVM JIT: Function {fun_name.impl()} somehow already present!")
failed("Function {fun_name.impl()} somehow already present!")
}
ffunc = LLVMAddFunctionWithType(g_mod, fun_name.impl(), fun_type)
if (flags.need_di) {
set_debug_linkage(ffunc)
} else {
set_private_linkage(ffunc)
}
if (!isCmres) {
// Add zero/sign extension when necessary. Otherwise
// it may lead to hardly reproducible bugs on c++ side.
let ret_ext = need_z_or_s_ext(result)
if (ret_ext != null) {
LLVMAddAttributeAtIndex(ffunc, 0u, ret_ext)
}
}
// setup parameter alignment
for (a, ai in arguments, ucount()) {
var param = LLVMGetParam(ffunc, ai)
if (a._type.isRef) {
LLVMSetParamAlignment(param, uint(a._type.alignOf))
} elif (a._type.isPointer && a._type.firstType != null) {
LLVMSetParamAlignment(param, uint(a._type.firstType.alignOf))
}
LLVMSetValueName(param, string(a.name))
if ((a._type.isRef || a._type.isPointer || a._type.isString) && a._type.flags.constant) {
LLVMAddAttributeToFunctionArgument(ffunc, ai, attributes.readonly)
}
if (option_no_alias || nat.noalias |> key_exists(string(a.name))) {
LLVMAddAttributeToFunctionArgument(ffunc, ai, attributes.noalias)
}
if (option_no_capture || nat.nocapture |> key_exists(string(a.name))) {
LLVMAddAttributeToFunctionArgument(ffunc, ai, attributes.nocapture)
}
}
// noalias of the capture target, context, result
var nai = uint(length(arguments))
if (captureType != null) {
LLVMAddAttributeToFunctionArgument(ffunc, nai, attributes.nocapture)
LLVMAddAttributeToFunctionArgument(ffunc, nai++, attributes.noalias) // capture target
}
LLVMAddAttributeToFunctionArgument(ffunc, nai, attributes.nocapture)
LLVMAddAttributeToFunctionArgument(ffunc, nai++, attributes.noalias) // context
if (isCmres) {
LLVMAddAttributeToFunctionArgument(ffunc, nai, attributes.nocapture)
LLVMAddAttributeToFunctionArgument(ffunc, nai++, attributes.noalias) // cmres
}
// alignment of the context and the result
LLVMSetParamAlignment(get_context_param(), 16u)
if (isCmres) {
LLVMSetParamAlignment(get_cmres_param(), uint(result.alignOf))
}
// wrapper function
var ret_type : LLVMOpaqueType?
if (captureType != null) {
ret_type = LLVMFunctionType(types.LLVMFloat4Type(),
fixed_array<LLVMTypeRef>(types.LLVMVoidPtrType(), // context
LLVMPointerType(types.LLVMFloat4Type(), 0u), // args
types.LLVMVoidPtrType(), // cmres
LLVMPointerType(captureType, 0u) // block
))
} else {
ret_type = LLVMFunctionType(types.LLVMFloat4Type(),
fixed_array<LLVMTypeRef>(types.LLVMVoidPtrType(), // context
LLVMPointerType(types.LLVMFloat4Type(), 0u), // args
types.LLVMVoidPtrType() // cmres
))
}
wfunc = LLVMAddFunctionWithType(g_mod, fun_name.publ(), ret_type)
if (mode != LlvmJitMode.JIT) {
// todo: we shouldn't generate public function `wfunc`
// at all when gen_exe enabled.
// But it requires some refactoring.
set_private_linkage(wfunc)
} else {
set_public_linkage(wfunc)
}
LLVMSetParamAlignment(LLVMGetParam(wfunc, 0u), 16u)
LLVMSetParamAlignment(LLVMGetParam(wfunc, 1u), 16u)
if (isCmres) {
LLVMSetParamAlignment(LLVMGetParam(wfunc, 2u), uint(result.alignOf))
}
if (captureType != null) {
LLVMSetParamAlignment(LLVMGetParam(wfunc, 3u), 16u)
}
}
def add_llvm_functions(fun : FunctionPtr) {
thisFunc = fun
let fnmna = uid.get_dll_fn_name(fun)
build_llvm_function_pair(fnmna, isCMRES(fun), fun.arguments, fun.result, null, fun.annotations)
thisFunc = null
}
// [llvm_code(name="key")] path: the registered das generator (llvm_jit_code registry) emits the
// impl body wholesale; only the public wrapper comes from the signature. Returns true when fully
// handled (generated or hard-errored via failed()); false = generator declines, caller falls to normal body codegen.
def try_llvm_code_function(fun : FunctionPtr) : bool {
register_user_llvm_code_generators() // direct call: registrations land in THIS context's registry
let ann = find_llvm_code_annotation(fun)
let gen_name = llvm_code_generator_name(ann)
if (empty(gen_name)) {
failed("[llvm_code] on {fun.name}: missing name=\"...\" argument")
return true
}
if (!has_llvm_code_generator(gen_name)) {
failed("[llvm_code] on {fun.name}: no generator registered under '{gen_name}' — is its module required from llvm/daslib/llvm_user_modules.das?")
return true
}
let fnmna = uid.get_dll_fn_name(fun)
ffunc = LLVMGetNamedFunction(g_mod, fnmna.impl())
wfunc = LLVMGetNamedFunction(g_mod, fnmna.publ())
var gc = LlvmCodeCtx(jit = JitCtx(ctx = g_ctx, builder = g_builder, types = types),
fn = fun, impl = ffunc, impl_type = g_fn_types[fnmna.impl()], ann = ann)
let generated = invoke_llvm_code_generator(gen_name, gc)
if (generated) {
build_wrapper_function(fnmna, fun.arguments, clone_type(fun.result), isCMRES(fun), null, fun.at)
}
ffunc = null
wfunc = null
return generated
}
def build_wrapper_function(fnmna : DllName; arguments : dasvector`ptr`Variable; var result : TypeDeclPtr; isCmres : bool; captureType : LLVMOpaqueType?; at : LineInfo) {
var wentry = LLVMAppendBasicBlockInContext(g_ctx, wfunc, "entry")
LLVMPositionBuilderAtEnd(g_builder, wentry)
if (debug_info_enabled()) {
// The wrapper needs its own DISubprogram: at O2+ the impl often inlines into
// it, and LLVM drops the callee's !dbg when the host has no debug scope.
let unit = get_debug_file_location(at)
let publName = fnmna.publ()
var wty = LLVMDIBuilderCreateSubroutineType(g_di_builder, unit, null, 0u, LLVMDIFlags.LLVMDIFlagZero)
let wsp = LLVMDIBuilderCreateFunction(g_di_builder, unit,
publName, uint64(long_length(publName)), "", 0ul, unit, at.line,
wty, 0, 1, at.line, LLVMDIFlags.LLVMDIFlagZero, 0)
LLVMSetSubprogram(wfunc, wsp)
LLVMSetCurrentDebugLocation2(g_builder,
LLVMDIBuilderCreateDebugLocation(g_ctx, at.line, at.column, wsp, null))
}
var wargs : array<LLVMOpaqueValue?>
var args = LLVMGetParam(wfunc, 1u)
for (a, ai in arguments, count()) {
var arg_ptr = LLVMBuildGEP2(g_builder, types.LLVMFloat4Type(), args, types.ConstI32(uint64(ai)), "arg_ptr_{ai}")
var arg_type = type_to_llvm_abi_type(a._type)
arg_ptr = LLVMBuildPointerCast(g_builder, arg_ptr, LLVMPointerType(arg_type, 0u), "")
var arg_v : LLVMOpaqueValue?
if (a._type.isVoid) {
pass
} elif (a._type.flags.ref) {
arg_v = LLVMBuildLoadData2Aligned(g_builder, arg_type, arg_ptr, a._type.alignOf, "arg_ref_value_{ai}")
} elif (!a._type.isRef) {
arg_v = LLVMBuildLoadData2Aligned(g_builder, arg_type, arg_ptr, a._type.alignOf, "arg_value_{ai}")
} else {
arg_v = LLVMBuildLoadData2Aligned(g_builder, arg_type, arg_ptr, a._type.alignOf, "arg_any_{ai}")
}
if (arg_v != null) {
wargs |> push(arg_v)
}
}
if (captureType != null) {
wargs |> push(LLVMGetParam(wfunc, 3u)) // block
}
wargs |> push(LLVMGetParam(wfunc, 0u)) // context
if (isCmres) {
wargs |> push(LLVMGetParam(wfunc, 2u)) // cmres
}
var ret_v = LLVMBuildCall2(g_builder, g_fn_types[(fnmna.impl())], ffunc, wargs, "")
if (!result.isVoid) {
if (isCmres) {
LLVMBuildRet(g_builder, cast_ptr_to_vec4f(LLVMGetParam(wfunc, 2u)))
} else {
var tres = cast_to_vec4f(result, ret_v)
if (tres != null) {
LLVMBuildRet(g_builder, tres)
} else {
LLVMBuildRet(g_builder, LLVMGetUndef(types.LLVMFloat4Type()))
}
}
} else {
LLVMBuildRet(g_builder, LLVMGetUndef(types.LLVMFloat4Type()))
}
// Wrapper-scoped location must not leak onto the next function's entry code.
clear_builder_location()
}
def create_line_info_global(at : LineInfo; dummy : LLVMOpaqueValue?) {
let uint8_ptr = LLVMPointerType(types.t_int8, 0u)
let line_info_type = jit_struct_type(type<tuple<fileName : void?; column : int; line : int; lastColumn : int; lastLine : int>>)
let line_info_global = LLVMAddGlobal(g_mod, line_info_type, "li_{int(at.line)}_{int(at.column)}")
set_globalvar_linkage(line_info_global)
var init_values = fixed_array(g_builder |> LLVMBuildPointerCast(dummy, uint8_ptr, ""),
types.ConstI32(at.column |> uint64()),
types.ConstI32(at.line |> uint64()),
types.ConstI32(at.last_column |> uint64()),
types.ConstI32(at.last_line |> uint64())
)
let line_info_init = LLVMConstStructInContext(g_ctx, array_data_ptr(init_values), init_values |> length() |> uint(), 0)
LLVMSetInitializer(line_info_global, line_info_init)
return line_info_global
}
def create_line_info_ptr_global(line_info_global : LLVMOpaqueValue?) {
let uint8_ptr = LLVMPointerType(LLVMPointerType(types.t_int8, 0u), 0u)
let line_info_ptr_type = uint8_ptr
let line_info_ptr_global = LLVMAddGlobal(g_mod, line_info_ptr_type, "li_ptr" /* no name */)
set_globalvar_linkage(line_info_ptr_global)
LLVMSetInitializer(line_info_ptr_global, line_info_global)
return line_info_ptr_global
}
def instrument_and_map_global(at : LineInfo; line_info_ptr_global : LLVMOpaqueValue?) {
let info_ptr = instrument_line_info(at) // pointer in 'code' of the context
g_engine |> LLVMAddGlobalMapping(line_info_ptr_global, info_ptr)
return line_info_ptr_global
}
def get_line_info_ptr(at : LineInfo) {
let void_ptr = types.LLVMVoidPtrType()
let fi = get_file_info_global(g_builder, types, at.fileInfo != null ? string(at.fileInfo.name) : "unknown_filename")
let line_info_global = create_line_info_global(at, fi)
let line_info_ptr_global = create_line_info_ptr_global(line_info_global)
instrument_and_map_global(at, line_info_ptr_global)
var loaded_ptr = LLVMBuildLoad2(g_builder, void_ptr, line_info_ptr_global, "")
// return g_builder |> LLVMBuildPointerCast(loaded_ptr, void_ptr, "")
return loaded_ptr
}
def build_function_entry(funAt : LineInfo;
bodyId : uint64; need_prologue : bool;
var totalStackSize : uint;
var arguments : dasvector`ptr`Variable) {
if (need_prologue && totalStackSize < SIZE_OF_PROLOGUE) {
totalStackSize = SIZE_OF_PROLOGUE
}
// now write to regular function
function_entry = append_basic_block("entry")
LLVMPositionBuilderAtEnd(g_builder, function_entry)
// enter
build_enter(funAt)
// allocate prologue if need be
if (need_prologue) {
prologue = LLVMBuildAlloca(g_builder, g_t_stack_state, "prologue")
prologue = LLVMBuildPointerCast(g_builder, prologue, LLVMPointerType(g_t_stack_state, 0u), "")
var params = fixed_array(
get_string_constant_ptr(g_builder, "{thisFunc.name}"),
get_line_info_ptr(funAt),
types.ConstI32(uint64(totalStackSize)),
prologue,
get_context_param(),
get_line_info_ptr(funAt) // at — used for stack-overflow throw
)
var typ = g_fn_types[FN_JIT_PROLOGUE]
LLVMBuildCall2(g_builder, typ, LLVMGetNamedFunction(g_mod, FN_JIT_PROLOGUE), params, "")
}
// allocate arguments (promoted to local variables). hasMakeBlock forces always-promote so
// block-captured argument variables are addressable; could be narrowed to captured-only.
var alwaysPromote = false
if (thisBlock != null && thisBlock.blockFlags.hasMakeBlock) {
alwaysPromote = true
} elif (thisFunc != null && thisFunc.flags.hasMakeBlock) {
alwaysPromote = true
}
for (a, ai in arguments, range(10050)) {
if ((alwaysPromote || a.access_flags.access_ref || a.access_flags.access_pass) && !a._type.isRef) {
var tryV = LLVMBuildAlloca(g_builder, type_to_llvm_abi_type(a._type), "var_{a.name}")
LLVMSetAlignment(tryV, 16u)
LLVMBuildStore(g_builder, LLVMGetParam(ffunc, uint(ai)), tryV)
setV(a, tryV)
}
}
// function body
function_body = append_basic_block("body_{bodyId}")
LLVMPositionBuilderAtEnd(g_builder, function_body)
}
def override canVisitFunctionArgumentInit(fun : Function?; arg : VariablePtr; value : ExpressionPtr) : bool {
return false
}
def override preVisitFunction(var fun : FunctionPtr) : void {
assert(g_builder != null, "missing builder")
thisFunc = fun
uid.reset(fun)
ldu_hint = LLVM_JIT_ALLOW_UNALIGNED_VECTOR_READ_OUT_OF_BOUNDS
let fnmna = uid.get_dll_fn_name(fun)
ffunc = LLVMGetNamedFunction(g_mod, fnmna.impl())
wfunc = LLVMGetNamedFunction(g_mod, fnmna.publ())
// build wrapper function
build_wrapper_function(fnmna, fun.arguments, fun.result, isCMRES(fun), null, fun.at)
build_function_entry(fun.at, hash(get_mangled_name(fun)),
fun.flags.hasMakeBlock || flags.emit_prologue,
fun.totalStackSize, fun.arguments)
process_function_hints(fun.annotations, fun.arguments)
process_labels(fun.body)
process_finally(fun.body)
debug_before_function(fun)
set_builder_location(fun.at)
}
def build_epilogue {
if (prologue != null) {
var params = fixed_array(
prologue,
get_context_param()
)
var typ = g_fn_types[FN_JIT_EPILOGUE]
LLVMBuildCall2(g_builder, typ, LLVMGetNamedFunction(g_mod, FN_JIT_EPILOGUE), params, "")
}
}
def current_block_terminates {
return LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(g_builder)) != null
}
def override visitFunction(fun : FunctionPtr) : FunctionPtr {
LLVMPositionBuilderAtEnd(g_builder, function_entry)
LLVMBuildBr(g_builder, function_body)
debug_after_function()
LLVM_JIT_ALLOW_UNALIGNED_VECTOR_READ_OUT_OF_BOUNDS = ldu_hint
ffunc = null
thisFunc = null
uid.reset(null)
return fun
}
// ExprBlock
def add_default_terminator(blk : ExprBlock?) {
if ((thisBlock == null && thisFunc != null && thisFunc.body != blk)
|| (thisBlock != null && thisBlock != blk)) return
if (!current_block_terminates()) {
call_all_finally_blocks("default_terminator", false)
build_exit(blk.at)
if (thisBlock != null && thisBlock.returnType != null && !thisBlock.returnType.isVoid) {
LLVMBuildUnreachable(g_builder)
} elif (thisBlock == null && thisFunc != null && thisFunc.result != null && !thisFunc.result.isVoid) {
LLVMBuildUnreachable(g_builder)
} else {
build_epilogue()
LLVMBuildRetVoid(g_builder)
}
}
}
def hasFinalSection(blk : ExprBlock?) {
if (blk == null) return false
return !empty(blk.finalList)
}
def has_any_finally_block(stopAtLoop : bool) {
let len = length(block_stack)
for (i in range(len)) {
var blk = block_stack[len - 1 - i]
if (stopAtLoop && blk.blockFlags.inTheLoop) break
if (blk |> hasFinalSection()) return true
}
return false
}
def call_all_finally_blocks(from_where : string; stopAtLoop : bool) {
let len = length(block_stack)
var anyFinallyBlocks = false
for (i in range(len)) {
var blk = block_stack[len - 1 - i]
let atLoopBoundary = stopAtLoop && (blk.blockFlags.inTheLoop || blk.blockFlags.forLoop)
if (blk |> hasFinalSection()) {
var after = append_basic_block("{from_where}_after_call_finally_block_{int(blk.at.line)}")
var after_ptr = LLVMBlockAddress(LLVMGetBasicBlockParent(after), after)
LLVMBuildStore(g_builder, after_ptr, callBlock)
var fblk = finallyBlocks[blk]
LLVMBuildBr(g_builder, fblk)
LLVMPositionBuilderAtEnd(g_builder, after)
afterFinallyBlocks[blk] |> push(after)
anyFinallyBlocks = true
}
// For return paths that bypass loop_end (stopAtLoop=false), emit iterator-close
// for each enclosing for-loop body. break/continue route through loop_end/loop_continue
// which already handle close, so skip there.
if (!stopAtLoop && blk.blockFlags.forLoop && key_exists(forBodyToExpr, blk)) {
emit_iterator_close(forBodyToExpr[blk])
}
if (atLoopBoundary) break
}
return anyFinallyBlocks
}
def override preVisitExprBlock(var blk : ExprBlock?) : void {
block_stack |> push(blk)
}
def override preVisitExprBlockExpression(blk : ExprBlock?; expr : ExpressionPtr) : void {
if (LLVM_DEBUG_TRACES && LLVM_DEBUG_LINE_TRACES) {
if (!current_block_terminates()) {
build_debug_trace(expr.at, FN_JIT_DEBUG_LINE)
}
}
}
def override preVisitExprBlockFinal(blk : ExprBlock?) : void {
add_default_terminator(blk)
if (finallyBlocks |> key_exists(blk)) {
var fblk = finallyBlocks[blk]
if (!current_block_terminates()) {
LLVMBuildStore(g_builder, LLVMConstNull(LLVMPointerType(types.t_int8, 0u)), callBlock)
LLVMBuildBr(g_builder, fblk)
}
LLVMPositionBuilderAtEnd(g_builder, fblk)
}
}
def jump_to_next_finally(blk : ExprBlock?) {
afterFinallyBlocks |> get(blk) $(AfterFinallyBlocks) {
if (!empty(AfterFinallyBlocks)) {
var cc = LLVMBuildLoad2(g_builder, LLVMPointerType(types.t_int8, 0u), callBlock, "")
let needCond = thisFunc.body != blk && thisBlock != blk
var do_jump, skip_jump : LLVMOpaqueBasicBlock?
if (needCond) {
do_jump = append_basic_block("do_jump_blk_line_{int(blk.at.line)}_")
skip_jump = append_basic_block("skip_jump_blk_line_{int(blk.at.line)}_")
var not_null = LLVMBuildICmp(g_builder, LLVMIntPredicate.LLVMIntNE, cc, LLVMConstNull(LLVMPointerType(types.t_int8, 0u)), "")
LLVMBuildCondBr(g_builder, not_null, do_jump, skip_jump)
LLVMPositionBuilderAtEnd(g_builder, do_jump)
}
var indb = LLVMBuildIndirectBr(g_builder, cc, uint(length(AfterFinallyBlocks)))
for (bb in AfterFinallyBlocks) {
LLVMAddDestination(indb, bb)
}
if (skip_jump != null) {
LLVMPositionBuilderAtEnd(g_builder, skip_jump)
}
}
}