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/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"
37 static struct RegisterJIT {
38 RegisterJIT() { MCJIT::Register(); }
43 extern "C" void LLVMLinkInMCJIT() {
46 ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
47 std::string *ErrorStr,
48 RTDyldMemoryManager *MemMgr,
50 // Try to register the program as a source of symbols to resolve against.
52 // FIXME: Don't do this here.
53 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
55 return new MCJIT(std::move(M), TM,
56 MemMgr ? MemMgr : new SectionMemoryManager());
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.
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.
73 std::unique_ptr<Module> First = std::move(Modules[0]);
76 OwnedModules.addModule(std::move(First));
77 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
81 MutexGuard locked(lock);
83 Dyld.deregisterEHFrames();
85 LoadedObjectList::iterator it, end;
86 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
87 ObjectImage *Obj = *it;
89 NotifyFreeingObject(*Obj);
93 LoadedObjects.clear();
100 void MCJIT::addModule(std::unique_ptr<Module> M) {
101 MutexGuard locked(lock);
102 OwnedModules.addModule(std::move(M));
105 bool MCJIT::removeModule(Module *M) {
106 MutexGuard locked(lock);
107 return OwnedModules.removeModule(M);
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());
117 LoadedObjects.push_back(LoadedObject);
119 NotifyObjectEmitted(*LoadedObject);
122 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
123 Archives.push_back(std::move(A));
127 void MCJIT::setObjectCache(ObjectCache* NewCache) {
128 MutexGuard locked(lock);
132 ObjectBufferStream* MCJIT::emitObject(Module *M) {
133 MutexGuard locked(lock);
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.
141 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
142 PM.add(new DataLayoutPass(M));
144 // The RuntimeDyld will take ownership of this shortly
145 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
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!");
154 // Initialize passes.
156 // Flush the output buffer to get the generated code into memory
157 CompiledObject->flush();
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).
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 = CompiledObject->getMemBuffer();
165 ObjCache->notifyObjectCompiled(M, MB);
168 return CompiledObject.release();
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);
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.");
179 // Re-compilation is not supported
180 if (OwnedModules.hasModuleBeenLoaded(M))
183 std::unique_ptr<ObjectBuffer> ObjectToLoad;
184 // Try to load the pre-compiled object from cache if possible
186 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
187 if (PreCompiledObject.get())
188 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
191 // If the cache did not contain a suitable object, compile the object
193 ObjectToLoad.reset(emitObject(M));
194 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
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);
202 report_fatal_error(Dyld.getErrorString());
204 // FIXME: Make this optional, maybe even move it to a JIT event listener
205 LoadedObject->registerWithDebugger();
207 NotifyObjectEmitted(*LoadedObject);
209 OwnedModules.markModuleAsLoaded(M);
212 void MCJIT::finalizeLoadedModules() {
213 MutexGuard locked(lock);
215 // Resolve any outstanding relocations.
216 Dyld.resolveRelocations();
218 OwnedModules.markAllLoadedModulesAsFinalized();
220 // Register EH frame data for any module we own which has been loaded
221 Dyld.registerEHFrames();
223 // Set page permissions.
224 MemMgr.finalizeMemory();
227 // FIXME: Rename this.
228 void MCJIT::finalizeObject() {
229 MutexGuard locked(lock);
231 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
232 E = OwnedModules.end_added();
235 generateCodeForModule(M);
238 finalizeLoadedModules();
241 void MCJIT::finalizeModule(Module *M) {
242 MutexGuard locked(lock);
244 // This must be a module which has already been added to this MCJIT instance.
245 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
247 // If the module hasn't been compiled, just do that.
248 if (!OwnedModules.hasModuleBeenLoaded(M))
249 generateCodeForModule(M);
251 finalizeLoadedModules();
254 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
255 report_fatal_error("not yet implemented");
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);
265 Module *MCJIT::findModuleForSymbol(const std::string &Name,
266 bool CheckFunctionsOnly) {
267 MutexGuard locked(lock);
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();
274 Function *F = M->getFunction(Name);
275 if (F && !F->isDeclaration())
277 if (!CheckFunctionsOnly) {
278 GlobalVariable *G = M->getGlobalVariable(Name);
279 if (G && !G->isDeclaration())
281 // FIXME: Do we need to worry about global aliases?
284 // We didn't find the symbol in any of our modules.
288 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
289 bool CheckFunctionsOnly)
291 MutexGuard locked(lock);
293 // First, check to see if we already have this symbol.
294 uint64_t Addr = getExistingSymbolAddress(Name);
298 for (object::OwningBinary<object::Archive> &OB : Archives) {
299 object::Archive *A = OB.getBinary().get();
300 // Look for our symbols in each Archive
301 object::Archive::child_iterator ChildIt = A->findSym(Name);
302 if (ChildIt != A->child_end()) {
303 // FIXME: Support nested archives?
304 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
305 ChildIt->getAsBinary();
306 if (ChildBinOrErr.getError())
308 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
309 if (ChildBin->isObject()) {
310 std::unique_ptr<object::ObjectFile> OF(
311 static_cast<object::ObjectFile *>(ChildBin.release()));
312 // This causes the object file to be loaded.
313 addObjectFile(std::move(OF));
314 // The address should be here now.
315 Addr = getExistingSymbolAddress(Name);
322 // If it hasn't already been generated, see if it's in one of our modules.
323 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
325 generateCodeForModule(M);
327 // Check the RuntimeDyld table again, it should be there now.
328 return getExistingSymbolAddress(Name);
331 // If a LazyFunctionCreator is installed, use it to get/create the function.
332 // FIXME: Should we instead have a LazySymbolCreator callback?
333 if (LazyFunctionCreator)
334 Addr = (uint64_t)LazyFunctionCreator(Name);
339 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
340 MutexGuard locked(lock);
341 uint64_t Result = getSymbolAddress(Name, false);
343 finalizeLoadedModules();
347 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
348 MutexGuard locked(lock);
349 uint64_t Result = getSymbolAddress(Name, true);
351 finalizeLoadedModules();
355 // Deprecated. Use getFunctionAddress instead.
356 void *MCJIT::getPointerToFunction(Function *F) {
357 MutexGuard locked(lock);
359 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
360 bool AbortOnFailure = !F->hasExternalWeakLinkage();
361 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
362 addGlobalMapping(F, Addr);
366 Module *M = F->getParent();
367 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
369 // Make sure the relevant module has been compiled and loaded.
370 if (HasBeenAddedButNotLoaded)
371 generateCodeForModule(M);
372 else if (!OwnedModules.hasModuleBeenLoaded(M))
373 // If this function doesn't belong to one of our modules, we're done.
376 // FIXME: Should the Dyld be retaining module information? Probably not.
378 // This is the accessor for the target address, so make sure to check the
379 // load address of the symbol, not the local address.
380 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
381 SmallString<128> Name;
382 TM->getNameWithPrefix(Name, F, Mang);
383 return (void*)Dyld.getSymbolLoadAddress(Name);
386 void *MCJIT::recompileAndRelinkFunction(Function *F) {
387 report_fatal_error("not yet implemented");
390 void MCJIT::freeMachineCodeForFunction(Function *F) {
391 report_fatal_error("not yet implemented");
394 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
395 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
396 for (; I != E; ++I) {
397 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
401 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
402 // Execute global ctors/dtors for each module in the program.
403 runStaticConstructorsDestructorsInModulePtrSet(
404 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
405 runStaticConstructorsDestructorsInModulePtrSet(
406 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
407 runStaticConstructorsDestructorsInModulePtrSet(
408 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
411 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
412 ModulePtrSet::iterator I,
413 ModulePtrSet::iterator E) {
414 for (; I != E; ++I) {
415 if (Function *F = (*I)->getFunction(FnName))
421 Function *MCJIT::FindFunctionNamed(const char *FnName) {
422 Function *F = FindFunctionNamedInModulePtrSet(
423 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
425 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
426 OwnedModules.end_loaded());
428 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
429 OwnedModules.end_finalized());
433 GenericValue MCJIT::runFunction(Function *F,
434 const std::vector<GenericValue> &ArgValues) {
435 assert(F && "Function *F was null at entry to run()");
437 void *FPtr = getPointerToFunction(F);
438 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
439 FunctionType *FTy = F->getFunctionType();
440 Type *RetTy = FTy->getReturnType();
442 assert((FTy->getNumParams() == ArgValues.size() ||
443 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
444 "Wrong number of arguments passed into function!");
445 assert(FTy->getNumParams() == ArgValues.size() &&
446 "This doesn't support passing arguments through varargs (yet)!");
448 // Handle some common cases first. These cases correspond to common `main'
450 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
451 switch (ArgValues.size()) {
453 if (FTy->getParamType(0)->isIntegerTy(32) &&
454 FTy->getParamType(1)->isPointerTy() &&
455 FTy->getParamType(2)->isPointerTy()) {
456 int (*PF)(int, char **, const char **) =
457 (int(*)(int, char **, const char **))(intptr_t)FPtr;
459 // Call the function.
461 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
462 (char **)GVTOP(ArgValues[1]),
463 (const char **)GVTOP(ArgValues[2])));
468 if (FTy->getParamType(0)->isIntegerTy(32) &&
469 FTy->getParamType(1)->isPointerTy()) {
470 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
472 // Call the function.
474 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
475 (char **)GVTOP(ArgValues[1])));
480 if (FTy->getNumParams() == 1 &&
481 FTy->getParamType(0)->isIntegerTy(32)) {
483 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
484 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
491 // Handle cases where no arguments are passed first.
492 if (ArgValues.empty()) {
494 switch (RetTy->getTypeID()) {
495 default: llvm_unreachable("Unknown return type for function call!");
496 case Type::IntegerTyID: {
497 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
499 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
500 else if (BitWidth <= 8)
501 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
502 else if (BitWidth <= 16)
503 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
504 else if (BitWidth <= 32)
505 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
506 else if (BitWidth <= 64)
507 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
509 llvm_unreachable("Integer types > 64 bits not supported");
513 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
515 case Type::FloatTyID:
516 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
518 case Type::DoubleTyID:
519 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
521 case Type::X86_FP80TyID:
522 case Type::FP128TyID:
523 case Type::PPC_FP128TyID:
524 llvm_unreachable("long double not supported yet");
525 case Type::PointerTyID:
526 return PTOGV(((void*(*)())(intptr_t)FPtr)());
530 llvm_unreachable("Full-featured argument passing not supported yet!");
533 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
534 bool AbortOnFailure) {
535 if (!isSymbolSearchingDisabled()) {
536 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
541 /// If a LazyFunctionCreator is installed, use it to get/create the function.
542 if (LazyFunctionCreator)
543 if (void *RP = LazyFunctionCreator(Name))
546 if (AbortOnFailure) {
547 report_fatal_error("Program used external function '"+Name+
548 "' which could not be resolved!");
553 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
556 MutexGuard locked(lock);
557 EventListeners.push_back(L);
559 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
562 MutexGuard locked(lock);
563 SmallVector<JITEventListener*, 2>::reverse_iterator I=
564 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
565 if (I != EventListeners.rend()) {
566 std::swap(*I, EventListeners.back());
567 EventListeners.pop_back();
570 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
571 MutexGuard locked(lock);
572 MemMgr.notifyObjectLoaded(this, &Obj);
573 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
574 EventListeners[I]->NotifyObjectEmitted(Obj);
577 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
578 MutexGuard locked(lock);
579 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
580 EventListeners[I]->NotifyFreeingObject(Obj);
584 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
585 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
586 // If the symbols wasn't found and it begins with an underscore, try again
587 // without the underscore.
588 if (!Result && Name[0] == '_')
589 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
592 if (ParentEngine->isSymbolSearchingDisabled())
594 return ClientMM->getSymbolAddress(Name);