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