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