Reinstate "Nuke the old JIT."
[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/Support/MutexGuard.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetSubtargetInfo.h"
32
33 using namespace llvm;
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                                   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), TM,
56                    MemMgr ? MemMgr : new SectionMemoryManager());
57 }
58
59 MCJIT::MCJIT(std::unique_ptr<Module> M, TargetMachine *tm,
60              RTDyldMemoryManager *MM)
61     : ExecutionEngine(std::move(M)), TM(tm), Ctx(nullptr), MemMgr(this, MM),
62       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 }
79
80 MCJIT::~MCJIT() {
81   MutexGuard locked(lock);
82
83   Dyld.deregisterEHFrames();
84
85   LoadedObjectList::iterator it, end;
86   for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
87     ObjectImage *Obj = *it;
88     if (Obj) {
89       NotifyFreeingObject(*Obj);
90       delete Obj;
91     }
92   }
93   LoadedObjects.clear();
94
95   Archives.clear();
96
97   delete TM;
98 }
99
100 void MCJIT::addModule(std::unique_ptr<Module> M) {
101   MutexGuard locked(lock);
102   OwnedModules.addModule(std::move(M));
103 }
104
105 bool MCJIT::removeModule(Module *M) {
106   MutexGuard locked(lock);
107   return OwnedModules.removeModule(M);
108 }
109
110 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
111   ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
112   if (!LoadedObject || Dyld.hasError())
113     report_fatal_error(Dyld.getErrorString());
114
115   LoadedObjects.push_back(LoadedObject);
116
117   NotifyObjectEmitted(*LoadedObject);
118 }
119
120 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
121   addObjectFile(std::move(Obj.getBinary()));
122   Buffers.push_back(std::move(Obj.getBuffer()));
123 }
124
125 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
126   Archives.push_back(std::move(A));
127 }
128
129 void MCJIT::setObjectCache(ObjectCache* NewCache) {
130   MutexGuard locked(lock);
131   ObjCache = NewCache;
132 }
133
134 ObjectBufferStream* MCJIT::emitObject(Module *M) {
135   MutexGuard locked(lock);
136
137   // This must be a module which has already been added but not loaded to this
138   // MCJIT instance, since these conditions are tested by our caller,
139   // generateCodeForModule.
140
141   PassManager PM;
142
143   M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
144   PM.add(new DataLayoutPass(M));
145
146   // The RuntimeDyld will take ownership of this shortly
147   std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
148
149   // Turn the machine code intermediate representation into bytes in memory
150   // that may be executed.
151   if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
152                             !getVerifyModules())) {
153     report_fatal_error("Target does not support MC emission!");
154   }
155
156   // Initialize passes.
157   PM.run(*M);
158   // Flush the output buffer to get the generated code into memory
159   CompiledObject->flush();
160
161   // If we have an object cache, tell it about the new object.
162   // Note that we're using the compiled image, not the loaded image (as below).
163   if (ObjCache) {
164     // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
165     // to create a temporary object here and delete it after the call.
166     MemoryBufferRef MB = CompiledObject->getMemBuffer();
167     ObjCache->notifyObjectCompiled(M, MB);
168   }
169
170   return CompiledObject.release();
171 }
172
173 void MCJIT::generateCodeForModule(Module *M) {
174   // Get a thread lock to make sure we aren't trying to load multiple times
175   MutexGuard locked(lock);
176
177   // This must be a module which has already been added to this MCJIT instance.
178   assert(OwnedModules.ownsModule(M) &&
179          "MCJIT::generateCodeForModule: Unknown module.");
180
181   // Re-compilation is not supported
182   if (OwnedModules.hasModuleBeenLoaded(M))
183     return;
184
185   std::unique_ptr<ObjectBuffer> ObjectToLoad;
186   // Try to load the pre-compiled object from cache if possible
187   if (ObjCache) {
188     std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
189     if (PreCompiledObject.get())
190       ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
191   }
192
193   // If the cache did not contain a suitable object, compile the object
194   if (!ObjectToLoad) {
195     ObjectToLoad.reset(emitObject(M));
196     assert(ObjectToLoad.get() && "Compilation did not produce an object.");
197   }
198
199   // Load the object into the dynamic linker.
200   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
201   ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
202   LoadedObjects.push_back(LoadedObject);
203   if (!LoadedObject)
204     report_fatal_error(Dyld.getErrorString());
205
206   // FIXME: Make this optional, maybe even move it to a JIT event listener
207   LoadedObject->registerWithDebugger();
208
209   NotifyObjectEmitted(*LoadedObject);
210
211   OwnedModules.markModuleAsLoaded(M);
212 }
213
214 void MCJIT::finalizeLoadedModules() {
215   MutexGuard locked(lock);
216
217   // Resolve any outstanding relocations.
218   Dyld.resolveRelocations();
219
220   OwnedModules.markAllLoadedModulesAsFinalized();
221
222   // Register EH frame data for any module we own which has been loaded
223   Dyld.registerEHFrames();
224
225   // Set page permissions.
226   MemMgr.finalizeMemory();
227 }
228
229 // FIXME: Rename this.
230 void MCJIT::finalizeObject() {
231   MutexGuard locked(lock);
232
233   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
234                               E = OwnedModules.end_added();
235        I != E; ++I) {
236     Module *M = *I;
237     generateCodeForModule(M);
238   }
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().get();
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   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->getSubtargetImpl()->getDataLayout());
379   SmallString<128> Name;
380   TM->getNameWithPrefix(Name, F, Mang);
381   return (void*)Dyld.getSymbolLoadAddress(Name);
382 }
383
384 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
385     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
386   for (; I != E; ++I) {
387     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
388   }
389 }
390
391 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
392   // Execute global ctors/dtors for each module in the program.
393   runStaticConstructorsDestructorsInModulePtrSet(
394       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
395   runStaticConstructorsDestructorsInModulePtrSet(
396       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
397   runStaticConstructorsDestructorsInModulePtrSet(
398       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
399 }
400
401 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
402                                                  ModulePtrSet::iterator I,
403                                                  ModulePtrSet::iterator E) {
404   for (; I != E; ++I) {
405     if (Function *F = (*I)->getFunction(FnName))
406       return F;
407   }
408   return nullptr;
409 }
410
411 Function *MCJIT::FindFunctionNamed(const char *FnName) {
412   Function *F = FindFunctionNamedInModulePtrSet(
413       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
414   if (!F)
415     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
416                                         OwnedModules.end_loaded());
417   if (!F)
418     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
419                                         OwnedModules.end_finalized());
420   return F;
421 }
422
423 GenericValue MCJIT::runFunction(Function *F,
424                                 const std::vector<GenericValue> &ArgValues) {
425   assert(F && "Function *F was null at entry to run()");
426
427   void *FPtr = getPointerToFunction(F);
428   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
429   FunctionType *FTy = F->getFunctionType();
430   Type *RetTy = FTy->getReturnType();
431
432   assert((FTy->getNumParams() == ArgValues.size() ||
433           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
434          "Wrong number of arguments passed into function!");
435   assert(FTy->getNumParams() == ArgValues.size() &&
436          "This doesn't support passing arguments through varargs (yet)!");
437
438   // Handle some common cases first.  These cases correspond to common `main'
439   // prototypes.
440   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
441     switch (ArgValues.size()) {
442     case 3:
443       if (FTy->getParamType(0)->isIntegerTy(32) &&
444           FTy->getParamType(1)->isPointerTy() &&
445           FTy->getParamType(2)->isPointerTy()) {
446         int (*PF)(int, char **, const char **) =
447           (int(*)(int, char **, const char **))(intptr_t)FPtr;
448
449         // Call the function.
450         GenericValue rv;
451         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
452                                  (char **)GVTOP(ArgValues[1]),
453                                  (const char **)GVTOP(ArgValues[2])));
454         return rv;
455       }
456       break;
457     case 2:
458       if (FTy->getParamType(0)->isIntegerTy(32) &&
459           FTy->getParamType(1)->isPointerTy()) {
460         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
461
462         // Call the function.
463         GenericValue rv;
464         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
465                                  (char **)GVTOP(ArgValues[1])));
466         return rv;
467       }
468       break;
469     case 1:
470       if (FTy->getNumParams() == 1 &&
471           FTy->getParamType(0)->isIntegerTy(32)) {
472         GenericValue rv;
473         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
474         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
475         return rv;
476       }
477       break;
478     }
479   }
480
481   // Handle cases where no arguments are passed first.
482   if (ArgValues.empty()) {
483     GenericValue rv;
484     switch (RetTy->getTypeID()) {
485     default: llvm_unreachable("Unknown return type for function call!");
486     case Type::IntegerTyID: {
487       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
488       if (BitWidth == 1)
489         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
490       else if (BitWidth <= 8)
491         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
492       else if (BitWidth <= 16)
493         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
494       else if (BitWidth <= 32)
495         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
496       else if (BitWidth <= 64)
497         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
498       else
499         llvm_unreachable("Integer types > 64 bits not supported");
500       return rv;
501     }
502     case Type::VoidTyID:
503       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
504       return rv;
505     case Type::FloatTyID:
506       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
507       return rv;
508     case Type::DoubleTyID:
509       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
510       return rv;
511     case Type::X86_FP80TyID:
512     case Type::FP128TyID:
513     case Type::PPC_FP128TyID:
514       llvm_unreachable("long double not supported yet");
515     case Type::PointerTyID:
516       return PTOGV(((void*(*)())(intptr_t)FPtr)());
517     }
518   }
519
520   llvm_unreachable("Full-featured argument passing not supported yet!");
521 }
522
523 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
524                                        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 (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
569     JITEventListener *L = EventListeners[I];
570     L->NotifyFreeingObject(Obj);
571   }
572 }
573
574 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
575   uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
576   // If the symbols wasn't found and it begins with an underscore, try again
577   // without the underscore.
578   if (!Result && Name[0] == '_')
579     Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
580   if (Result)
581     return Result;
582   if (ParentEngine->isSymbolSearchingDisabled())
583     return 0;
584   return ClientMM->getSymbolAddress(Name);
585 }