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