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,
49 std::unique_ptr<TargetMachine> TM) {
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), std::move(TM),
56 MemMgr ? MemMgr : new SectionMemoryManager());
59 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
60 RTDyldMemoryManager *MM)
61 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
62 MemMgr(this, MM), 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 for (auto &Obj : LoadedObjects)
87 NotifyFreeingObject(*Obj);
92 void MCJIT::addModule(std::unique_ptr<Module> M) {
93 MutexGuard locked(lock);
94 OwnedModules.addModule(std::move(M));
97 bool MCJIT::removeModule(Module *M) {
98 MutexGuard locked(lock);
99 return OwnedModules.removeModule(M);
102 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
103 std::unique_ptr<ObjectImage> LoadedObject = Dyld.loadObject(std::move(Obj));
104 if (!LoadedObject || Dyld.hasError())
105 report_fatal_error(Dyld.getErrorString());
107 NotifyObjectEmitted(*LoadedObject);
109 LoadedObjects.push_back(std::move(LoadedObject));
112 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
113 addObjectFile(std::move(Obj.getBinary()));
114 Buffers.push_back(std::move(Obj.getBuffer()));
117 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
118 Archives.push_back(std::move(A));
121 void MCJIT::setObjectCache(ObjectCache* NewCache) {
122 MutexGuard locked(lock);
126 std::unique_ptr<ObjectBufferStream> MCJIT::emitObject(Module *M) {
127 MutexGuard locked(lock);
129 // This must be a module which has already been added but not loaded to this
130 // MCJIT instance, since these conditions are tested by our caller,
131 // generateCodeForModule.
135 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
136 PM.add(new DataLayoutPass());
138 // The RuntimeDyld will take ownership of this shortly
139 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
141 // Turn the machine code intermediate representation into bytes in memory
142 // that may be executed.
143 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
144 !getVerifyModules())) {
145 report_fatal_error("Target does not support MC emission!");
148 // Initialize passes.
150 // Flush the output buffer to get the generated code into memory
151 CompiledObject->flush();
153 // If we have an object cache, tell it about the new object.
154 // Note that we're using the compiled image, not the loaded image (as below).
156 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
157 // to create a temporary object here and delete it after the call.
158 MemoryBufferRef MB = CompiledObject->getMemBuffer();
159 ObjCache->notifyObjectCompiled(M, MB);
162 return CompiledObject;
165 void MCJIT::generateCodeForModule(Module *M) {
166 // Get a thread lock to make sure we aren't trying to load multiple times
167 MutexGuard locked(lock);
169 // This must be a module which has already been added to this MCJIT instance.
170 assert(OwnedModules.ownsModule(M) &&
171 "MCJIT::generateCodeForModule: Unknown module.");
173 // Re-compilation is not supported
174 if (OwnedModules.hasModuleBeenLoaded(M))
177 std::unique_ptr<ObjectBuffer> ObjectToLoad;
178 // Try to load the pre-compiled object from cache if possible
180 if (std::unique_ptr<MemoryBuffer> PreCompiledObject =
181 ObjCache->getObject(M))
183 llvm::make_unique<ObjectBuffer>(std::move(PreCompiledObject));
186 // If the cache did not contain a suitable object, compile the object
188 ObjectToLoad = emitObject(M);
189 assert(ObjectToLoad && "Compilation did not produce an object.");
192 // Load the object into the dynamic linker.
193 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
194 std::unique_ptr<ObjectImage> LoadedObject =
195 Dyld.loadObject(std::move(ObjectToLoad));
197 report_fatal_error(Dyld.getErrorString());
199 // FIXME: Make this optional, maybe even move it to a JIT event listener
200 LoadedObject->registerWithDebugger();
202 NotifyObjectEmitted(*LoadedObject);
204 LoadedObjects.push_back(std::move(LoadedObject));
206 OwnedModules.markModuleAsLoaded(M);
209 void MCJIT::finalizeLoadedModules() {
210 MutexGuard locked(lock);
212 // Resolve any outstanding relocations.
213 Dyld.resolveRelocations();
215 OwnedModules.markAllLoadedModulesAsFinalized();
217 // Register EH frame data for any module we own which has been loaded
218 Dyld.registerEHFrames();
220 // Set page permissions.
221 MemMgr.finalizeMemory();
224 // FIXME: Rename this.
225 void MCJIT::finalizeObject() {
226 MutexGuard locked(lock);
228 // Generate code for module is going to move objects out of the 'added' list,
229 // so we need to copy that out before using it:
230 SmallVector<Module*, 16> ModsToAdd;
231 for (auto M : OwnedModules.added())
232 ModsToAdd.push_back(M);
234 for (auto M : ModsToAdd)
235 generateCodeForModule(M);
237 finalizeLoadedModules();
240 void MCJIT::finalizeModule(Module *M) {
241 MutexGuard locked(lock);
243 // This must be a module which has already been added to this MCJIT instance.
244 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
246 // If the module hasn't been compiled, just do that.
247 if (!OwnedModules.hasModuleBeenLoaded(M))
248 generateCodeForModule(M);
250 finalizeLoadedModules();
253 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
254 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
255 SmallString<128> FullName;
256 Mang.getNameWithPrefix(FullName, Name);
257 return Dyld.getSymbolLoadAddress(FullName);
260 Module *MCJIT::findModuleForSymbol(const std::string &Name,
261 bool CheckFunctionsOnly) {
262 MutexGuard locked(lock);
264 // If it hasn't already been generated, see if it's in one of our modules.
265 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
266 E = OwnedModules.end_added();
269 Function *F = M->getFunction(Name);
270 if (F && !F->isDeclaration())
272 if (!CheckFunctionsOnly) {
273 GlobalVariable *G = M->getGlobalVariable(Name);
274 if (G && !G->isDeclaration())
276 // FIXME: Do we need to worry about global aliases?
279 // We didn't find the symbol in any of our modules.
283 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
284 bool CheckFunctionsOnly)
286 MutexGuard locked(lock);
288 // First, check to see if we already have this symbol.
289 uint64_t Addr = getExistingSymbolAddress(Name);
293 for (object::OwningBinary<object::Archive> &OB : Archives) {
294 object::Archive *A = OB.getBinary().get();
295 // Look for our symbols in each Archive
296 object::Archive::child_iterator ChildIt = A->findSym(Name);
297 if (ChildIt != A->child_end()) {
298 // FIXME: Support nested archives?
299 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
300 ChildIt->getAsBinary();
301 if (ChildBinOrErr.getError())
303 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
304 if (ChildBin->isObject()) {
305 std::unique_ptr<object::ObjectFile> OF(
306 static_cast<object::ObjectFile *>(ChildBin.release()));
307 // This causes the object file to be loaded.
308 addObjectFile(std::move(OF));
309 // The address should be here now.
310 Addr = getExistingSymbolAddress(Name);
317 // If it hasn't already been generated, see if it's in one of our modules.
318 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
320 generateCodeForModule(M);
322 // Check the RuntimeDyld table again, it should be there now.
323 return getExistingSymbolAddress(Name);
326 // If a LazyFunctionCreator is installed, use it to get/create the function.
327 // FIXME: Should we instead have a LazySymbolCreator callback?
328 if (LazyFunctionCreator)
329 Addr = (uint64_t)LazyFunctionCreator(Name);
334 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
335 MutexGuard locked(lock);
336 uint64_t Result = getSymbolAddress(Name, false);
338 finalizeLoadedModules();
342 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
343 MutexGuard locked(lock);
344 uint64_t Result = getSymbolAddress(Name, true);
346 finalizeLoadedModules();
350 // Deprecated. Use getFunctionAddress instead.
351 void *MCJIT::getPointerToFunction(Function *F) {
352 MutexGuard locked(lock);
354 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
355 bool AbortOnFailure = !F->hasExternalWeakLinkage();
356 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
357 addGlobalMapping(F, Addr);
361 Module *M = F->getParent();
362 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
364 // Make sure the relevant module has been compiled and loaded.
365 if (HasBeenAddedButNotLoaded)
366 generateCodeForModule(M);
367 else if (!OwnedModules.hasModuleBeenLoaded(M))
368 // If this function doesn't belong to one of our modules, we're done.
371 // FIXME: Should the Dyld be retaining module information? Probably not.
373 // This is the accessor for the target address, so make sure to check the
374 // load address of the symbol, not the local address.
375 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
376 SmallString<128> Name;
377 TM->getNameWithPrefix(Name, F, Mang);
378 return (void*)Dyld.getSymbolLoadAddress(Name);
381 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
382 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
383 for (; I != E; ++I) {
384 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
388 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
389 // Execute global ctors/dtors for each module in the program.
390 runStaticConstructorsDestructorsInModulePtrSet(
391 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
392 runStaticConstructorsDestructorsInModulePtrSet(
393 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
394 runStaticConstructorsDestructorsInModulePtrSet(
395 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
398 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
399 ModulePtrSet::iterator I,
400 ModulePtrSet::iterator E) {
401 for (; I != E; ++I) {
402 if (Function *F = (*I)->getFunction(FnName))
408 Function *MCJIT::FindFunctionNamed(const char *FnName) {
409 Function *F = FindFunctionNamedInModulePtrSet(
410 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
412 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
413 OwnedModules.end_loaded());
415 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
416 OwnedModules.end_finalized());
420 GenericValue MCJIT::runFunction(Function *F,
421 const std::vector<GenericValue> &ArgValues) {
422 assert(F && "Function *F was null at entry to run()");
424 void *FPtr = getPointerToFunction(F);
425 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
426 FunctionType *FTy = F->getFunctionType();
427 Type *RetTy = FTy->getReturnType();
429 assert((FTy->getNumParams() == ArgValues.size() ||
430 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
431 "Wrong number of arguments passed into function!");
432 assert(FTy->getNumParams() == ArgValues.size() &&
433 "This doesn't support passing arguments through varargs (yet)!");
435 // Handle some common cases first. These cases correspond to common `main'
437 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
438 switch (ArgValues.size()) {
440 if (FTy->getParamType(0)->isIntegerTy(32) &&
441 FTy->getParamType(1)->isPointerTy() &&
442 FTy->getParamType(2)->isPointerTy()) {
443 int (*PF)(int, char **, const char **) =
444 (int(*)(int, char **, const char **))(intptr_t)FPtr;
446 // Call the function.
448 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
449 (char **)GVTOP(ArgValues[1]),
450 (const char **)GVTOP(ArgValues[2])));
455 if (FTy->getParamType(0)->isIntegerTy(32) &&
456 FTy->getParamType(1)->isPointerTy()) {
457 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
459 // Call the function.
461 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
462 (char **)GVTOP(ArgValues[1])));
467 if (FTy->getNumParams() == 1 &&
468 FTy->getParamType(0)->isIntegerTy(32)) {
470 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
471 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
478 // Handle cases where no arguments are passed first.
479 if (ArgValues.empty()) {
481 switch (RetTy->getTypeID()) {
482 default: llvm_unreachable("Unknown return type for function call!");
483 case Type::IntegerTyID: {
484 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
486 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
487 else if (BitWidth <= 8)
488 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
489 else if (BitWidth <= 16)
490 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
491 else if (BitWidth <= 32)
492 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
493 else if (BitWidth <= 64)
494 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
496 llvm_unreachable("Integer types > 64 bits not supported");
500 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
502 case Type::FloatTyID:
503 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
505 case Type::DoubleTyID:
506 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
508 case Type::X86_FP80TyID:
509 case Type::FP128TyID:
510 case Type::PPC_FP128TyID:
511 llvm_unreachable("long double not supported yet");
512 case Type::PointerTyID:
513 return PTOGV(((void*(*)())(intptr_t)FPtr)());
517 llvm_unreachable("Full-featured argument passing not supported yet!");
520 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
521 if (!isSymbolSearchingDisabled()) {
522 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
527 /// If a LazyFunctionCreator is installed, use it to get/create the function.
528 if (LazyFunctionCreator)
529 if (void *RP = LazyFunctionCreator(Name))
532 if (AbortOnFailure) {
533 report_fatal_error("Program used external function '"+Name+
534 "' which could not be resolved!");
539 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
542 MutexGuard locked(lock);
543 EventListeners.push_back(L);
545 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
548 MutexGuard locked(lock);
549 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
550 if (I != EventListeners.rend()) {
551 std::swap(*I, EventListeners.back());
552 EventListeners.pop_back();
555 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
556 MutexGuard locked(lock);
557 MemMgr.notifyObjectLoaded(this, &Obj);
558 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
559 EventListeners[I]->NotifyObjectEmitted(Obj);
562 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
563 MutexGuard locked(lock);
564 for (JITEventListener *L : EventListeners)
565 L->NotifyFreeingObject(Obj);
568 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
569 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
570 // If the symbols wasn't found and it begins with an underscore, try again
571 // without the underscore.
572 if (!Result && Name[0] == '_')
573 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
576 if (ParentEngine->isSymbolSearchingDisabled())
578 return ClientMM->getSymbolAddress(Name);