-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
codegen.cpp
7975 lines (7478 loc) · 332 KB
/
codegen.cpp
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
// This file is a part of Julia. License is MIT: https://julialang.org/license
#include "llvm-version.h"
#include "platform.h"
#include "options.h"
#if defined(_OS_WINDOWS_)
// use ELF because RuntimeDyld COFF i686 support didn't exist
// use ELF because RuntimeDyld COFF X86_64 doesn't seem to work (fails to generate function pointers)?
#define FORCE_ELF
#endif
#if defined(_CPU_X86_)
#define JL_NEED_FLOATTEMP_VAR 1
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include <setjmp.h>
#include <string>
#include <sstream>
#include <fstream>
#include <map>
#include <array>
#include <vector>
#include <set>
#include <cstdio>
#include <iostream>
#include <functional>
// target machine computation
#include <llvm/CodeGen/TargetSubtargetInfo.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Object/SymbolSize.h>
// IR building
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/Object/ObjectFile.h>
#include <llvm/IR/DIBuilder.h>
#include <llvm/AsmParser/Parser.h>
#include <llvm/DebugInfo/DIContext.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/Attributes.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/MDBuilder.h>
// support
#include <llvm/ADT/SmallBitVector.h>
#include <llvm/ADT/Optional.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/SourceMgr.h> // for llvmcall
#include <llvm/Transforms/Utils/Cloning.h> // for llvmcall inlining
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/IR/Verifier.h> // for llvmcall validation
#include <llvm/Bitcode/BitcodeWriter.h>
// C API
#include <llvm-c/Types.h>
// for configuration options
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/IR/InlineAsm.h>
#if defined(_CPU_ARM_) || defined(_CPU_AARCH64_)
# include <sys/utsname.h>
#endif
#if defined(USE_POLLY)
#include <polly/RegisterPasses.h>
#include <polly/ScopDetection.h>
#endif
#include <llvm/ExecutionEngine/ExecutionEngine.h>
using namespace llvm;
#if JL_LLVM_VERSION >= 80000
typedef Instruction TerminatorInst;
#endif
#if defined(_OS_WINDOWS_) && !defined(NOMINMAX)
#define NOMINMAX
#endif
#include "julia.h"
#include "julia_internal.h"
#include "jitlayers.h"
#include "codegen_shared.h"
#include "processor.h"
#include "julia_assert.h"
// LLVM version compatibility macros
legacy::PassManager *jl_globalPM;
#define DIFlagZero (DINode::FlagZero)
extern "C" {
#include "builtin_proto.h"
#ifdef HAVE_SSP
extern uintptr_t __stack_chk_guard;
extern void __stack_chk_fail();
#else
JL_DLLEXPORT uintptr_t __stack_chk_guard = (uintptr_t)0xBAD57ACCBAD67ACC; // 0xBADSTACKBADSTACK
JL_DLLEXPORT void __stack_chk_fail()
{
/* put your panic function or similar in here */
fprintf(stderr, "fatal error: stack corruption detected\n");
gc_debug_critical_error();
abort(); // end with abort, since the compiler destroyed the stack upon entry to this function, there's no going back now
}
#endif
#ifdef _OS_WINDOWS_
#if defined(_CPU_X86_64_)
#if defined(_COMPILER_MINGW_)
extern void ___chkstk_ms(void);
#else
extern void __chkstk(void);
#endif
#else
#if defined(_COMPILER_MINGW_)
#undef _alloca
extern void _alloca(void);
#else
extern void _chkstk(void);
#endif
#endif
//void *force_chkstk(void) {
// return alloca(40960);
//}
#endif
}
#if defined(_COMPILER_MICROSOFT_) && !defined(__alignof__)
#define __alignof__ __alignof
#endif
#define DISABLE_FLOAT16
// llvm state
JL_DLLEXPORT LLVMContext &jl_LLVMContext = *(new LLVMContext());
TargetMachine *jl_TargetMachine;
extern JITEventListener *CreateJuliaJITEventListener();
// for image reloading
bool imaging_mode = false;
Module *shadow_output;
#define jl_Module ctx.f->getParent()
#define jl_builderModule(builder) (builder).GetInsertBlock()->getParent()->getParent()
static DataLayout &jl_data_layout = *(new DataLayout(""));
// types
static Type *T_jlvalue;
static Type *T_pjlvalue;
static Type *T_prjlvalue;
static Type *T_ppjlvalue;
static Type *T_pprjlvalue;
static Type *jl_array_llvmt;
static Type *jl_parray_llvmt;
static FunctionType *jl_func_sig;
static FunctionType *jl_func_sig_sparams;
static Type *T_pvoidfunc;
static IntegerType *T_int1;
static IntegerType *T_int8;
static IntegerType *T_int16;
static IntegerType *T_int32;
static IntegerType *T_int64;
static IntegerType *T_uint8;
static IntegerType *T_uint16;
static IntegerType *T_uint32;
static IntegerType *T_uint64;
static IntegerType *T_char;
static IntegerType *T_size;
static IntegerType *T_sigatomic;
static Type *T_float16;
static Type *T_float32;
static Type *T_float64;
static Type *T_float128;
static Type *T_pint8;
static Type *T_pint16;
static Type *T_pint32;
static Type *T_pint64;
static Type *T_psize;
static Type *T_pfloat32;
static Type *T_pfloat64;
static Type *T_ppint8;
static Type *T_pppint8;
static Type *T_void;
// type-based alias analysis nodes. Indentation of comments indicates hierarchy.
static MDNode *tbaa_root; // Everything
static MDNode *tbaa_gcframe; // GC frame
// LLVM should have enough info for alias analysis of non-gcframe stack slot
// this is mainly a place holder for `jl_cgval_t::tbaa`
static MDNode *tbaa_stack; // stack slot
static MDNode *tbaa_unionselbyte; // a selector byte in isbits Union struct fields
static MDNode *tbaa_data; // Any user data that `pointerset/ref` are allowed to alias
static MDNode *tbaa_binding; // jl_binding_t::value
static MDNode *tbaa_value; // jl_value_t, that is not jl_array_t
static MDNode *tbaa_mutab; // mutable type
static MDNode *tbaa_immut; // immutable type
static MDNode *tbaa_ptrarraybuf; // Data in an array of boxed values
static MDNode *tbaa_arraybuf; // Data in an array of POD
static MDNode *tbaa_array; // jl_array_t
static MDNode *tbaa_arrayptr; // The pointer inside a jl_array_t
static MDNode *tbaa_arraysize; // A size in a jl_array_t
static MDNode *tbaa_arraylen; // The len in a jl_array_t
static MDNode *tbaa_arrayflags; // The flags in a jl_array_t
static MDNode *tbaa_arrayoffset; // The offset in a jl_array_t
static MDNode *tbaa_arrayselbyte; // a selector byte in a isbits Union jl_array_t
static MDNode *tbaa_const; // Memory that is immutable by the time LLVM can see it
static Attribute Thunk;
// Basic DITypes
static DICompositeType *jl_value_dillvmt;
static DIDerivedType *jl_pvalue_dillvmt;
static DIDerivedType *jl_ppvalue_dillvmt;
static DISubroutineType *jl_di_func_sig;
static DISubroutineType *jl_di_func_null_sig;
// constants
static Constant *V_null;
extern "C" {
JL_DLLEXPORT Type *julia_type_to_llvm(jl_value_t *jt, bool *isboxed=NULL);
}
static bool type_is_ghost(Type *ty)
{
return (ty == T_void || ty->isEmptyTy());
}
// global vars
static GlobalVariable *jlRTLD_DEFAULT_var;
#ifdef _OS_WINDOWS_
static GlobalVariable *jlexe_var;
static GlobalVariable *jldll_var;
#endif //_OS_WINDOWS_
static Function *jltls_states_func;
// important functions
static Function *jlnew_func;
static Function *jlsplatnew_func;
static Function *jlthrow_func;
static Function *jlerror_func;
static Function *jltypeerror_func;
static Function *jlundefvarerror_func;
static Function *jlboundserror_func;
static Function *jluboundserror_func;
static Function *jlvboundserror_func;
static Function *jlboundserrorv_func;
static Function *jlcheckassign_func;
static Function *jldeclareconst_func;
static Function *jlgetbindingorerror_func;
static Function *jlboundp_func;
static Function *jltopeval_func;
static Function *jlcopyast_func;
static Function *jltuple_func;
static Function *jlnsvec_func;
static Function *jlapplygeneric_func;
static Function *jlinvoke_func;
static Function *jlgetfield_func;
static Function *jlmethod_func;
static Function *jlgenericfunction_func;
static Function *jlenter_func;
static Function *jl_current_exception_func;
static Function *jlleave_func;
static Function *jl_restore_excstack_func;
static Function *jl_excstack_state_func;
static Function *jlegal_func;
static Function *jl_alloc_obj_func;
static Function *jl_newbits_func;
static Function *jl_typeof_func;
static Function *jl_loopinfo_marker_func;
static Function *jl_write_barrier_func;
static Function *jlisa_func;
static Function *jlsubtype_func;
static Function *jlapplytype_func;
static Function *jl_object_id__func;
static Function *setjmp_func;
static Function *memcmp_derived_func;
static Function *box_int8_func;
static Function *box_uint8_func;
static Function *box_int16_func;
static Function *box_uint16_func;
static Function *box_int32_func;
static Function *box_char_func;
static Function *box_uint32_func;
static Function *box_int64_func;
static Function *box_uint64_func;
static Function *box_float32_func;
static Function *box_float64_func;
static Function *box_ssavalue_func;
static Function *expect_func;
static Function *jldlsym_func;
static Function *jltypeassert_func;
//static Function *jlgetnthfield_func;
static Function *jlgetnthfieldchecked_func;
//static Function *jlsetnthfield_func;
static Function *jlgetcfunctiontrampoline_func;
#ifdef _OS_WINDOWS_
#if defined(_CPU_X86_64_)
Function *juliapersonality_func;
#endif
#endif
static Function *diff_gc_total_bytes_func;
static Function *jlarray_data_owner_func;
static GlobalVariable *jlgetworld_global;
// placeholder functions
static Function *gcroot_flush_func;
static Function *gc_preserve_begin_func;
static Function *gc_preserve_end_func;
static Function *except_enter_func;
static Function *pointer_from_objref_func;
static std::map<jl_fptr_args_t, Function*> builtin_func_map;
// --- code generation ---
extern "C" {
int globalUnique = 0;
int jl_default_debug_info_kind = (int) DICompileUnit::DebugEmissionKind::FullDebug;
jl_cgparams_t jl_default_cgparams = {1, 1, 1, 1, 0,
#ifdef _OS_WINDOWS_
0,
#else
1,
#endif
jl_default_debug_info_kind, NULL, NULL, NULL, NULL, NULL};
}
template<typename T>
static void add_return_attr(T *f, Attribute::AttrKind Kind)
{
f->addAttribute(AttributeList::ReturnIndex, Kind);
}
static MDNode *best_tbaa(jl_value_t *jt) {
jt = jl_unwrap_unionall(jt);
if (!jl_is_datatype(jt))
return tbaa_value;
if (jl_is_abstracttype(jt))
return tbaa_value;
// If we're here, we know all subtypes are (im)mutable, even if we
// don't know what the exact type is
return jl_is_mutable(jt) ? tbaa_mutab : tbaa_immut;
}
// tracks whether codegen is currently able to simply stack-allocate this type
// note that this includes jl_isbits, although codegen should work regardless
static bool jl_is_concrete_immutable(jl_value_t* t)
{
return jl_is_immutable_datatype(t) && ((jl_datatype_t*)t)->layout;
}
static bool jl_is_pointerfree(jl_value_t* t)
{
if (!jl_is_immutable_datatype(t))
return 0;
const jl_datatype_layout_t *layout = ((jl_datatype_t*)t)->layout;
return layout && layout->npointers == 0;
}
// these queries are usually related, but we split them out here
// for convenience and clarity (and because it changes the calling convention)
static bool deserves_stack(jl_value_t* t, bool pointerfree=false)
{
if (!jl_is_concrete_immutable(t))
return false;
return ((jl_datatype_t*)t)->isinlinealloc;
}
static bool deserves_argbox(jl_value_t* t)
{
return !deserves_stack(t);
}
static bool deserves_retbox(jl_value_t* t)
{
return deserves_argbox(t);
}
static bool deserves_sret(jl_value_t *dt, Type *T)
{
assert(jl_is_datatype(dt));
return (size_t)jl_datatype_size(dt) > sizeof(void*) && !T->isFloatingPointTy() && !T->isVectorTy();
}
// metadata tracking for a llvm Value* during codegen
struct jl_cgval_t {
Value *V; // may be of type T* or T, or set to NULL if ghost (or if the value has not been initialized yet, for a variable definition)
// For unions, we may need to keep a reference to the boxed part individually.
// If this is non-NULL, then, at runtime, we satisfy the invariant that (for the corresponding
// runtime values) if `(TIndex | 0x80) != 0`, then `Vboxed == V` (by value).
// For convenience, we also set this value of isboxed values, in which case
// it is equal (at compile time) to V.
Value *Vboxed;
Value *TIndex; // if `V` is an unboxed (tagged) Union described by `typ`, this gives the DataType index (1-based, small int) as an i8
jl_value_t *constant; // constant value (rooted in linfo.def.roots)
jl_value_t *typ; // the original type of V, never NULL
bool isboxed; // whether this value is a jl_value_t* allocated on the heap with the right type tag
bool isghost; // whether this value is "ghost"
MDNode *tbaa; // The related tbaa node. Non-NULL iff this holds an address.
bool ispointer() const
{
// whether this value is compatible with `data_pointer`
return tbaa != nullptr;
}
jl_cgval_t(Value *V, Value *gcroot, bool isboxed, jl_value_t *typ, Value *tindex) : // general constructor (with pointer type auto-detect)
V(V), // V is allowed to be NULL in a jl_varinfo_t context, but not during codegen contexts
Vboxed(isboxed ? V : nullptr),
TIndex(tindex),
constant(NULL),
typ(typ),
isboxed(isboxed),
isghost(false),
tbaa(isboxed ? best_tbaa(typ) : nullptr)
{
assert(gcroot == nullptr);
assert(!(isboxed && TIndex != NULL));
assert(TIndex == NULL || TIndex->getType() == T_int8);
}
explicit jl_cgval_t(jl_value_t *typ) : // ghost value constructor
// mark explicit to avoid being used implicitly for conversion from NULL (use jl_cgval_t() instead)
V(NULL),
Vboxed(NULL),
TIndex(NULL),
constant(((jl_datatype_t*)typ)->instance),
typ(typ),
isboxed(false),
isghost(true),
tbaa(nullptr)
{
assert(jl_is_datatype(typ));
assert(constant);
}
jl_cgval_t(const jl_cgval_t &v, jl_value_t *typ, Value *tindex) : // copy constructor with new type
V(v.V),
Vboxed(v.Vboxed),
TIndex(tindex),
constant(v.constant),
typ(typ),
isboxed(v.isboxed),
isghost(v.isghost),
tbaa(v.tbaa)
{
// this constructor expects we had a badly or equivalently typed version
// make sure we aren't discarding the actual type information
if (v.TIndex) {
assert((TIndex == NULL) == jl_is_concrete_type(typ));
}
else {
assert(isboxed || v.typ == typ || tindex);
}
}
jl_cgval_t() : // undef / unreachable / default constructor
V(UndefValue::get(T_void)),
Vboxed(NULL),
TIndex(NULL),
constant(NULL),
typ(jl_bottom_type),
isboxed(false),
isghost(true),
tbaa(nullptr)
{
}
};
// per-local-variable information
struct jl_varinfo_t {
Instruction *boxroot; // an address, if the var might be in a jl_value_t** stack slot (marked tbaa_const, if appropriate)
jl_cgval_t value; // a stack slot or constant value
Value *pTIndex; // i8* stack slot for the value.TIndex tag describing `value.V`
DILocalVariable *dinfo;
// if the variable might be used undefined and is not boxed
// this i1 flag is true when it is defined
Value *defFlag;
bool isSA; // whether all stores dominate all uses
bool isVolatile;
bool isArgument;
bool usedUndef;
bool used;
jl_varinfo_t() : boxroot(NULL),
value(jl_cgval_t()),
pTIndex(NULL),
dinfo(NULL),
defFlag(NULL),
isSA(false),
isVolatile(false),
isArgument(false),
usedUndef(false),
used(false)
{
}
};
struct jl_returninfo_t {
Function *decl;
enum CallingConv {
Boxed = 0,
Register,
SRet,
Union,
Ghosts
} cc;
size_t union_bytes;
size_t union_align;
size_t union_minalign;
unsigned return_roots;
};
static jl_returninfo_t get_specsig_function(Module *M, const std::string &name, jl_value_t *sig, jl_value_t *jlrettype);
// information about the context of a piece of code: its enclosing
// function and module, and visible local variables and labels.
class jl_codectx_t {
public:
IRBuilder<> builder;
Function *f = NULL;
// local var info. globals are not in here.
std::vector<jl_varinfo_t> slots;
std::map<int, jl_varinfo_t> phic_slots;
std::vector<jl_cgval_t> SAvalues;
std::vector<std::tuple<jl_cgval_t, BasicBlock *, AllocaInst *, PHINode *, jl_value_t *>> PhiNodes;
std::vector<bool> ssavalue_assigned;
jl_module_t *module = NULL;
jl_method_instance_t *linfo = NULL;
jl_code_info_t *source = NULL;
jl_array_t *code = NULL;
size_t world = 0;
jl_array_t *roots = NULL;
const char *name = NULL;
StringRef file{};
ssize_t *line = NULL;
Value *spvals_ptr = NULL;
Value *argArray = NULL;
Value *argCount = NULL;
MDNode *aliasscope = NULL;
std::string funcName;
int vaSlot = -1; // name of vararg argument
int nReqArgs = 0;
int nargs = 0;
int nvargs = -1;
CallInst *ptlsStates = NULL;
Value *signalPage = NULL;
Value *world_age_field = NULL;
bool debug_enabled = false;
const jl_cgparams_t *params = NULL;
jl_codectx_t(LLVMContext &llvmctx)
: builder(llvmctx) { }
~jl_codectx_t() {
assert(this->roots == NULL);
}
};
static jl_cgval_t emit_expr(jl_codectx_t &ctx, jl_value_t *expr, ssize_t ssaval = -1);
static Value *global_binding_pointer(jl_codectx_t &ctx, jl_module_t *m, jl_sym_t *s,
jl_binding_t **pbnd, bool assign);
static jl_cgval_t emit_checked_var(jl_codectx_t &ctx, Value *bp, jl_sym_t *name, bool isvol, MDNode *tbaa);
static jl_cgval_t emit_sparam(jl_codectx_t &ctx, size_t i);
static Value *emit_condition(jl_codectx_t &ctx, const jl_cgval_t &condV, const std::string &msg);
static void allocate_gc_frame(jl_codectx_t &ctx, BasicBlock *b0);
static void CreateTrap(IRBuilder<> &irbuilder);
static CallInst *emit_jlcall(jl_codectx_t &ctx, Value *theFptr, Value *theF,
jl_cgval_t *args, size_t nargs, CallingConv::ID cc);
static Value *literal_pointer_val(jl_codectx_t &ctx, jl_value_t *p);
static GlobalVariable *prepare_global_in(Module *M, GlobalVariable *G);
#define prepare_global(G) prepare_global_in(jl_Module, (G))
static Instruction *tbaa_decorate(MDNode *md, Instruction *load_or_store);
// --- convenience functions for tagging llvm values with julia types ---
static GlobalVariable *get_pointer_to_constant(Constant *val, StringRef name, Module &M)
{
GlobalVariable *gv = new GlobalVariable(
M,
val->getType(),
true,
GlobalVariable::PrivateLinkage,
val,
name);
gv->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
return gv;
}
static AllocaInst *emit_static_alloca(jl_codectx_t &ctx, Type *lty)
{
return new AllocaInst(lty, 0, "", /*InsertBefore=*/ctx.ptlsStates);
}
static void undef_derived_strct(IRBuilder<> &irbuilder, Value *ptr, jl_datatype_t *sty, MDNode *tbaa)
{
assert(ptr->getType()->getPointerAddressSpace() != AddressSpace::Tracked);
size_t i, np = sty->layout->npointers;
if (np == 0)
return;
ptr = irbuilder.CreateBitCast(ptr, T_prjlvalue->getPointerTo(ptr->getType()->getPointerAddressSpace()));
Value *V_null = ConstantPointerNull::get(cast<PointerType>(T_prjlvalue));
for (i = 0; i < np; i++) {
Value *fld = irbuilder.CreateConstInBoundsGEP1_32(T_prjlvalue, ptr, jl_ptr_offset(sty, i));
tbaa_decorate(tbaa, irbuilder.CreateStore(V_null, fld));
}
}
static inline jl_cgval_t ghostValue(jl_value_t *typ)
{
if (typ == jl_bottom_type)
return jl_cgval_t(); // Undef{}
if (typ == (jl_value_t*)jl_typeofbottom_type) {
// normalize TypeofBottom to Type{Union{}}
typ = (jl_value_t*)jl_wrap_Type(jl_bottom_type);
}
if (jl_is_type_type(typ)) {
// replace T::Type{T} with T, by assuming that T must be a leaftype of some sort
jl_cgval_t constant(NULL, NULL, true, typ, NULL);
constant.constant = jl_tparam0(typ);
return constant;
}
return jl_cgval_t(typ);
}
static inline jl_cgval_t ghostValue(jl_datatype_t *typ)
{
return ghostValue((jl_value_t*)typ);
}
static inline jl_cgval_t mark_julia_const(jl_value_t *jv)
{
jl_value_t *typ;
if (jl_is_type(jv)) {
typ = (jl_value_t*)jl_wrap_Type(jv); // TODO: gc-root this?
}
else {
typ = jl_typeof(jv);
if (type_is_ghost(julia_type_to_llvm(typ))) {
return ghostValue(typ);
}
}
jl_cgval_t constant(NULL, NULL, true, typ, NULL);
constant.constant = jv;
return constant;
}
static inline jl_cgval_t mark_julia_slot(Value *v, jl_value_t *typ, Value *tindex, MDNode *tbaa)
{
// this enables lazy-copying of immutable values and stack or argument slots
assert(tbaa);
jl_cgval_t tagval(v, NULL, false, typ, tindex);
tagval.tbaa = tbaa;
return tagval;
}
static bool valid_as_globalinit(const Value *v) {
if (isa<ConstantExpr>(v)) {
// llvm can't handle all the things that could be inside a ConstantExpr
// (such as addrspacecast), and we don't really mind losing this optimization
return false;
}
if (const auto *CC = dyn_cast<ConstantAggregate>(v)) {
for (const Value *elem : CC->operand_values())
if (!valid_as_globalinit(elem))
return false;
}
return isa<Constant>(v);
}
static inline jl_cgval_t value_to_pointer(jl_codectx_t &ctx, Value *v, jl_value_t *typ, Value *tindex)
{
Value *loc;
if (valid_as_globalinit(v)) { // llvm can't handle all the things that could be inside a ConstantExpr
loc = get_pointer_to_constant(cast<Constant>(v), "", *jl_Module);
}
else {
loc = emit_static_alloca(ctx, v->getType());
ctx.builder.CreateStore(v, loc);
}
return mark_julia_slot(loc, typ, tindex, tbaa_stack);
}
static inline jl_cgval_t value_to_pointer(jl_codectx_t &ctx, const jl_cgval_t &v)
{
if (v.ispointer())
return v;
return value_to_pointer(ctx, v.V, v.typ, v.TIndex);
}
static inline jl_cgval_t mark_julia_type(jl_codectx_t &ctx, Value *v, bool isboxed, jl_value_t *typ)
{
if (jl_is_datatype(typ) && jl_is_datatype_singleton((jl_datatype_t*)typ)) {
// no need to explicitly load/store a constant/ghost value
return ghostValue(typ);
}
if (jl_is_type_type(typ)) {
jl_value_t *tp0 = jl_tparam0(typ);
if (jl_is_concrete_type(tp0) || tp0 == jl_bottom_type) {
// replace T::Type{T} with T
return ghostValue(typ);
}
}
Type *T = julia_type_to_llvm(typ);
if (type_is_ghost(T)) {
return ghostValue(typ);
}
if (v && !isboxed && v->getType()->isAggregateType() && CountTrackedPointers(v->getType()).count == 0) {
// eagerly put this back onto the stack
// llvm mem2reg pass will remove this if unneeded
return value_to_pointer(ctx, v, typ, NULL);
}
return jl_cgval_t(v, NULL, isboxed, typ, NULL);
}
static inline jl_cgval_t mark_julia_type(jl_codectx_t &ctx, Value *v, bool isboxed, jl_datatype_t *typ)
{
return mark_julia_type(ctx, v, isboxed, (jl_value_t*)typ);
}
// see if it might be profitable (and cheap) to change the type of v to typ
static inline jl_cgval_t update_julia_type(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ)
{
if (v.typ == typ || v.typ == jl_bottom_type || v.constant || typ == (jl_value_t*)jl_any_type || jl_egal(v.typ, typ))
return v; // fast-path
if (jl_is_concrete_type(v.typ) && !jl_is_kind(v.typ)) {
if (jl_is_concrete_type(typ) && !jl_is_kind(typ)) {
// type mismatch: changing from one leaftype to another
CreateTrap(ctx.builder);
return jl_cgval_t();
}
return v; // doesn't improve type info
}
if (v.TIndex) {
jl_value_t *utyp = jl_unwrap_unionall(typ);
if (jl_is_datatype(utyp)) {
bool alwaysboxed;
if (jl_is_concrete_type(utyp))
alwaysboxed = !jl_is_pointerfree(utyp);
else
alwaysboxed = !((jl_datatype_t*)utyp)->abstract && ((jl_datatype_t*)utyp)->mutabl;
if (alwaysboxed) {
// discovered that this union-split type must actually be isboxed
if (v.Vboxed) {
return jl_cgval_t(v.Vboxed, nullptr, true, typ, NULL);
}
else {
// type mismatch (there weren't any boxed values in the union)
CreateTrap(ctx.builder);
return jl_cgval_t();
}
}
}
if (!jl_is_concrete_type(typ))
return v; // not generally worth trying to change type info (which would require recomputing tindex)
}
Type *T = julia_type_to_llvm(typ);
if (type_is_ghost(T))
return ghostValue(typ);
return jl_cgval_t(v, typ, NULL);
}
static jl_cgval_t convert_julia_type(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ);
// --- allocating local variables ---
static jl_sym_t *slot_symbol(jl_codectx_t &ctx, int s)
{
return (jl_sym_t*)jl_array_ptr_ref(ctx.source->slotnames, s);
}
static void store_def_flag(jl_codectx_t &ctx, const jl_varinfo_t &vi, bool val)
{
assert((!vi.boxroot || vi.pTIndex) && "undef check is null pointer for boxed things");
assert(vi.usedUndef && vi.defFlag && "undef flag codegen corrupted");
ctx.builder.CreateStore(ConstantInt::get(T_int1, val), vi.defFlag, vi.isVolatile);
}
static void alloc_def_flag(jl_codectx_t &ctx, jl_varinfo_t& vi)
{
assert((!vi.boxroot || vi.pTIndex) && "undef check is null pointer for boxed things");
if (vi.usedUndef) {
vi.defFlag = emit_static_alloca(ctx, T_int1);
store_def_flag(ctx, vi, false);
}
}
// --- utilities ---
static void CreateTrap(IRBuilder<> &irbuilder)
{
Function *f = irbuilder.GetInsertBlock()->getParent();
Function *trap_func = Intrinsic::getDeclaration(
f->getParent(),
Intrinsic::trap);
irbuilder.CreateCall(trap_func);
irbuilder.CreateUnreachable();
BasicBlock *newBB = BasicBlock::Create(irbuilder.getContext(), "after_noret", f);
irbuilder.SetInsertPoint(newBB);
}
#if 0 // this code is likely useful, but currently unused
#ifndef JL_NDEBUG
static void CreateConditionalAbort(IRBuilder<> &irbuilder, Value *test)
{
Function *f = irbuilder.GetInsertBlock()->getParent();
BasicBlock *abortBB = BasicBlock::Create(jl_LLVMContext, "debug_abort", f);
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_abort", f);
irbuilder.CreateCondBr(test, abortBB, postBB);
irbuilder.SetInsertPoint(abortBB);
Function *trap_func = Intrinsic::getDeclaration(
f->getParent(),
Intrinsic::trap);
irbuilder.CreateCall(trap_func);
irbuilder.CreateUnreachable();
irbuilder.SetInsertPoint(postBB);
}
#endif
#endif
#include "cgutils.cpp"
static void jl_rethrow_with_add(const char *fmt, ...)
{
if (jl_typeis(jl_current_exception(), jl_errorexception_type)) {
char *str = jl_string_data(jl_fieldref(jl_current_exception(),0));
char buf[1024];
va_list args;
va_start(args, fmt);
int nc = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
nc += snprintf(buf+nc, sizeof(buf)-nc, ": %s", str);
jl_value_t *msg = jl_pchar_to_string(buf, nc);
JL_GC_PUSH1(&msg);
jl_throw(jl_new_struct(jl_errorexception_type, msg));
}
jl_rethrow();
}
static jl_cgval_t convert_julia_type_union(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ)
{
// previous value was a split union, compute new index, or box
Value *new_tindex = ConstantInt::get(T_int8, 0x80);
SmallBitVector skip_box(1, true);
Value *tindex = ctx.builder.CreateAnd(v.TIndex, ConstantInt::get(T_int8, 0x7f));
if (jl_is_uniontype(typ)) {
// compute the TIndex mapping from v.typ -> typ
unsigned counter = 0;
for_each_uniontype_small(
// for each old union-split value
[&](unsigned idx, jl_datatype_t *jt) {
unsigned new_idx = get_box_tindex(jt, typ);
bool t;
if (new_idx) {
// found a matching element,
// match it against either the unboxed index
Value *cmp = ctx.builder.CreateICmpEQ(tindex, ConstantInt::get(T_int8, idx));
new_tindex = ctx.builder.CreateSelect(cmp, ConstantInt::get(T_int8, new_idx), new_tindex);
t = true;
}
else if (!jl_subtype((jl_value_t*)jt, typ)) {
// new value doesn't need to be boxed
// since it isn't part of the new union
t = true;
}
else {
// will actually need to box this element
// since it appeared as a leaftype in the original type
// but not in the remark type
t = false;
}
skip_box.resize(idx + 1, t);
},
v.typ,
counter);
}
// some of the values are still unboxed
if (!isa<Constant>(new_tindex)) {
Value *wasboxed = NULL;
// If the old value was boxed and unknown (type tag 0x80),
// it is possible that the tag was actually one of the types
// that are now explicitly represented. To find out, we need
// to compare typeof(v.Vboxed) (i.e. the type of the unknown
// value) against all the types that are now explicitly
// selected and select the appropriate one as our new tindex.
if (v.Vboxed) {
wasboxed = ctx.builder.CreateAnd(v.TIndex, ConstantInt::get(T_int8, 0x80));
new_tindex = ctx.builder.CreateOr(wasboxed, new_tindex);
wasboxed = ctx.builder.CreateICmpNE(wasboxed, ConstantInt::get(T_int8, 0));
BasicBlock *currBB = ctx.builder.GetInsertBlock();
// We lazily create a BB for this, once we decide that we
// actually need it.
Value *union_box_dt = NULL;
BasicBlock *union_isaBB = NULL;
auto maybe_setup_union_isa = [&]() {
if (!union_isaBB) {
union_isaBB = BasicBlock::Create(jl_LLVMContext, "union_isa", ctx.f);
ctx.builder.SetInsertPoint(union_isaBB);
union_box_dt = emit_typeof(ctx, v.Vboxed);
}
};
// If we don't find a match. The type remains unknown
// (0x80). We could use `v.Tindex`, here, since we know
// it has to be 0x80, but it seems likely the backend
// will like the explicit constant better.
Value *union_box_tindex = ConstantInt::get(T_int8, 0x80);
unsigned counter = 0;
for_each_uniontype_small(
// for each new union-split value
[&](unsigned idx, jl_datatype_t *jt) {
unsigned old_idx = get_box_tindex(jt, v.typ);
if (old_idx == 0) {
// didn't handle this item before, select its new union index
maybe_setup_union_isa();
Value *cmp = ctx.builder.CreateICmpEQ(maybe_decay_untracked(literal_pointer_val(ctx, (jl_value_t*)jt)), union_box_dt);
union_box_tindex = ctx.builder.CreateSelect(cmp, ConstantInt::get(T_int8, 0x80 | idx), union_box_tindex);
}
},
typ,
counter);
if (union_box_dt) {
BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_union_isa", ctx.f);
ctx.builder.CreateBr(postBB);
ctx.builder.SetInsertPoint(currBB);
Value *wasunknown = ctx.builder.CreateICmpEQ(v.TIndex, ConstantInt::get(T_int8, 0x80));
ctx.builder.CreateCondBr(wasunknown, union_isaBB, postBB);
ctx.builder.SetInsertPoint(postBB);
PHINode *tindex_phi = ctx.builder.CreatePHI(T_int8, 2);
tindex_phi->addIncoming(new_tindex, currBB);
tindex_phi->addIncoming(union_box_tindex, union_isaBB);
new_tindex = tindex_phi;
}
}
if (!skip_box.all()) {
// some values weren't unboxed in the new union
// box them now (tindex above already selected 0x80 = box for them)
Value *boxv = box_union(ctx, v, skip_box);
if (v.Vboxed) {
// If the value is boxed both before and after, we don't need
// to touch it at all. Otherwise we're either transitioning
// unboxed->boxed, or leaving an unboxed value in place.
Value *isboxed = ctx.builder.CreateICmpNE(
ctx.builder.CreateAnd(new_tindex, ConstantInt::get(T_int8, 0x80)),
ConstantInt::get(T_int8, 0));
boxv = ctx.builder.CreateSelect(
ctx.builder.CreateAnd(wasboxed, isboxed), v.Vboxed, boxv);
}
if (v.V == NULL) {
// v.V might be NULL if it was all ghost objects before
return jl_cgval_t(boxv, NULL, false, typ, new_tindex);
} else {
Value *isboxv = ctx.builder.CreateIsNotNull(boxv);
Value *slotv;
MDNode *tbaa;
if (v.ispointer()) {
slotv = v.V;
tbaa = v.tbaa;
}
else {
slotv = emit_static_alloca(ctx, v.V->getType());
ctx.builder.CreateStore(v.V, slotv);
tbaa = tbaa_stack;
}
slotv = ctx.builder.CreateSelect(isboxv,
decay_derived(boxv),
decay_derived(emit_bitcast(ctx, slotv, boxv->getType())));
jl_cgval_t newv = jl_cgval_t(slotv, NULL, false, typ, new_tindex);
newv.Vboxed = boxv;
newv.tbaa = tbaa;
return newv;
}
}
}
else {
return jl_cgval_t(boxed(ctx, v), NULL, true, typ, NULL);
}
return jl_cgval_t(v, typ, new_tindex);