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