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/MCJIT.h"
14 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
15 #include "llvm/IR/DataLayout.h"
16 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/Mangler.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/Object/Archive.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/PassManager.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"
31 void ObjectCache::anchor() {}
35 static struct RegisterJIT {
36 RegisterJIT() { MCJIT::Register(); }
41 extern "C" void LLVMLinkInMCJIT() {
44 ExecutionEngine *MCJIT::createJIT(std::unique_ptr<Module> M,
45 std::string *ErrorStr,
46 std::unique_ptr<RTDyldMemoryManager> MemMgr,
47 std::unique_ptr<TargetMachine> TM) {
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(nullptr, nullptr);
53 std::unique_ptr<RTDyldMemoryManager> MM = std::move(MemMgr);
55 MM = std::unique_ptr<SectionMemoryManager>(new SectionMemoryManager());
57 return new MCJIT(std::move(M), std::move(TM), std::move(MM));
60 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> tm,
61 std::unique_ptr<RTDyldMemoryManager> MM)
62 : ExecutionEngine(std::move(M)), TM(std::move(tm)), Ctx(nullptr),
63 MemMgr(this, std::move(MM)), Dyld(&MemMgr), ObjCache(nullptr) {
64 // FIXME: We are managing our modules, so we do not want the base class
65 // ExecutionEngine to manage them as well. To avoid double destruction
66 // of the first (and only) module added in ExecutionEngine constructor
67 // we remove it from EE and will destruct it ourselves.
69 // It may make sense to move our module manager (based on SmallStPtr) back
70 // into EE if the JIT and Interpreter can live with it.
71 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
72 // runStaticConstructorsDestructors could be moved back to EE as well.
74 std::unique_ptr<Module> First = std::move(Modules[0]);
77 OwnedModules.addModule(std::move(First));
78 setDataLayout(TM->getDataLayout());
79 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
83 MutexGuard locked(lock);
85 Dyld.deregisterEHFrames();
87 for (auto &Obj : LoadedObjects)
89 NotifyFreeingObject(*Obj);
94 void MCJIT::addModule(std::unique_ptr<Module> M) {
95 MutexGuard locked(lock);
96 OwnedModules.addModule(std::move(M));
99 bool MCJIT::removeModule(Module *M) {
100 MutexGuard locked(lock);
101 return OwnedModules.removeModule(M);
104 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
105 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
107 report_fatal_error(Dyld.getErrorString());
109 NotifyObjectEmitted(*Obj, *L);
111 LoadedObjects.push_back(std::move(Obj));
114 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
115 std::unique_ptr<object::ObjectFile> ObjFile;
116 std::unique_ptr<MemoryBuffer> MemBuf;
117 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
118 addObjectFile(std::move(ObjFile));
119 Buffers.push_back(std::move(MemBuf));
122 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
123 Archives.push_back(std::move(A));
126 void MCJIT::setObjectCache(ObjectCache* NewCache) {
127 MutexGuard locked(lock);
131 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
132 MutexGuard locked(lock);
134 // This must be a module which has already been added but not loaded to this
135 // MCJIT instance, since these conditions are tested by our caller,
136 // generateCodeForModule.
140 M->setDataLayout(TM->getDataLayout());
141 PM.add(new DataLayoutPass());
143 // The RuntimeDyld will take ownership of this shortly
144 SmallVector<char, 4096> ObjBufferSV;
145 raw_svector_ostream ObjStream(ObjBufferSV);
147 // Turn the machine code intermediate representation into bytes in memory
148 // that may be executed.
149 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
150 report_fatal_error("Target does not support MC emission!");
152 // Initialize passes.
154 // Flush the output buffer to get the generated code into memory
157 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
158 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
160 // If we have an object cache, tell it about the new object.
161 // Note that we're using the compiled image, not the loaded image (as below).
163 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
164 // to create a temporary object here and delete it after the call.
165 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
166 ObjCache->notifyObjectCompiled(M, MB);
169 return CompiledObjBuffer;
172 void MCJIT::generateCodeForModule(Module *M) {
173 // Get a thread lock to make sure we aren't trying to load multiple times
174 MutexGuard locked(lock);
176 // This must be a module which has already been added to this MCJIT instance.
177 assert(OwnedModules.ownsModule(M) &&
178 "MCJIT::generateCodeForModule: Unknown module.");
180 // Re-compilation is not supported
181 if (OwnedModules.hasModuleBeenLoaded(M))
184 std::unique_ptr<MemoryBuffer> ObjectToLoad;
185 // Try to load the pre-compiled object from cache if possible
187 ObjectToLoad = ObjCache->getObject(M);
189 // If the cache did not contain a suitable object, compile the object
191 ObjectToLoad = emitObject(M);
192 assert(ObjectToLoad && "Compilation did not produce an object.");
195 // Load the object into the dynamic linker.
196 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
197 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
198 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
199 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
200 Dyld.loadObject(*LoadedObject.get());
203 report_fatal_error(Dyld.getErrorString());
205 NotifyObjectEmitted(*LoadedObject.get(), *L);
207 Buffers.push_back(std::move(ObjectToLoad));
208 LoadedObjects.push_back(std::move(*LoadedObject));
210 OwnedModules.markModuleAsLoaded(M);
213 void MCJIT::finalizeLoadedModules() {
214 MutexGuard locked(lock);
216 // Resolve any outstanding relocations.
217 Dyld.resolveRelocations();
219 OwnedModules.markAllLoadedModulesAsFinalized();
221 // Register EH frame data for any module we own which has been loaded
222 Dyld.registerEHFrames();
224 // Set page permissions.
225 MemMgr.finalizeMemory();
228 // FIXME: Rename this.
229 void MCJIT::finalizeObject() {
230 MutexGuard locked(lock);
232 // Generate code for module is going to move objects out of the 'added' list,
233 // so we need to copy that out before using it:
234 SmallVector<Module*, 16> ModsToAdd;
235 for (auto M : OwnedModules.added())
236 ModsToAdd.push_back(M);
238 for (auto M : ModsToAdd)
239 generateCodeForModule(M);
241 finalizeLoadedModules();
244 void MCJIT::finalizeModule(Module *M) {
245 MutexGuard locked(lock);
247 // This must be a module which has already been added to this MCJIT instance.
248 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
250 // If the module hasn't been compiled, just do that.
251 if (!OwnedModules.hasModuleBeenLoaded(M))
252 generateCodeForModule(M);
254 finalizeLoadedModules();
257 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
258 Mangler Mang(TM->getDataLayout());
259 SmallString<128> FullName;
260 Mang.getNameWithPrefix(FullName, Name);
261 return Dyld.getSymbolLoadAddress(FullName);
264 Module *MCJIT::findModuleForSymbol(const std::string &Name,
265 bool CheckFunctionsOnly) {
266 MutexGuard locked(lock);
268 // If it hasn't already been generated, see if it's in one of our modules.
269 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
270 E = OwnedModules.end_added();
273 Function *F = M->getFunction(Name);
274 if (F && !F->isDeclaration())
276 if (!CheckFunctionsOnly) {
277 GlobalVariable *G = M->getGlobalVariable(Name);
278 if (G && !G->isDeclaration())
280 // FIXME: Do we need to worry about global aliases?
283 // We didn't find the symbol in any of our modules.
287 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
288 bool CheckFunctionsOnly)
290 MutexGuard locked(lock);
292 // First, check to see if we already have this symbol.
293 uint64_t Addr = getExistingSymbolAddress(Name);
297 for (object::OwningBinary<object::Archive> &OB : Archives) {
298 object::Archive *A = OB.getBinary();
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())
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);
321 // If it hasn't already been generated, see if it's in one of our modules.
322 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
324 generateCodeForModule(M);
326 // Check the RuntimeDyld table again, it should be there now.
327 return getExistingSymbolAddress(Name);
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);
338 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
339 MutexGuard locked(lock);
340 uint64_t Result = getSymbolAddress(Name, false);
342 finalizeLoadedModules();
346 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
347 MutexGuard locked(lock);
348 uint64_t Result = getSymbolAddress(Name, true);
350 finalizeLoadedModules();
354 // Deprecated. Use getFunctionAddress instead.
355 void *MCJIT::getPointerToFunction(Function *F) {
356 MutexGuard locked(lock);
358 Mangler Mang(TM->getDataLayout());
359 SmallString<128> Name;
360 TM->getNameWithPrefix(Name, F, Mang);
362 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
363 bool AbortOnFailure = !F->hasExternalWeakLinkage();
364 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
365 updateGlobalMapping(F, Addr);
369 Module *M = F->getParent();
370 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
372 // Make sure the relevant module has been compiled and loaded.
373 if (HasBeenAddedButNotLoaded)
374 generateCodeForModule(M);
375 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
376 // If this function doesn't belong to one of our modules, we're done.
377 // FIXME: Asking for the pointer to a function that hasn't been registered,
378 // and isn't a declaration (which is handled above) should probably
383 // FIXME: Should the Dyld be retaining module information? Probably not.
385 // This is the accessor for the target address, so make sure to check the
386 // load address of the symbol, not the local address.
387 return (void*)Dyld.getSymbolLoadAddress(Name);
390 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
391 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
392 for (; I != E; ++I) {
393 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
397 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
398 // Execute global ctors/dtors for each module in the program.
399 runStaticConstructorsDestructorsInModulePtrSet(
400 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
401 runStaticConstructorsDestructorsInModulePtrSet(
402 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
403 runStaticConstructorsDestructorsInModulePtrSet(
404 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
407 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
408 ModulePtrSet::iterator I,
409 ModulePtrSet::iterator E) {
410 for (; I != E; ++I) {
411 Function *F = (*I)->getFunction(FnName);
412 if (F && !F->isDeclaration())
418 Function *MCJIT::FindFunctionNamed(const char *FnName) {
419 Function *F = FindFunctionNamedInModulePtrSet(
420 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
422 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
423 OwnedModules.end_loaded());
425 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
426 OwnedModules.end_finalized());
430 GenericValue MCJIT::runFunction(Function *F,
431 const std::vector<GenericValue> &ArgValues) {
432 assert(F && "Function *F was null at entry to run()");
434 void *FPtr = getPointerToFunction(F);
435 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
436 FunctionType *FTy = F->getFunctionType();
437 Type *RetTy = FTy->getReturnType();
439 assert((FTy->getNumParams() == ArgValues.size() ||
440 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
441 "Wrong number of arguments passed into function!");
442 assert(FTy->getNumParams() == ArgValues.size() &&
443 "This doesn't support passing arguments through varargs (yet)!");
445 // Handle some common cases first. These cases correspond to common `main'
447 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
448 switch (ArgValues.size()) {
450 if (FTy->getParamType(0)->isIntegerTy(32) &&
451 FTy->getParamType(1)->isPointerTy() &&
452 FTy->getParamType(2)->isPointerTy()) {
453 int (*PF)(int, char **, const char **) =
454 (int(*)(int, char **, const char **))(intptr_t)FPtr;
456 // Call the function.
458 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
459 (char **)GVTOP(ArgValues[1]),
460 (const char **)GVTOP(ArgValues[2])));
465 if (FTy->getParamType(0)->isIntegerTy(32) &&
466 FTy->getParamType(1)->isPointerTy()) {
467 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
469 // Call the function.
471 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
472 (char **)GVTOP(ArgValues[1])));
477 if (FTy->getNumParams() == 1 &&
478 FTy->getParamType(0)->isIntegerTy(32)) {
480 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
481 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
488 // Handle cases where no arguments are passed first.
489 if (ArgValues.empty()) {
491 switch (RetTy->getTypeID()) {
492 default: llvm_unreachable("Unknown return type for function call!");
493 case Type::IntegerTyID: {
494 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
496 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
497 else if (BitWidth <= 8)
498 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
499 else if (BitWidth <= 16)
500 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
501 else if (BitWidth <= 32)
502 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
503 else if (BitWidth <= 64)
504 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
506 llvm_unreachable("Integer types > 64 bits not supported");
510 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
512 case Type::FloatTyID:
513 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
515 case Type::DoubleTyID:
516 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
518 case Type::X86_FP80TyID:
519 case Type::FP128TyID:
520 case Type::PPC_FP128TyID:
521 llvm_unreachable("long double not supported yet");
522 case Type::PointerTyID:
523 return PTOGV(((void*(*)())(intptr_t)FPtr)());
527 llvm_unreachable("Full-featured argument passing not supported yet!");
530 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
531 if (!isSymbolSearchingDisabled()) {
532 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
537 /// If a LazyFunctionCreator is installed, use it to get/create the function.
538 if (LazyFunctionCreator)
539 if (void *RP = LazyFunctionCreator(Name))
542 if (AbortOnFailure) {
543 report_fatal_error("Program used external function '"+Name+
544 "' which could not be resolved!");
549 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
552 MutexGuard locked(lock);
553 EventListeners.push_back(L);
556 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
559 MutexGuard locked(lock);
560 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
561 if (I != EventListeners.rend()) {
562 std::swap(*I, EventListeners.back());
563 EventListeners.pop_back();
567 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
568 const RuntimeDyld::LoadedObjectInfo &L) {
569 MutexGuard locked(lock);
570 MemMgr.notifyObjectLoaded(this, Obj);
571 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
572 EventListeners[I]->NotifyObjectEmitted(Obj, L);
576 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
577 MutexGuard locked(lock);
578 for (JITEventListener *L : EventListeners)
579 L->NotifyFreeingObject(Obj);
582 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
583 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
584 // If the symbols wasn't found and it begins with an underscore, try again
585 // without the underscore.
586 if (!Result && Name[0] == '_')
587 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
590 if (ParentEngine->isSymbolSearchingDisabled())
592 return ClientMM->getSymbolAddress(Name);