Make it explicit that ExecutionEngine takes ownership of the modules.
[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
111
112 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
113   ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
114   if (!LoadedObject || Dyld.hasError())
115     report_fatal_error(Dyld.getErrorString());
116
117   LoadedObjects.push_back(LoadedObject);
118
119   NotifyObjectEmitted(*LoadedObject);
120 }
121
122 void MCJIT::addArchive(std::unique_ptr<object::Archive> A) {
123   Archives.push_back(std::move(A));
124 }
125
126
127 void MCJIT::setObjectCache(ObjectCache* NewCache) {
128   MutexGuard locked(lock);
129   ObjCache = NewCache;
130 }
131
132 ObjectBufferStream* MCJIT::emitObject(Module *M) {
133   MutexGuard locked(lock);
134
135   // This must be a module which has already been added but not loaded to this
136   // MCJIT instance, since these conditions are tested by our caller,
137   // generateCodeForModule.
138
139   PassManager PM;
140
141   M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
142   PM.add(new DataLayoutPass(M));
143
144   // The RuntimeDyld will take ownership of this shortly
145   std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
146
147   // Turn the machine code intermediate representation into bytes in memory
148   // that may be executed.
149   if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
150                             !getVerifyModules())) {
151     report_fatal_error("Target does not support MC emission!");
152   }
153
154   // Initialize passes.
155   PM.run(*M);
156   // Flush the output buffer to get the generated code into memory
157   CompiledObject->flush();
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     std::unique_ptr<MemoryBuffer> MB = CompiledObject->getMemBuffer();
165     ObjCache->notifyObjectCompiled(M, MB.get());
166   }
167
168   return CompiledObject.release();
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<ObjectBuffer> ObjectToLoad;
184   // Try to load the pre-compiled object from cache if possible
185   if (ObjCache) {
186     std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
187     if (PreCompiledObject.get())
188       ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
189   }
190
191   // If the cache did not contain a suitable object, compile the object
192   if (!ObjectToLoad) {
193     ObjectToLoad.reset(emitObject(M));
194     assert(ObjectToLoad.get() && "Compilation did not produce an object.");
195   }
196
197   // Load the object into the dynamic linker.
198   // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
199   ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
200   LoadedObjects.push_back(LoadedObject);
201   if (!LoadedObject)
202     report_fatal_error(Dyld.getErrorString());
203
204   // FIXME: Make this optional, maybe even move it to a JIT event listener
205   LoadedObject->registerWithDebugger();
206
207   NotifyObjectEmitted(*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   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
232                               E = OwnedModules.end_added();
233        I != E; ++I) {
234     Module *M = *I;
235     generateCodeForModule(M);
236   }
237
238   finalizeLoadedModules();
239 }
240
241 void MCJIT::finalizeModule(Module *M) {
242   MutexGuard locked(lock);
243
244   // This must be a module which has already been added to this MCJIT instance.
245   assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
246
247   // If the module hasn't been compiled, just do that.
248   if (!OwnedModules.hasModuleBeenLoaded(M))
249     generateCodeForModule(M);
250
251   finalizeLoadedModules();
252 }
253
254 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
255   report_fatal_error("not yet implemented");
256 }
257
258 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
259   Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
260   SmallString<128> FullName;
261   Mang.getNameWithPrefix(FullName, Name);
262   return Dyld.getSymbolLoadAddress(FullName);
263 }
264
265 Module *MCJIT::findModuleForSymbol(const std::string &Name,
266                                    bool CheckFunctionsOnly) {
267   MutexGuard locked(lock);
268
269   // If it hasn't already been generated, see if it's in one of our modules.
270   for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
271                               E = OwnedModules.end_added();
272        I != E; ++I) {
273     Module *M = *I;
274     Function *F = M->getFunction(Name);
275     if (F && !F->isDeclaration())
276       return M;
277     if (!CheckFunctionsOnly) {
278       GlobalVariable *G = M->getGlobalVariable(Name);
279       if (G && !G->isDeclaration())
280         return M;
281       // FIXME: Do we need to worry about global aliases?
282     }
283   }
284   // We didn't find the symbol in any of our modules.
285   return nullptr;
286 }
287
288 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
289                                  bool CheckFunctionsOnly)
290 {
291   MutexGuard locked(lock);
292
293   // First, check to see if we already have this symbol.
294   uint64_t Addr = getExistingSymbolAddress(Name);
295   if (Addr)
296     return Addr;
297
298   for (std::unique_ptr<object::Archive> &A : Archives) {
299     // Look for our symbols in each Archive
300     object::Archive::child_iterator ChildIt = A->findSym(Name);
301     if (ChildIt != A->child_end()) {
302       // FIXME: Support nested archives?
303       ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
304           ChildIt->getAsBinary();
305       if (ChildBinOrErr.getError())
306         continue;
307       std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
308       if (ChildBin->isObject()) {
309         std::unique_ptr<object::ObjectFile> OF(
310             static_cast<object::ObjectFile *>(ChildBin.release()));
311         // This causes the object file to be loaded.
312         addObjectFile(std::move(OF));
313         // The address should be here now.
314         Addr = getExistingSymbolAddress(Name);
315         if (Addr)
316           return Addr;
317       }
318     }
319   }
320
321   // If it hasn't already been generated, see if it's in one of our modules.
322   Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
323   if (M) {
324     generateCodeForModule(M);
325
326     // Check the RuntimeDyld table again, it should be there now.
327     return getExistingSymbolAddress(Name);
328   }
329
330   // If a LazyFunctionCreator is installed, use it to get/create the function.
331   // FIXME: Should we instead have a LazySymbolCreator callback?
332   if (LazyFunctionCreator)
333     Addr = (uint64_t)LazyFunctionCreator(Name);
334
335   return Addr;
336 }
337
338 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
339   MutexGuard locked(lock);
340   uint64_t Result = getSymbolAddress(Name, false);
341   if (Result != 0)
342     finalizeLoadedModules();
343   return Result;
344 }
345
346 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
347   MutexGuard locked(lock);
348   uint64_t Result = getSymbolAddress(Name, true);
349   if (Result != 0)
350     finalizeLoadedModules();
351   return Result;
352 }
353
354 // Deprecated.  Use getFunctionAddress instead.
355 void *MCJIT::getPointerToFunction(Function *F) {
356   MutexGuard locked(lock);
357
358   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
359     bool AbortOnFailure = !F->hasExternalWeakLinkage();
360     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
361     addGlobalMapping(F, Addr);
362     return Addr;
363   }
364
365   Module *M = F->getParent();
366   bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
367
368   // Make sure the relevant module has been compiled and loaded.
369   if (HasBeenAddedButNotLoaded)
370     generateCodeForModule(M);
371   else if (!OwnedModules.hasModuleBeenLoaded(M))
372     // If this function doesn't belong to one of our modules, we're done.
373     return nullptr;
374
375   // FIXME: Should the Dyld be retaining module information? Probably not.
376   //
377   // This is the accessor for the target address, so make sure to check the
378   // load address of the symbol, not the local address.
379   Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
380   SmallString<128> Name;
381   TM->getNameWithPrefix(Name, F, Mang);
382   return (void*)Dyld.getSymbolLoadAddress(Name);
383 }
384
385 void *MCJIT::recompileAndRelinkFunction(Function *F) {
386   report_fatal_error("not yet implemented");
387 }
388
389 void MCJIT::freeMachineCodeForFunction(Function *F) {
390   report_fatal_error("not yet implemented");
391 }
392
393 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
394     bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
395   for (; I != E; ++I) {
396     ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
397   }
398 }
399
400 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
401   // Execute global ctors/dtors for each module in the program.
402   runStaticConstructorsDestructorsInModulePtrSet(
403       isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
404   runStaticConstructorsDestructorsInModulePtrSet(
405       isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
406   runStaticConstructorsDestructorsInModulePtrSet(
407       isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
408 }
409
410 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
411                                                  ModulePtrSet::iterator I,
412                                                  ModulePtrSet::iterator E) {
413   for (; I != E; ++I) {
414     if (Function *F = (*I)->getFunction(FnName))
415       return F;
416   }
417   return nullptr;
418 }
419
420 Function *MCJIT::FindFunctionNamed(const char *FnName) {
421   Function *F = FindFunctionNamedInModulePtrSet(
422       FnName, OwnedModules.begin_added(), OwnedModules.end_added());
423   if (!F)
424     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
425                                         OwnedModules.end_loaded());
426   if (!F)
427     F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
428                                         OwnedModules.end_finalized());
429   return F;
430 }
431
432 GenericValue MCJIT::runFunction(Function *F,
433                                 const std::vector<GenericValue> &ArgValues) {
434   assert(F && "Function *F was null at entry to run()");
435
436   void *FPtr = getPointerToFunction(F);
437   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
438   FunctionType *FTy = F->getFunctionType();
439   Type *RetTy = FTy->getReturnType();
440
441   assert((FTy->getNumParams() == ArgValues.size() ||
442           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
443          "Wrong number of arguments passed into function!");
444   assert(FTy->getNumParams() == ArgValues.size() &&
445          "This doesn't support passing arguments through varargs (yet)!");
446
447   // Handle some common cases first.  These cases correspond to common `main'
448   // prototypes.
449   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
450     switch (ArgValues.size()) {
451     case 3:
452       if (FTy->getParamType(0)->isIntegerTy(32) &&
453           FTy->getParamType(1)->isPointerTy() &&
454           FTy->getParamType(2)->isPointerTy()) {
455         int (*PF)(int, char **, const char **) =
456           (int(*)(int, char **, const char **))(intptr_t)FPtr;
457
458         // Call the function.
459         GenericValue rv;
460         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
461                                  (char **)GVTOP(ArgValues[1]),
462                                  (const char **)GVTOP(ArgValues[2])));
463         return rv;
464       }
465       break;
466     case 2:
467       if (FTy->getParamType(0)->isIntegerTy(32) &&
468           FTy->getParamType(1)->isPointerTy()) {
469         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
470
471         // Call the function.
472         GenericValue rv;
473         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
474                                  (char **)GVTOP(ArgValues[1])));
475         return rv;
476       }
477       break;
478     case 1:
479       if (FTy->getNumParams() == 1 &&
480           FTy->getParamType(0)->isIntegerTy(32)) {
481         GenericValue rv;
482         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
483         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
484         return rv;
485       }
486       break;
487     }
488   }
489
490   // Handle cases where no arguments are passed first.
491   if (ArgValues.empty()) {
492     GenericValue rv;
493     switch (RetTy->getTypeID()) {
494     default: llvm_unreachable("Unknown return type for function call!");
495     case Type::IntegerTyID: {
496       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
497       if (BitWidth == 1)
498         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
499       else if (BitWidth <= 8)
500         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
501       else if (BitWidth <= 16)
502         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
503       else if (BitWidth <= 32)
504         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
505       else if (BitWidth <= 64)
506         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
507       else
508         llvm_unreachable("Integer types > 64 bits not supported");
509       return rv;
510     }
511     case Type::VoidTyID:
512       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
513       return rv;
514     case Type::FloatTyID:
515       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
516       return rv;
517     case Type::DoubleTyID:
518       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
519       return rv;
520     case Type::X86_FP80TyID:
521     case Type::FP128TyID:
522     case Type::PPC_FP128TyID:
523       llvm_unreachable("long double not supported yet");
524     case Type::PointerTyID:
525       return PTOGV(((void*(*)())(intptr_t)FPtr)());
526     }
527   }
528
529   llvm_unreachable("Full-featured argument passing not supported yet!");
530 }
531
532 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
533                                        bool AbortOnFailure) {
534   if (!isSymbolSearchingDisabled()) {
535     void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
536     if (ptr)
537       return ptr;
538   }
539
540   /// If a LazyFunctionCreator is installed, use it to get/create the function.
541   if (LazyFunctionCreator)
542     if (void *RP = LazyFunctionCreator(Name))
543       return RP;
544
545   if (AbortOnFailure) {
546     report_fatal_error("Program used external function '"+Name+
547                        "' which could not be resolved!");
548   }
549   return nullptr;
550 }
551
552 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
553   if (!L)
554     return;
555   MutexGuard locked(lock);
556   EventListeners.push_back(L);
557 }
558 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
559   if (!L)
560     return;
561   MutexGuard locked(lock);
562   SmallVector<JITEventListener*, 2>::reverse_iterator I=
563       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
564   if (I != EventListeners.rend()) {
565     std::swap(*I, EventListeners.back());
566     EventListeners.pop_back();
567   }
568 }
569 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
570   MutexGuard locked(lock);
571   MemMgr.notifyObjectLoaded(this, &Obj);
572   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
573     EventListeners[I]->NotifyObjectEmitted(Obj);
574   }
575 }
576 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
577   MutexGuard locked(lock);
578   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
579     EventListeners[I]->NotifyFreeingObject(Obj);
580   }
581 }
582
583 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
584   uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
585   // If the symbols wasn't found and it begins with an underscore, try again
586   // without the underscore.
587   if (!Result && Name[0] == '_')
588     Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
589   if (Result)
590     return Result;
591   if (ParentEngine->isSymbolSearchingDisabled())
592     return 0;
593   return ClientMM->getSymbolAddress(Name);
594 }