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