1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MCJIT.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ExecutionEngine/GenericValue.h"
13 #include "llvm/ExecutionEngine/JITEventListener.h"
14 #include "llvm/ExecutionEngine/MCJIT.h"
15 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/DynamicLibrary.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/MutexGuard.h"
29 
30 using namespace llvm;
31 
32 void ObjectCache::anchor() {}
33 
34 namespace {
35 
36 static struct RegisterJIT {
37   RegisterJIT() { MCJIT::Register(); }
38 } JITRegistrator;
39 
40 }
41 
42 extern "C" void LLVMLinkInMCJIT() {
43 }
44 
45 ExecutionEngine*
46 MCJIT::createJIT(std::unique_ptr<Module> M,
47                  std::string *ErrorStr,
48                  std::shared_ptr<MCJITMemoryManager> MemMgr,
49                  std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
50                  std::unique_ptr<TargetMachine> TM) {
51   // Try to register the program as a source of symbols to resolve against.
52   //
53   // FIXME: Don't do this here.
54   sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
55 
56   if (!MemMgr || !Resolver) {
57     auto RTDyldMM = std::make_shared<SectionMemoryManager>();
58     if (!MemMgr)
59       MemMgr = RTDyldMM;
60     if (!Resolver)
61       Resolver = RTDyldMM;
62   }
63 
64   return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
65                    std::move(Resolver));
66 }
67 
68 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
69              std::shared_ptr<MCJITMemoryManager> MemMgr,
70              std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
71     : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
72       Ctx(nullptr), MemMgr(std::move(MemMgr)),
73       Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
74       ObjCache(nullptr) {
75   // FIXME: We are managing our modules, so we do not want the base class
76   // ExecutionEngine to manage them as well. To avoid double destruction
77   // of the first (and only) module added in ExecutionEngine constructor
78   // we remove it from EE and will destruct it ourselves.
79   //
80   // It may make sense to move our module manager (based on SmallStPtr) back
81   // into EE if the JIT and Interpreter can live with it.
82   // If so, additional functions: addModule, removeModule, FindFunctionNamed,
83   // runStaticConstructorsDestructors could be moved back to EE as well.
84   //
85   std::unique_ptr<Module> First = std::move(Modules[0]);
86   Modules.clear();
87 
88   if (First->getDataLayout().isDefault())
89     First->setDataLayout(getDataLayout());
90 
91   OwnedModules.addModule(std::move(First));
92   RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
93 }
94 
95 MCJIT::~MCJIT() {
96   MutexGuard locked(lock);
97 
98   Dyld.deregisterEHFrames();
99 
100   for (auto &Obj : LoadedObjects)
101     if (Obj)
102       NotifyFreeingObject(*Obj);
103 
104   Archives.clear();
105 }
106 
107 void MCJIT::addModule(std::unique_ptr<Module> M) {
108   MutexGuard locked(lock);
109 
110   if (M->getDataLayout().isDefault())
111     M->setDataLayout(getDataLayout());
112 
113   OwnedModules.addModule(std::move(M));
114 }
115 
116 bool MCJIT::removeModule(Module *M) {
117   MutexGuard locked(lock);
118   return OwnedModules.removeModule(M);
119 }
120 
121 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
122   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
123   if (Dyld.hasError())
124     report_fatal_error(Dyld.getErrorString());
125 
126   NotifyObjectEmitted(*Obj, *L);
127 
128   LoadedObjects.push_back(std::move(Obj));
129 }
130 
131 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
132   std::unique_ptr<object::ObjectFile> ObjFile;
133   std::unique_ptr<MemoryBuffer> MemBuf;
134   std::tie(ObjFile, MemBuf) = Obj.takeBinary();
135   addObjectFile(std::move(ObjFile));
136   Buffers.push_back(std::move(MemBuf));
137 }
138 
139 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
140   Archives.push_back(std::move(A));
141 }
142 
143 void MCJIT::setObjectCache(ObjectCache* NewCache) {
144   MutexGuard locked(lock);
145   ObjCache = NewCache;
146 }
147 
148 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
149   MutexGuard locked(lock);
150 
151   // This must be a module which has already been added but not loaded to this
152   // MCJIT instance, since these conditions are tested by our caller,
153   // generateCodeForModule.
154 
155   legacy::PassManager PM;
156 
157   // The RuntimeDyld will take ownership of this shortly
158   SmallVector<char, 4096> ObjBufferSV;
159   raw_svector_ostream ObjStream(ObjBufferSV);
160 
161   // Turn the machine code intermediate representation into bytes in memory
162   // that may be executed.
163   if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
164     report_fatal_error("Target does not support MC emission!");
165 
166   // Initialize passes.
167   PM.run(*M);
168   // Flush the output buffer to get the generated code into memory
169 
170   std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
171                                 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
172 
173   // If we have an object cache, tell it about the new object.
174   // Note that we're using the compiled image, not the loaded image (as below).
175   if (ObjCache) {
176     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
177     // to create a temporary object here and delete it after the call.
178     MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
179     ObjCache->notifyObjectCompiled(M, MB);
180   }
181 
182   return CompiledObjBuffer;
183 }
184 
185 void MCJIT::generateCodeForModule(Module *M) {
186   // Get a thread lock to make sure we aren't trying to load multiple times
187   MutexGuard locked(lock);
188 
189   // This must be a module which has already been added to this MCJIT instance.
190   assert(OwnedModules.ownsModule(M) &&
191          "MCJIT::generateCodeForModule: Unknown module.");
192 
193   // Re-compilation is not supported
194   if (OwnedModules.hasModuleBeenLoaded(M))
195     return;
196 
197   std::unique_ptr<MemoryBuffer> ObjectToLoad;
198   // Try to load the pre-compiled object from cache if possible
199   if (ObjCache)
200     ObjectToLoad = ObjCache->getObject(M);
201 
202   assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
203 
204   // If the cache did not contain a suitable object, compile the object
205   if (!ObjectToLoad) {
206     ObjectToLoad = emitObject(M);
207     assert(ObjectToLoad && "Compilation did not produce an object.");
208   }
209 
210   // Load the object into the dynamic linker.
211   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
212   Expected<std::unique_ptr<object::ObjectFile>> LoadedObject =
213     object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
214   if (!LoadedObject) {
215     std::string Buf;
216     raw_string_ostream OS(Buf);
217     logAllUnhandledErrors(LoadedObject.takeError(), OS, "");
218     OS.flush();
219     report_fatal_error(Buf);
220   }
221   std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
222     Dyld.loadObject(*LoadedObject.get());
223 
224   if (Dyld.hasError())
225     report_fatal_error(Dyld.getErrorString());
226 
227   NotifyObjectEmitted(*LoadedObject.get(), *L);
228 
229   Buffers.push_back(std::move(ObjectToLoad));
230   LoadedObjects.push_back(std::move(*LoadedObject));
231 
232   OwnedModules.markModuleAsLoaded(M);
233 }
234 
235 void MCJIT::finalizeLoadedModules() {
236   MutexGuard locked(lock);
237 
238   // Resolve any outstanding relocations.
239   Dyld.resolveRelocations();
240 
241   OwnedModules.markAllLoadedModulesAsFinalized();
242 
243   // Register EH frame data for any module we own which has been loaded
244   Dyld.registerEHFrames();
245 
246   // Set page permissions.
247   MemMgr->finalizeMemory();
248 }
249 
250 // FIXME: Rename this.
251 void MCJIT::finalizeObject() {
252   MutexGuard locked(lock);
253 
254   // Generate code for module is going to move objects out of the 'added' list,
255   // so we need to copy that out before using it:
256   SmallVector<Module*, 16> ModsToAdd;
257   for (auto M : OwnedModules.added())
258     ModsToAdd.push_back(M);
259 
260   for (auto M : ModsToAdd)
261     generateCodeForModule(M);
262 
263   finalizeLoadedModules();
264 }
265 
266 void MCJIT::finalizeModule(Module *M) {
267   MutexGuard locked(lock);
268 
269   // This must be a module which has already been added to this MCJIT instance.
270   assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
271 
272   // If the module hasn't been compiled, just do that.
273   if (!OwnedModules.hasModuleBeenLoaded(M))
274     generateCodeForModule(M);
275 
276   finalizeLoadedModules();
277 }
278 
279 RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
280   SmallString<128> FullName;
281   Mangler::getNameWithPrefix(FullName, Name, getDataLayout());
282 
283   if (void *Addr = getPointerToGlobalIfAvailable(FullName))
284     return RuntimeDyld::SymbolInfo(static_cast<uint64_t>(
285                                      reinterpret_cast<uintptr_t>(Addr)),
286                                    JITSymbolFlags::Exported);
287 
288   return Dyld.getSymbol(FullName);
289 }
290 
291 Module *MCJIT::findModuleForSymbol(const std::string &Name,
292                                    bool CheckFunctionsOnly) {
293   MutexGuard locked(lock);
294 
295   // If it hasn't already been generated, see if it's in one of our modules.
296   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
297                               E = OwnedModules.end_added();
298        I != E; ++I) {
299     Module *M = *I;
300     Function *F = M->getFunction(Name);
301     if (F && !F->isDeclaration())
302       return M;
303     if (!CheckFunctionsOnly) {
304       GlobalVariable *G = M->getGlobalVariable(Name);
305       if (G && !G->isDeclaration())
306         return M;
307       // FIXME: Do we need to worry about global aliases?
308     }
309   }
310   // We didn't find the symbol in any of our modules.
311   return nullptr;
312 }
313 
314 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
315                                  bool CheckFunctionsOnly) {
316   return findSymbol(Name, CheckFunctionsOnly).getAddress();
317 }
318 
319 RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
320                                           bool CheckFunctionsOnly) {
321   MutexGuard locked(lock);
322 
323   // First, check to see if we already have this symbol.
324   if (auto Sym = findExistingSymbol(Name))
325     return Sym;
326 
327   for (object::OwningBinary<object::Archive> &OB : Archives) {
328     object::Archive *A = OB.getBinary();
329     // Look for our symbols in each Archive
330     object::Archive::child_iterator ChildIt = A->findSym(Name);
331     if (std::error_code EC = ChildIt->getError())
332       report_fatal_error(EC.message());
333     if (ChildIt != A->child_end()) {
334       // FIXME: Support nested archives?
335       Expected<std::unique_ptr<object::Binary>> ChildBinOrErr =
336           (*ChildIt)->getAsBinary();
337       if (!ChildBinOrErr) {
338         // TODO: Actually report errors helpfully.
339         consumeError(ChildBinOrErr.takeError());
340         continue;
341       }
342       std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
343       if (ChildBin->isObject()) {
344         std::unique_ptr<object::ObjectFile> OF(
345             static_cast<object::ObjectFile *>(ChildBin.release()));
346         // This causes the object file to be loaded.
347         addObjectFile(std::move(OF));
348         // The address should be here now.
349         if (auto Sym = findExistingSymbol(Name))
350           return Sym;
351       }
352     }
353   }
354 
355   // If it hasn't already been generated, see if it's in one of our modules.
356   Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
357   if (M) {
358     generateCodeForModule(M);
359 
360     // Check the RuntimeDyld table again, it should be there now.
361     return findExistingSymbol(Name);
362   }
363 
364   // If a LazyFunctionCreator is installed, use it to get/create the function.
365   // FIXME: Should we instead have a LazySymbolCreator callback?
366   if (LazyFunctionCreator) {
367     auto Addr = static_cast<uint64_t>(
368                   reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
369     return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
370   }
371 
372   return nullptr;
373 }
374 
375 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
376   MutexGuard locked(lock);
377   uint64_t Result = getSymbolAddress(Name, false);
378   if (Result != 0)
379     finalizeLoadedModules();
380   return Result;
381 }
382 
383 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
384   MutexGuard locked(lock);
385   uint64_t Result = getSymbolAddress(Name, true);
386   if (Result != 0)
387     finalizeLoadedModules();
388   return Result;
389 }
390 
391 // Deprecated.  Use getFunctionAddress instead.
392 void *MCJIT::getPointerToFunction(Function *F) {
393   MutexGuard locked(lock);
394 
395   Mangler Mang;
396   SmallString<128> Name;
397   TM->getNameWithPrefix(Name, F, Mang);
398 
399   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
400     bool AbortOnFailure = !F->hasExternalWeakLinkage();
401     void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
402     updateGlobalMapping(F, Addr);
403     return Addr;
404   }
405 
406   Module *M = F->getParent();
407   bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
408 
409   // Make sure the relevant module has been compiled and loaded.
410   if (HasBeenAddedButNotLoaded)
411     generateCodeForModule(M);
412   else if (!OwnedModules.hasModuleBeenLoaded(M)) {
413     // If this function doesn't belong to one of our modules, we're done.
414     // FIXME: Asking for the pointer to a function that hasn't been registered,
415     //        and isn't a declaration (which is handled above) should probably
416     //        be an assertion.
417     return nullptr;
418   }
419 
420   // FIXME: Should the Dyld be retaining module information? Probably not.
421   //
422   // This is the accessor for the target address, so make sure to check the
423   // load address of the symbol, not the local address.
424   return (void*)Dyld.getSymbol(Name).getAddress();
425 }
426 
427 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
428     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
429   for (; I != E; ++I) {
430     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
431   }
432 }
433 
434 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
435   // Execute global ctors/dtors for each module in the program.
436   runStaticConstructorsDestructorsInModulePtrSet(
437       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
438   runStaticConstructorsDestructorsInModulePtrSet(
439       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
440   runStaticConstructorsDestructorsInModulePtrSet(
441       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
442 }
443 
444 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
445                                                  ModulePtrSet::iterator I,
446                                                  ModulePtrSet::iterator E) {
447   for (; I != E; ++I) {
448     Function *F = (*I)->getFunction(FnName);
449     if (F && !F->isDeclaration())
450       return F;
451   }
452   return nullptr;
453 }
454 
455 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
456                                                              bool AllowInternal,
457                                                              ModulePtrSet::iterator I,
458                                                              ModulePtrSet::iterator E) {
459   for (; I != E; ++I) {
460     GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
461     if (GV && !GV->isDeclaration())
462       return GV;
463   }
464   return nullptr;
465 }
466 
467 
468 Function *MCJIT::FindFunctionNamed(const char *FnName) {
469   Function *F = FindFunctionNamedInModulePtrSet(
470       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
471   if (!F)
472     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
473                                         OwnedModules.end_loaded());
474   if (!F)
475     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
476                                         OwnedModules.end_finalized());
477   return F;
478 }
479 
480 GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
481   GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
482       Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
483   if (!GV)
484     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
485                                         OwnedModules.end_loaded());
486   if (!GV)
487     GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
488                                         OwnedModules.end_finalized());
489   return GV;
490 }
491 
492 GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
493   assert(F && "Function *F was null at entry to run()");
494 
495   void *FPtr = getPointerToFunction(F);
496   finalizeModule(F->getParent());
497   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
498   FunctionType *FTy = F->getFunctionType();
499   Type *RetTy = FTy->getReturnType();
500 
501   assert((FTy->getNumParams() == ArgValues.size() ||
502           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
503          "Wrong number of arguments passed into function!");
504   assert(FTy->getNumParams() == ArgValues.size() &&
505          "This doesn't support passing arguments through varargs (yet)!");
506 
507   // Handle some common cases first.  These cases correspond to common `main'
508   // prototypes.
509   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
510     switch (ArgValues.size()) {
511     case 3:
512       if (FTy->getParamType(0)->isIntegerTy(32) &&
513           FTy->getParamType(1)->isPointerTy() &&
514           FTy->getParamType(2)->isPointerTy()) {
515         int (*PF)(int, char **, const char **) =
516           (int(*)(int, char **, const char **))(intptr_t)FPtr;
517 
518         // Call the function.
519         GenericValue rv;
520         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
521                                  (char **)GVTOP(ArgValues[1]),
522                                  (const char **)GVTOP(ArgValues[2])));
523         return rv;
524       }
525       break;
526     case 2:
527       if (FTy->getParamType(0)->isIntegerTy(32) &&
528           FTy->getParamType(1)->isPointerTy()) {
529         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
530 
531         // Call the function.
532         GenericValue rv;
533         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
534                                  (char **)GVTOP(ArgValues[1])));
535         return rv;
536       }
537       break;
538     case 1:
539       if (FTy->getNumParams() == 1 &&
540           FTy->getParamType(0)->isIntegerTy(32)) {
541         GenericValue rv;
542         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
543         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
544         return rv;
545       }
546       break;
547     }
548   }
549 
550   // Handle cases where no arguments are passed first.
551   if (ArgValues.empty()) {
552     GenericValue rv;
553     switch (RetTy->getTypeID()) {
554     default: llvm_unreachable("Unknown return type for function call!");
555     case Type::IntegerTyID: {
556       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
557       if (BitWidth == 1)
558         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
559       else if (BitWidth <= 8)
560         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
561       else if (BitWidth <= 16)
562         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
563       else if (BitWidth <= 32)
564         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
565       else if (BitWidth <= 64)
566         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
567       else
568         llvm_unreachable("Integer types > 64 bits not supported");
569       return rv;
570     }
571     case Type::VoidTyID:
572       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
573       return rv;
574     case Type::FloatTyID:
575       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
576       return rv;
577     case Type::DoubleTyID:
578       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
579       return rv;
580     case Type::X86_FP80TyID:
581     case Type::FP128TyID:
582     case Type::PPC_FP128TyID:
583       llvm_unreachable("long double not supported yet");
584     case Type::PointerTyID:
585       return PTOGV(((void*(*)())(intptr_t)FPtr)());
586     }
587   }
588 
589   llvm_unreachable("Full-featured argument passing not supported yet!");
590 }
591 
592 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
593   if (!isSymbolSearchingDisabled()) {
594     void *ptr =
595       reinterpret_cast<void*>(
596         static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
597     if (ptr)
598       return ptr;
599   }
600 
601   /// If a LazyFunctionCreator is installed, use it to get/create the function.
602   if (LazyFunctionCreator)
603     if (void *RP = LazyFunctionCreator(Name))
604       return RP;
605 
606   if (AbortOnFailure) {
607     report_fatal_error("Program used external function '"+Name+
608                        "' which could not be resolved!");
609   }
610   return nullptr;
611 }
612 
613 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
614   if (!L)
615     return;
616   MutexGuard locked(lock);
617   EventListeners.push_back(L);
618 }
619 
620 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
621   if (!L)
622     return;
623   MutexGuard locked(lock);
624   auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
625   if (I != EventListeners.rend()) {
626     std::swap(*I, EventListeners.back());
627     EventListeners.pop_back();
628   }
629 }
630 
631 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
632                                 const RuntimeDyld::LoadedObjectInfo &L) {
633   MutexGuard locked(lock);
634   MemMgr->notifyObjectLoaded(this, Obj);
635   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
636     EventListeners[I]->NotifyObjectEmitted(Obj, L);
637   }
638 }
639 
640 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
641   MutexGuard locked(lock);
642   for (JITEventListener *L : EventListeners)
643     L->NotifyFreeingObject(Obj);
644 }
645 
646 RuntimeDyld::SymbolInfo
647 LinkingSymbolResolver::findSymbol(const std::string &Name) {
648   auto Result = ParentEngine.findSymbol(Name, false);
649   // If the symbols wasn't found and it begins with an underscore, try again
650   // without the underscore.
651   if (!Result && Name[0] == '_')
652     Result = ParentEngine.findSymbol(Name.substr(1), false);
653   if (Result)
654     return Result;
655   if (ParentEngine.isSymbolSearchingDisabled())
656     return nullptr;
657   return ClientResolver->findSymbol(Name);
658 }
659