1 //===-- MCJIT.cpp - MC-based Just-in-Time Compiler ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
34 static struct RegisterJIT {
35 RegisterJIT() { MCJIT::Register(); }
40 extern "C" void LLVMLinkInMCJIT() {
43 ExecutionEngine *MCJIT::createJIT(Module *M,
44 std::string *ErrorStr,
45 RTDyldMemoryManager *MemMgr,
48 // Try to register the program as a source of symbols to resolve against.
50 // FIXME: Don't do this here.
51 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
53 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
57 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
58 bool AllocateGVsWithCode)
59 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(this, MM), Dyld(&MemMgr),
62 OwnedModules.addModule(m);
63 setDataLayout(TM->getDataLayout());
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.
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.
79 Dyld.deregisterEHFrames();
81 LoadedObjectMap::iterator it, end = LoadedObjects.end();
82 for (it = LoadedObjects.begin(); it != end; ++it) {
83 ObjectImage *Obj = it->second;
85 NotifyFreeingObject(*Obj);
89 LoadedObjects.clear();
93 void MCJIT::addModule(Module *M) {
94 MutexGuard locked(lock);
95 OwnedModules.addModule(M);
98 bool MCJIT::removeModule(Module *M) {
99 MutexGuard locked(lock);
100 return OwnedModules.removeModule(M);
105 void MCJIT::setObjectCache(ObjectCache* NewCache) {
106 MutexGuard locked(lock);
110 ObjectBufferStream* MCJIT::emitObject(Module *M) {
111 MutexGuard locked(lock);
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.
119 PM.add(new DataLayout(*TM->getDataLayout()));
121 // The RuntimeDyld will take ownership of this shortly
122 OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
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!");
130 // Initialize passes.
132 // Flush the output buffer to get the generated code into memory
133 CompiledObject->flush();
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).
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());
144 return CompiledObject.take();
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);
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.");
155 // Re-compilation is not supported
156 if (OwnedModules.hasModuleBeenLoaded(M))
159 OwningPtr<ObjectBuffer> ObjectToLoad;
160 // Try to load the pre-compiled object from cache if possible
162 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
163 if (0 != PreCompiledObject.get())
164 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
167 // If the cache did not contain a suitable object, compile the object
169 ObjectToLoad.reset(emitObject(M));
170 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
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;
178 report_fatal_error(Dyld.getErrorString());
180 // FIXME: Make this optional, maybe even move it to a JIT event listener
181 LoadedObject->registerWithDebugger();
183 NotifyObjectEmitted(*LoadedObject);
185 OwnedModules.markModuleAsLoaded(M);
188 void MCJIT::finalizeLoadedModules() {
189 MutexGuard locked(lock);
191 // Resolve any outstanding relocations.
192 Dyld.resolveRelocations();
194 OwnedModules.markAllLoadedModulesAsFinalized();
196 // Register EH frame data for any module we own which has been loaded
197 Dyld.registerEHFrames();
199 // Set page permissions.
200 MemMgr.finalizeMemory();
203 // FIXME: Rename this.
204 void MCJIT::finalizeObject() {
205 MutexGuard locked(lock);
207 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
208 E = OwnedModules.end_added();
211 generateCodeForModule(M);
214 finalizeLoadedModules();
217 void MCJIT::finalizeModule(Module *M) {
218 MutexGuard locked(lock);
220 // This must be a module which has already been added to this MCJIT instance.
221 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
223 // If the module hasn't been compiled, just do that.
224 if (!OwnedModules.hasModuleBeenLoaded(M))
225 generateCodeForModule(M);
227 finalizeLoadedModules();
230 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
231 report_fatal_error("not yet implemented");
234 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
236 SmallString<128> FullName;
237 Mang.getNameWithPrefix(FullName, Name);
238 return Dyld.getSymbolLoadAddress(FullName);
241 Module *MCJIT::findModuleForSymbol(const std::string &Name,
242 bool CheckFunctionsOnly) {
243 MutexGuard locked(lock);
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();
250 Function *F = M->getFunction(Name);
251 if (F && !F->isDeclaration())
253 if (!CheckFunctionsOnly) {
254 GlobalVariable *G = M->getGlobalVariable(Name);
255 if (G && !G->isDeclaration())
257 // FIXME: Do we need to worry about global aliases?
260 // We didn't find the symbol in any of our modules.
264 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
265 bool CheckFunctionsOnly)
267 MutexGuard locked(lock);
269 // First, check to see if we already have this symbol.
270 uint64_t Addr = getExistingSymbolAddress(Name);
274 // If it hasn't already been generated, see if it's in one of our modules.
275 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
279 generateCodeForModule(M);
281 // Check the RuntimeDyld table again, it should be there now.
282 return getExistingSymbolAddress(Name);
285 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
286 MutexGuard locked(lock);
287 uint64_t Result = getSymbolAddress(Name, false);
289 finalizeLoadedModules();
293 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
294 MutexGuard locked(lock);
295 uint64_t Result = getSymbolAddress(Name, true);
297 finalizeLoadedModules();
301 // Deprecated. Use getFunctionAddress instead.
302 void *MCJIT::getPointerToFunction(Function *F) {
303 MutexGuard locked(lock);
305 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
306 bool AbortOnFailure = !F->hasExternalWeakLinkage();
307 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
308 addGlobalMapping(F, Addr);
312 Module *M = F->getParent();
313 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
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.
322 // FIXME: Should the Dyld be retaining module information? Probably not.
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.
327 SmallString<128> Name;
328 Mang.getNameWithPrefix(Name, F);
329 return (void*)Dyld.getSymbolLoadAddress(Name);
332 void *MCJIT::recompileAndRelinkFunction(Function *F) {
333 report_fatal_error("not yet implemented");
336 void MCJIT::freeMachineCodeForFunction(Function *F) {
337 report_fatal_error("not yet implemented");
340 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
341 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
342 for (; I != E; ++I) {
343 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
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());
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))
367 Function *MCJIT::FindFunctionNamed(const char *FnName) {
368 Function *F = FindFunctionNamedInModulePtrSet(
369 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
371 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
372 OwnedModules.end_loaded());
374 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
375 OwnedModules.end_finalized());
379 GenericValue MCJIT::runFunction(Function *F,
380 const std::vector<GenericValue> &ArgValues) {
381 assert(F && "Function *F was null at entry to run()");
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();
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)!");
394 // Handle some common cases first. These cases correspond to common `main'
396 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
397 switch (ArgValues.size()) {
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;
405 // Call the function.
407 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
408 (char **)GVTOP(ArgValues[1]),
409 (const char **)GVTOP(ArgValues[2])));
414 if (FTy->getParamType(0)->isIntegerTy(32) &&
415 FTy->getParamType(1)->isPointerTy()) {
416 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
418 // Call the function.
420 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
421 (char **)GVTOP(ArgValues[1])));
426 if (FTy->getNumParams() == 1 &&
427 FTy->getParamType(0)->isIntegerTy(32)) {
429 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
430 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
437 // Handle cases where no arguments are passed first.
438 if (ArgValues.empty()) {
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();
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)());
455 llvm_unreachable("Integer types > 64 bits not supported");
459 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
461 case Type::FloatTyID:
462 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
464 case Type::DoubleTyID:
465 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
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)());
476 llvm_unreachable("Full-featured argument passing not supported yet!");
479 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
480 bool AbortOnFailure) {
481 if (!isSymbolSearchingDisabled()) {
482 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
487 /// If a LazyFunctionCreator is installed, use it to get/create the function.
488 if (LazyFunctionCreator)
489 if (void *RP = LazyFunctionCreator(Name))
492 if (AbortOnFailure) {
493 report_fatal_error("Program used external function '"+Name+
494 "' which could not be resolved!");
499 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
502 MutexGuard locked(lock);
503 EventListeners.push_back(L);
505 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
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();
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);
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);
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);
538 return ClientMM->getSymbolAddress(Name);