-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
jitlayers.cpp
1319 lines (1203 loc) · 46.6 KB
/
jitlayers.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: http://julialang.org/license
#include "llvm-version.h"
#include "platform.h"
#include "options.h"
#include <iostream>
#include <sstream>
// analysis passes
#include <llvm/Analysis/Passes.h>
#if JL_LLVM_VERSION >= 30800
#include <llvm/Analysis/BasicAliasAnalysis.h>
#include <llvm/Analysis/TypeBasedAliasAnalysis.h>
#endif
#if JL_LLVM_VERSION >= 30700
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#endif
#if JL_LLVM_VERSION >= 30500
#include <llvm/IR/Verifier.h>
#else
#include <llvm/Analysis/Verifier.h>
#endif
#if defined(USE_POLLY)
#include <polly/RegisterPasses.h>
#include <polly/LinkAllPasses.h>
#include <polly/CodeGen/CodegenCleanup.h>
#endif
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Instrumentation.h>
#include <llvm/Transforms/Vectorize.h>
#if JL_LLVM_VERSION >= 30900
#include <llvm/Transforms/Scalar/GVN.h>
#endif
#if JL_LLVM_VERSION >= 40000
#include <llvm/Transforms/IPO/AlwaysInliner.h>
#endif
namespace llvm {
extern Pass *createLowerSimdLoopPass();
}
#if JL_LLVM_VERSION >= 40000
# include <llvm/Bitcode/BitcodeWriter.h>
#else
# include <llvm/Bitcode/ReaderWriter.h>
#endif
#if JL_LLVM_VERSION >= 30500
#include <llvm/Bitcode/BitcodeWriterPass.h>
#endif
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/ExecutionEngine/JITEventListener.h>
// target support
#include <llvm/ADT/Triple.h>
#include <llvm/Support/TargetRegistry.h>
#if JL_LLVM_VERSION < 30700
#include <llvm/Target/TargetLibraryInfo.h>
#endif
#include <llvm/IR/DataLayout.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/ADT/StringMap.h>
#include <llvm/ADT/StringSet.h>
#include <llvm/ADT/SmallSet.h>
using namespace llvm;
#include "julia.h"
#include "julia_internal.h"
#include "jitlayers.h"
#ifdef USE_MCJIT
RTDyldMemoryManager* createRTDyldMemoryManager(void);
#endif
static Type *T_void;
static IntegerType *T_uint32;
static IntegerType *T_uint64;
static IntegerType *T_size;
static Type *T_psize;
static Type *T_pvoidfunc;
static Type *T_pjlvalue;
void jl_init_jit(Type *T_pjlvalue_)
{
T_void = Type::getVoidTy(jl_LLVMContext);
T_uint32 = Type::getInt32Ty(jl_LLVMContext);
T_uint64 = Type::getInt64Ty(jl_LLVMContext);
if (sizeof(size_t) == 8)
T_size = T_uint64;
else
T_size = T_uint32;
T_psize = PointerType::get(T_size, 0);
T_pvoidfunc = FunctionType::get(T_void, /*isVarArg*/false)->getPointerTo();
T_pjlvalue = T_pjlvalue_;
}
// Except for parts of this file which were copied from LLVM, under the UIUC license (marked below).
// this defines the set of optimization passes defined for Julia at various optimization levels
#if JL_LLVM_VERSION >= 30700
void addOptimizationPasses(legacy::PassManager *PM)
#else
void addOptimizationPasses(PassManager *PM)
#endif
{
PM->add(createLowerGCFramePass());
#ifdef JL_DEBUG_BUILD
PM->add(createVerifierPass());
#endif
#if defined(JL_ASAN_ENABLED)
# if JL_LLVM_VERSION >= 30700 && JL_LLVM_VERSION < 30800
// LLVM 3.7 BUG: ASAN pass doesn't properly initialize its dependencies
initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
# endif
PM->add(createAddressSanitizerFunctionPass());
#endif
#if defined(JL_MSAN_ENABLED)
PM->add(llvm::createMemorySanitizerPass(true));
#endif
if (jl_options.opt_level == 0) {
PM->add(createLowerPTLSPass(imaging_mode));
return;
}
#if JL_LLVM_VERSION >= 30700
PM->add(createTargetTransformInfoWrapperPass(jl_TargetMachine->getTargetIRAnalysis()));
#else
jl_TargetMachine->addAnalysisPasses(*PM);
#endif
#if JL_LLVM_VERSION >= 30800
PM->add(createTypeBasedAAWrapperPass());
#else
PM->add(createTypeBasedAliasAnalysisPass());
#endif
if (jl_options.opt_level >= 3) {
#if JL_LLVM_VERSION >= 30800
PM->add(createBasicAAWrapperPass());
#else
PM->add(createBasicAliasAnalysisPass());
#endif
}
// list of passes from vmkit
PM->add(createCFGSimplificationPass()); // Clean up disgusting code
PM->add(createPromoteMemoryToRegisterPass());// Kill useless allocas
#if JL_LLVM_VERSION >= 40000
PM->add(createAlwaysInlinerLegacyPass()); // Respect always_inline
#else
PM->add(createAlwaysInlinerPass()); // Respect always_inline
#endif
#ifndef INSTCOMBINE_BUG
PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
#endif
// Let the InstCombine pass remove the unnecessary load of
// safepoint address first
PM->add(createLowerPTLSPass(imaging_mode));
PM->add(createSROAPass()); // Break up aggregate allocas
#ifndef INSTCOMBINE_BUG
PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
#endif
PM->add(createJumpThreadingPass()); // Thread jumps.
// NOTE: CFG simp passes after this point seem to hurt native codegen.
// See issue #6112. Should be re-evaluated when we switch to MCJIT.
//PM->add(createCFGSimplificationPass()); // Merge & remove BBs
#ifndef INSTCOMBINE_BUG
PM->add(createInstructionCombiningPass()); // Combine silly seq's
#endif
//PM->add(createCFGSimplificationPass()); // Merge & remove BBs
PM->add(createReassociatePass()); // Reassociate expressions
// this has the potential to make some things a bit slower
//PM->add(createBBVectorizePass());
PM->add(createEarlyCSEPass()); //// ****
PM->add(createLoopIdiomPass()); //// ****
PM->add(createLoopRotatePass()); // Rotate loops.
#ifdef USE_POLLY
// LCSSA (which has already run at this point due to the dependencies of the
// above passes) introduces redundant phis that hinder Polly. Therefore we
// run InstCombine here to remove them.
PM->add(createInstructionCombiningPass());
PM->add(polly::createCodePreparationPass());
polly::registerPollyPasses(*PM);
PM->add(polly::createCodegenCleanupPass());
#endif
// LoopRotate strips metadata from terminator, so run LowerSIMD afterwards
PM->add(createLowerSimdLoopPass()); // Annotate loop marked with "simdloop" as LLVM parallel loop
PM->add(createLICMPass()); // Hoist loop invariants
PM->add(createLoopUnswitchPass()); // Unswitch loops.
// Subsequent passes not stripping metadata from terminator
#ifndef INSTCOMBINE_BUG
PM->add(createInstructionCombiningPass());
#endif
PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
PM->add(createLoopDeletionPass()); // Delete dead loops
#if JL_LLVM_VERSION >= 30500
PM->add(createSimpleLoopUnrollPass()); // Unroll small loops
#else
PM->add(createLoopUnrollPass()); // Unroll small loops
#endif
#if JL_LLVM_VERSION < 30500 && !defined(INSTCOMBINE_BUG)
PM->add(createLoopVectorizePass()); // Vectorize loops
#endif
//PM->add(createLoopStrengthReducePass()); // (jwb added)
#ifndef INSTCOMBINE_BUG
PM->add(createInstructionCombiningPass()); // Clean up after the unroller
#endif
PM->add(createGVNPass()); // Remove redundancies
PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
PM->add(createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
PM->add(createSinkingPass()); ////////////// ****
PM->add(createInstructionSimplifierPass());///////// ****
#ifndef INSTCOMBINE_BUG
PM->add(createInstructionCombiningPass());
#endif
PM->add(createJumpThreadingPass()); // Thread jumps
PM->add(createDeadStoreEliminationPass()); // Delete dead stores
#if JL_LLVM_VERSION >= 30500
if (jl_options.opt_level >= 3) {
PM->add(createSLPVectorizerPass()); // Vectorize straight-line code
}
#endif
PM->add(createAggressiveDCEPass()); // Delete dead instructions
#if JL_LLVM_VERSION >= 30500
if (jl_options.opt_level >= 3)
PM->add(createInstructionCombiningPass()); // Clean up after SLP loop vectorizer
PM->add(createLoopVectorizePass()); // Vectorize loops
PM->add(createInstructionCombiningPass()); // Clean up after loop vectorizer
#endif
//PM->add(createCFGSimplificationPass()); // Merge & remove BBs
}
#ifdef USE_ORCJIT
#if JL_LLVM_VERSION < 30800
void notifyObjectLoaded(RTDyldMemoryManager *memmgr,
llvm::orc::ObjectLinkingLayerBase::ObjSetHandleT H);
#endif
// ------------------------ TEMPORARILY COPIED FROM LLVM -----------------
// This must be kept in sync with gdb/gdb/jit.h .
extern "C" {
typedef enum {
JIT_NOACTION = 0,
JIT_REGISTER_FN,
JIT_UNREGISTER_FN
} jit_actions_t;
struct jit_code_entry {
struct jit_code_entry *next_entry;
struct jit_code_entry *prev_entry;
const char *symfile_addr;
uint64_t symfile_size;
};
struct jit_descriptor {
uint32_t version;
// This should be jit_actions_t, but we want to be specific about the
// bit-width.
uint32_t action_flag;
struct jit_code_entry *relevant_entry;
struct jit_code_entry *first_entry;
};
// We put information about the JITed function in this global, which the
// debugger reads. Make sure to specify the version statically, because the
// debugger checks the version before we can set it during runtime.
extern struct jit_descriptor __jit_debug_descriptor;
LLVM_ATTRIBUTE_NOINLINE extern void __jit_debug_register_code();
}
namespace {
using namespace llvm;
using namespace llvm::object;
using namespace llvm::orc;
/// Do the registration.
void NotifyDebugger(jit_code_entry *JITCodeEntry)
{
__jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
// Insert this entry at the head of the list.
JITCodeEntry->prev_entry = nullptr;
jit_code_entry *NextEntry = __jit_debug_descriptor.first_entry;
JITCodeEntry->next_entry = NextEntry;
if (NextEntry) {
NextEntry->prev_entry = JITCodeEntry;
}
__jit_debug_descriptor.first_entry = JITCodeEntry;
__jit_debug_descriptor.relevant_entry = JITCodeEntry;
__jit_debug_register_code();
}
}
// ------------------------ END OF TEMPORARY COPY FROM LLVM -----------------
#if defined(_OS_LINUX_)
// Resolve non-lock free atomic functions in the libatomic library.
// This is the library that provides support for c11/c++11 atomic operations.
static uint64_t resolve_atomic(const char *name)
{
static void *atomic_hdl = jl_load_dynamic_library_e("libatomic",
JL_RTLD_LOCAL);
static const char *const atomic_prefix = "__atomic_";
if (!atomic_hdl)
return 0;
if (strncmp(name, atomic_prefix, strlen(atomic_prefix)) != 0)
return 0;
return (uintptr_t)jl_dlsym_e(atomic_hdl, name);
}
#endif
// Custom object emission notification handler for the JuliaOJIT
extern JITEventListener *CreateJuliaJITEventListener();
JuliaOJIT::DebugObjectRegistrar::DebugObjectRegistrar(JuliaOJIT &JIT)
: JuliaListener(CreateJuliaJITEventListener()),
JIT(JIT) {}
JL_DLLEXPORT void ORCNotifyObjectEmitted(JITEventListener *Listener,
const object::ObjectFile &obj,
const object::ObjectFile &debugObj,
const RuntimeDyld::LoadedObjectInfo &L,
RTDyldMemoryManager *memmgr);
// TODO: hook up RegisterJITEventListener, instead of hard-coding the GDB and JuliaListener targets
template <typename ObjSetT, typename LoadResult>
void JuliaOJIT::DebugObjectRegistrar::operator()(ObjectLinkingLayerBase::ObjSetHandleT H,
const ObjSetT &Objects, const LoadResult &LOS)
{
#if JL_LLVM_VERSION < 30800
notifyObjectLoaded(JIT.MemMgr, H);
#endif
auto oit = Objects.begin();
auto lit = LOS.begin();
for (; oit != Objects.end(); ++oit, ++lit) {
#if JL_LLVM_VERSION >= 30900
const auto &Object = (*oit)->getBinary();
#else
auto &Object = *oit;
#endif
auto &LO = *lit;
OwningBinary<object::ObjectFile> SavedObject = LO->getObjectForDebug(*Object);
// If the debug object is unavailable, save (a copy of) the original object
// for our backtraces
if (!SavedObject.getBinary()) {
// This is unfortunate, but there doesn't seem to be a way to take
// ownership of the original buffer
auto NewBuffer = MemoryBuffer::getMemBufferCopy(Object->getData(),
Object->getFileName());
auto NewObj = ObjectFile::createObjectFile(NewBuffer->getMemBufferRef());
assert(NewObj);
SavedObject = OwningBinary<object::ObjectFile>(std::move(*NewObj),
std::move(NewBuffer));
}
else {
NotifyGDB(SavedObject);
}
SavedObjects.push_back(std::move(SavedObject));
ORCNotifyObjectEmitted(JuliaListener.get(),
*Object,
*SavedObjects.back().getBinary(),
*LO, JIT.MemMgr);
// record all of the exported symbols defined in this object
// in the primary hash table for the enclosing JIT
for (auto &Symbol : Object->symbols()) {
auto Flags = Symbol.getFlags();
if (Flags & object::BasicSymbolRef::SF_Undefined)
continue;
if (!(Flags & object::BasicSymbolRef::SF_Exported))
continue;
auto NameOrError = Symbol.getName();
assert(NameOrError);
auto Name = NameOrError.get();
auto Sym = JIT.CompileLayer.findSymbolIn(H, Name, true);
assert(Sym);
// note: calling getAddress here eagerly finalizes H
// as an alternative, we could store the JITSymbol instead
// (which would present a lazy-initializer functor interface instead)
JIT.LocalSymbolTable[Name] = (void*)(uintptr_t)Sym.getAddress();
}
}
}
void JuliaOJIT::DebugObjectRegistrar::NotifyGDB(OwningBinary<object::ObjectFile> &DebugObj)
{
const char *Buffer = DebugObj.getBinary()->getMemoryBufferRef().getBufferStart();
size_t Size = DebugObj.getBinary()->getMemoryBufferRef().getBufferSize();
assert(Buffer && "Attempt to register a null object with a debugger.");
jit_code_entry *JITCodeEntry = new jit_code_entry();
if (!JITCodeEntry) {
jl_printf(JL_STDERR, "WARNING: Allocation failed when registering a JIT entry!\n");
}
else {
JITCodeEntry->symfile_addr = Buffer;
JITCodeEntry->symfile_size = Size;
NotifyDebugger(JITCodeEntry);
}
}
JuliaOJIT::JuliaOJIT(TargetMachine &TM)
: TM(TM),
DL(TM.createDataLayout()),
ObjStream(ObjBufferSV),
MemMgr(createRTDyldMemoryManager()),
ObjectLayer(DebugObjectRegistrar(*this)),
CompileLayer(
ObjectLayer,
[this](Module &M) {
JL_TIMING(LLVM_OPT);
PM.run(M);
std::unique_ptr<MemoryBuffer> ObjBuffer(
new ObjectMemoryBuffer(std::move(ObjBufferSV)));
auto Obj = object::ObjectFile::createObjectFile(ObjBuffer->getMemBufferRef());
if (!Obj) {
M.dump();
#if JL_LLVM_VERSION >= 30900
std::string Buf;
raw_string_ostream OS(Buf);
logAllUnhandledErrors(Obj.takeError(), OS, "");
OS.flush();
llvm::report_fatal_error("FATAL: Unable to compile LLVM Module: '" + Buf + "'\n"
"The module's content was printed above. Please file a bug report");
#else
llvm::report_fatal_error("FATAL: Unable to compile LLVM Module.\n"
"The module's content was printed above. Please file a bug report");
#endif
}
return OwningObj(std::move(*Obj), std::move(ObjBuffer));
}
)
{
if (!jl_generating_output()) {
addOptimizationPasses(&PM);
}
else {
PM.add(createLowerGCFramePass());
PM.add(createLowerPTLSPass(imaging_mode));
}
if (TM.addPassesToEmitMC(PM, Ctx, ObjStream))
llvm_unreachable("Target does not support MC emission.");
// Make sure SectionMemoryManager::getSymbolAddressInProcess can resolve
// symbols in the program as well. The nullptr argument to the function
// tells DynamicLibrary to load the program, not a library.
std::string *ErrorStr = nullptr;
if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
report_fatal_error("FATAL: unable to dlopen self\n" + *ErrorStr);
}
void JuliaOJIT::addGlobalMapping(StringRef Name, uint64_t Addr)
{
bool successful = GlobalSymbolTable.insert(std::make_pair(Name, (void*)Addr)).second;
(void)successful;
assert(successful);
}
void JuliaOJIT::addGlobalMapping(const GlobalValue *GV, void *Addr)
{
addGlobalMapping(getMangledName(GV), (uintptr_t)Addr);
}
void *JuliaOJIT::getPointerToGlobalIfAvailable(StringRef S)
{
SymbolTableT::const_iterator pos = GlobalSymbolTable.find(S);
if (pos != GlobalSymbolTable.end())
return pos->second;
return nullptr;
}
void *JuliaOJIT::getPointerToGlobalIfAvailable(const GlobalValue *GV)
{
return getPointerToGlobalIfAvailable(getMangledName(GV));
}
void JuliaOJIT::addModule(std::unique_ptr<Module> M)
{
#ifndef NDEBUG
// validate the relocations for M
for (Module::iterator I = M->begin(), E = M->end(); I != E; ) {
Function *F = &*I;
++I;
if (F->isDeclaration()) {
if (F->use_empty())
F->eraseFromParent();
else if (!(isIntrinsicFunction(F) ||
findUnmangledSymbol(F->getName()) ||
SectionMemoryManager::getSymbolAddressInProcess(
getMangledName(F->getName())))) {
std::cerr << "FATAL ERROR: "
<< "Symbol \"" << F->getName().str() << "\""
<< "not found";
abort();
}
}
}
#endif
JL_TIMING(LLVM_MODULE_FINISH);
// We need a memory manager to allocate memory and resolve symbols for this
// new module. Create one that resolves symbols by looking back into the JIT.
auto Resolver = orc::createLambdaResolver(
[&](const std::string &Name) {
// TODO: consider moving the FunctionMover resolver here
// Step 0: ObjectLinkingLayer has checked whether it is in the current module
// Step 1: See if it's something known to the ExecutionEngine
if (auto Sym = findSymbol(Name, true)) {
#if JL_LLVM_VERSION >= 40000
// `findSymbol` already eagerly resolved the address
// return it directly.
return Sym;
#else
return RuntimeDyld::SymbolInfo(Sym.getAddress(),
Sym.getFlags());
#endif
}
// Step 2: Search the program symbols
if (uint64_t addr = SectionMemoryManager::getSymbolAddressInProcess(Name))
return JL_SymbolInfo(addr, JITSymbolFlags::Exported);
#if defined(_OS_LINUX_)
if (uint64_t addr = resolve_atomic(Name.c_str()))
return JL_SymbolInfo(addr, JITSymbolFlags::Exported);
#endif
// Return failure code
return JL_SymbolInfo(nullptr);
},
[](const std::string &S) { return nullptr; }
);
SmallVector<std::unique_ptr<Module>,1> Ms;
Ms.push_back(std::move(M));
auto modset = CompileLayer.addModuleSet(std::move(Ms), MemMgr,
std::move(Resolver));
// Force LLVM to emit the module so that we can register the symbols
// in our lookup table.
CompileLayer.emitAndFinalize(modset);
}
void JuliaOJIT::removeModule(ModuleHandleT H)
{
CompileLayer.removeModuleSet(H);
}
JL_JITSymbol JuliaOJIT::findSymbol(const std::string &Name, bool ExportedSymbolsOnly)
{
void *Addr = nullptr;
if (ExportedSymbolsOnly) {
// Step 1: Check against list of known external globals
Addr = getPointerToGlobalIfAvailable(Name);
}
// Step 2: Search all previously emitted symbols
if (Addr == nullptr)
Addr = LocalSymbolTable[Name];
return JL_JITSymbol((uintptr_t)Addr, JITSymbolFlags::Exported);
}
JL_JITSymbol JuliaOJIT::findUnmangledSymbol(const std::string Name)
{
return findSymbol(getMangledName(Name), true);
}
uint64_t JuliaOJIT::getGlobalValueAddress(const std::string &Name)
{
return findSymbol(getMangledName(Name), false).getAddress();
}
uint64_t JuliaOJIT::getFunctionAddress(const std::string &Name)
{
return findSymbol(getMangledName(Name), false).getAddress();
}
Function *JuliaOJIT::FindFunctionNamed(const std::string &Name)
{
return shadow_output->getFunction(Name);
}
void JuliaOJIT::RegisterJITEventListener(JITEventListener *L)
{
// TODO
}
const DataLayout& JuliaOJIT::getDataLayout() const
{
return DL;
}
const Triple& JuliaOJIT::getTargetTriple() const
{
return TM.getTargetTriple();
}
std::string JuliaOJIT::getMangledName(const std::string &Name)
{
SmallString<128> FullName;
Mangler::getNameWithPrefix(FullName, Name, DL);
return FullName.str();
}
std::string JuliaOJIT::getMangledName(const GlobalValue *GV)
{
return getMangledName(GV->getName());
}
JuliaOJIT *jl_ExecutionEngine;
#else
ExecutionEngine *jl_ExecutionEngine;
#endif
// MSVC's link.exe requires each function declaration to have a Comdat section
// So rather than litter the code with conditionals,
// all global values that get emitted call this function
// and it decides whether the definition needs a Comdat section and adds the appropriate declaration
// TODO: consider moving this into jl_add_to_shadow or jl_dump_shadow? the JIT doesn't care, so most calls are now no-ops
template<class T> // for GlobalObject's
static T *addComdat(T *G)
{
#if defined(_OS_WINDOWS_) && JL_LLVM_VERSION >= 30500
if (imaging_mode && !G->isDeclaration()) {
// Add comdat information to make MSVC link.exe happy
// it's valid to emit this for ld.exe too,
// but makes it very slow to link for no benefit
if (G->getParent() == shadow_output) {
#if defined(_COMPILER_MICROSOFT_)
Comdat *jl_Comdat = G->getParent()->getOrInsertComdat(G->getName());
// ELF only supports Comdat::Any
jl_Comdat->setSelectionKind(Comdat::NoDuplicates);
G->setComdat(jl_Comdat);
#endif
#if defined(_CPU_X86_64_)
// Add unwind exception personalities to functions to handle async exceptions
assert(!juliapersonality_func || juliapersonality_func->getParent() == shadow_output);
if (Function *F = dyn_cast<Function>(G))
F->setPersonalityFn(juliapersonality_func);
#endif
}
// add __declspec(dllexport) to everything marked for export
if (G->getLinkage() == GlobalValue::ExternalLinkage)
G->setDLLStorageClass(GlobalValue::DLLExportStorageClass);
else
G->setDLLStorageClass(GlobalValue::DefaultStorageClass);
}
#endif
return G;
}
// destructively move the contents of src into dest
// this assumes that the targets of the two modules are the same
// including the DataLayout and ModuleFlags (for example)
// and that there is no module-level assembly
static void jl_merge_module(Module *dest, std::unique_ptr<Module> src)
{
assert(dest != src.get());
for (Module::global_iterator I = src->global_begin(), E = src->global_end(); I != E;) {
GlobalVariable *sG = &*I;
GlobalValue *dG = dest->getNamedValue(sG->getName());
++I;
// Replace a declaration with the definition:
if (dG) {
if (sG->isDeclaration()) {
sG->replaceAllUsesWith(dG);
sG->eraseFromParent();
continue;
}
else {
dG->replaceAllUsesWith(sG);
dG->eraseFromParent();
}
}
// Reparent the global variable:
sG->removeFromParent();
dest->getGlobalList().push_back(sG);
// Comdat is owned by the Module, recreate it in the new parent:
addComdat(sG);
}
for (Module::iterator I = src->begin(), E = src->end(); I != E;) {
Function *sG = &*I;
GlobalValue *dG = dest->getNamedValue(sG->getName());
++I;
// Replace a declaration with the definition:
if (dG) {
if (sG->isDeclaration()) {
sG->replaceAllUsesWith(dG);
sG->eraseFromParent();
continue;
}
else {
dG->replaceAllUsesWith(sG);
dG->eraseFromParent();
}
}
// Reparent the global variable:
sG->removeFromParent();
dest->getFunctionList().push_back(sG);
// Comdat is owned by the Module, recreate it in the new parent:
addComdat(sG);
}
for (Module::alias_iterator I = src->alias_begin(), E = src->alias_end(); I != E;) {
GlobalAlias *sG = &*I;
GlobalValue *dG = dest->getNamedValue(sG->getName());
++I;
if (dG) {
if (!dG->isDeclaration()) { // aliases are always definitions, so this test is reversed from the above two
sG->replaceAllUsesWith(dG);
sG->eraseFromParent();
continue;
}
else {
dG->replaceAllUsesWith(sG);
dG->eraseFromParent();
}
}
sG->removeFromParent();
dest->getAliasList().push_back(sG);
}
// metadata nodes need to be explicitly merged not just copied
// so there are special passes here for each known type of metadata
NamedMDNode *sNMD = src->getNamedMetadata("llvm.dbg.cu");
if (sNMD) {
NamedMDNode *dNMD = dest->getOrInsertNamedMetadata("llvm.dbg.cu");
#if JL_LLVM_VERSION >= 30500
for (NamedMDNode::op_iterator I = sNMD->op_begin(), E = sNMD->op_end(); I != E; ++I) {
dNMD->addOperand(*I);
}
#else
for (unsigned i = 0, l = sNMD->getNumOperands(); i < l; i++) {
dNMD->addOperand(sNMD->getOperand(i));
}
#endif
}
}
// to finalize a function, look up its name in the `module_for_fname` map of
// unfinalized functions and merge it, plus any other modules it depends upon,
// into `collector` then add `collector` to the execution engine
static StringMap<Module*> module_for_fname;
static void jl_merge_recursive(Module *m, Module *collector);
#if defined(USE_MCJIT) || defined(USE_ORCJIT)
static void jl_add_to_ee(std::unique_ptr<Module> m)
{
#if defined(_CPU_X86_64_) && defined(_OS_WINDOWS_) && JL_LLVM_VERSION >= 30500
// Add special values used by debuginfo to build the UnwindData table registration for Win64
ArrayType *atype = ArrayType::get(T_uint32, 3); // want 4-byte alignment of 12-bytes of data
(new GlobalVariable(*m, atype,
false, GlobalVariable::InternalLinkage,
ConstantAggregateZero::get(atype), "__UnwindData"))->setSection(".text");
(new GlobalVariable(*m, atype,
false, GlobalVariable::InternalLinkage,
ConstantAggregateZero::get(atype), "__catchjmp"))->setSection(".text");
#endif
assert(jl_ExecutionEngine);
#if JL_LLVM_VERSION >= 30600
jl_ExecutionEngine->addModule(std::move(m));
#else
jl_ExecutionEngine->addModule(m.release());
#endif
}
void jl_finalize_function(Function *F)
{
std::unique_ptr<Module> m(module_for_fname.lookup(F->getName()));
if (m) {
jl_merge_recursive(m.get(), m.get());
jl_add_to_ee(std::move(m));
}
}
#else
static bool jl_try_finalize(Module *m)
{
for (Module::iterator I = m->begin(), E = m->end(); I != E; ++I) {
Function *F = &*I;
if (F->isDeclaration() && !isIntrinsicFunction(F)) {
if (!jl_can_finalize_function(F))
return false;
}
}
jl_merge_recursive(m, shadow_output);
jl_merge_module(shadow_output, std::unique_ptr<Module>(m));
return true;
}
#endif
static void jl_finalize_function(const std::string &F, Module *collector)
{
std::unique_ptr<Module> m(module_for_fname.lookup(F));
if (m) {
jl_merge_recursive(m.get(), collector);
jl_merge_module(collector, std::move(m));
}
}
static void jl_merge_recursive(Module *m, Module *collector)
{
// probably not many unresolved declarations, but be sure to iterate over their Names,
// since the declarations may get destroyed by the jl_merge_module call.
// this is also why we copy the Name string, rather than save a StringRef
SmallVector<std::string, 8> to_finalize;
for (Module::iterator I = m->begin(), E = m->end(); I != E; ++I) {
Function *F = &*I;
if (!F->isDeclaration()) {
module_for_fname.erase(F->getName());
}
else if (!isIntrinsicFunction(F)) {
to_finalize.push_back(F->getName().str());
}
}
for (const auto F : to_finalize) {
jl_finalize_function(F, collector);
}
}
// see if any of the functions needed by F are still WIP
static StringSet<> incomplete_fname;
static bool jl_can_finalize_function(StringRef F, SmallSet<Module*, 16> &known)
{
if (incomplete_fname.find(F) != incomplete_fname.end())
return false;
Module *M = module_for_fname.lookup(F);
#if JL_LLVM_VERSION >= 30500
if (M && known.insert(M).second)
#else
if (M && known.insert(M))
#endif
{
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Function *F = &*I;
if (F->isDeclaration() && !isIntrinsicFunction(F)) {
if (!jl_can_finalize_function(F->getName(), known))
return false;
}
}
}
return true;
}
bool jl_can_finalize_function(Function *F)
{
SmallSet<Module*, 16> known;
return jl_can_finalize_function(F->getName(), known);
}
// let the JIT know this function is a WIP
void jl_init_function(Function *F)
{
incomplete_fname.insert(F->getName());
}
// this takes ownership of a module after code emission is complete
// and will add it to the execution engine when required (by jl_finalize_function)
void jl_finalize_module(Module *m, bool shadow)
{
#if !defined(USE_ORCJIT)
jl_globalPM->run(*m);
#endif
// record the function names that are part of this Module
// so it can be added to the JIT when needed
for (Module::iterator I = m->begin(), E = m->end(); I != E; ++I) {
Function *F = &*I;
if (!F->isDeclaration()) {
bool known = incomplete_fname.erase(F->getName());
(void)known; // TODO: assert(known); // llvmcall gets this wrong
module_for_fname[F->getName()] = m;
}
}
#if defined(USE_ORCJIT) || defined(USE_MCJIT)
// in the newer JITs, the shadow module is separate from the execution module
if (shadow)
jl_add_to_shadow(m);
#else
bool changes = jl_try_finalize(m);
while (changes) {
// this definitely isn't the most efficient, but it's only for the old LLVM 3.3 JIT
changes = false;
for (StringMap<Module*>::iterator MI = module_for_fname.begin(), ME = module_for_fname.end(); MI != ME; ++MI) {
changes |= jl_try_finalize(MI->second);
}
}
#endif
}
// helper function for adding a DLLImport (dlsym) address to the execution engine
// (for values created locally or in the sysimage, jl_emit_and_add_to_shadow is generally preferable)
#if JL_LLVM_VERSION >= 30500
void add_named_global(GlobalObject *gv, void *addr, bool dllimport)
#else
void add_named_global(GlobalValue *gv, void *addr, bool dllimport)
#endif
{
#ifdef _OS_WINDOWS_
// setting JL_DLLEXPORT correctly only matters when building a binary
// (global_proto will strip this from the JIT)
if (dllimport && imaging_mode) {
assert(gv->getLinkage() == GlobalValue::ExternalLinkage);
#if JL_LLVM_VERSION >= 30500
// add the __declspec(dllimport) attribute
gv->setDLLStorageClass(GlobalValue::DLLImportStorageClass);
#else
gv->setLinkage(GlobalValue::DLLImportLinkage);
#if defined(_P64)
// __imp_ variables are indirection pointers, so use malloc to simulate that
void **imp_addr = (void**)malloc(sizeof(void*));
*imp_addr = addr;
addr = (void*)imp_addr;
#endif
#endif
}
#endif // _OS_WINDOWS_
jl_ExecutionEngine->addGlobalMapping(gv, addr);
}
static std::vector<Constant*> jl_sysimg_gvars;
static std::vector<Constant*> jl_sysimg_fvars;
static std::map<void*, jl_value_llvm> jl_value_to_llvm;
// global variables to pointers are pretty common,
// so this method is available as a convenience for emitting them.
// for other types, the formula for implementation is straightforward:
// (see stringConstPtr, for an alternative example to the code below)
//
// if in imaging_mode, emit a GlobalVariable with the same name and an initializer to the shadow_module
// making it valid for emission and reloading in the sysimage
//
// then add a global mapping to the current value (usually from calloc'd space)
// to the execution engine to make it valid for the current session (with the current value)
void* jl_emit_and_add_to_shadow(GlobalVariable *gv, void *gvarinit)
{
PointerType *T = cast<PointerType>(gv->getType()->getElementType()); // pointer is the only supported type here
GlobalVariable *shadowvar = NULL;
#if defined(USE_MCJIT) || defined(USE_ORCJIT)
if (imaging_mode)
#endif
shadowvar = global_proto(gv, shadow_output);
if (shadowvar) {
shadowvar->setInitializer(ConstantPointerNull::get(T));
shadowvar->setLinkage(GlobalVariable::InternalLinkage);
addComdat(shadowvar);
if (imaging_mode && gvarinit) {
// make the pointer valid for future sessions
jl_sysimg_gvars.push_back(ConstantExpr::getBitCast(shadowvar, T_psize));
jl_value_llvm gv_struct;
gv_struct.gv = global_proto(gv);
gv_struct.index = jl_sysimg_gvars.size();
jl_value_to_llvm[gvarinit] = gv_struct;
}
}
// make the pointer valid for this session
#if defined(USE_MCJIT) || defined(USE_ORCJIT)
void *slot = calloc(1, sizeof(void*));
jl_ExecutionEngine->addGlobalMapping(gv, slot);
return slot;
#else
return jl_ExecutionEngine->getPointerToGlobal(shadowvar);
#endif
}
// Emit a slot in the system image to be filled at sysimg init time.
// Returns the global var. Fill `idx` with 1-base index in the sysimg gv.
// Use as an optimization for runtime constant addresses to have one less
// load. (Used only by threading).
GlobalVariable *jl_emit_sysimg_slot(Module *m, Type *typ, const char *name,
uintptr_t init, size_t &idx)
{
assert(imaging_mode);
// This is **NOT** a external variable or a normal global variable
// This is a special internal global slot with a special index
// in the global variable table.
GlobalVariable *gv = new GlobalVariable(*m, typ, false,
GlobalVariable::InternalLinkage,
ConstantPointerNull::get((PointerType*)typ), name);