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