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/ADT/STLExtras.h"
12 #include "llvm/ExecutionEngine/GenericValue.h"
13 #include "llvm/ExecutionEngine/JITEventListener.h"
14 #include "llvm/ExecutionEngine/MCJIT.h"
15 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Object/Archive.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/DynamicLibrary.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/MutexGuard.h"
32 void ObjectCache::anchor() {}
36 static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
42 extern "C" void LLVMLinkInMCJIT() {
46 MCJIT::createJIT(std::unique_ptr<Module> M,
47 std::string *ErrorStr,
48 std::shared_ptr<MCJITMemoryManager> MemMgr,
49 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
50 std::unique_ptr<TargetMachine> TM) {
51 // Try to register the program as a source of symbols to resolve against.
53 // FIXME: Don't do this here.
54 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
56 if (!MemMgr || !Resolver) {
57 auto RTDyldMM = std::make_shared<SectionMemoryManager>();
64 return new MCJIT(std::move(M), std::move(TM), std::move(MemMgr),
68 MCJIT::MCJIT(std::unique_ptr<Module> M, std::unique_ptr<TargetMachine> TM,
69 std::shared_ptr<MCJITMemoryManager> MemMgr,
70 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver)
71 : ExecutionEngine(TM->createDataLayout(), std::move(M)), TM(std::move(TM)),
72 Ctx(nullptr), MemMgr(std::move(MemMgr)),
73 Resolver(*this, std::move(Resolver)), Dyld(*this->MemMgr, this->Resolver),
75 // FIXME: We are managing our modules, so we do not want the base class
76 // ExecutionEngine to manage them as well. To avoid double destruction
77 // of the first (and only) module added in ExecutionEngine constructor
78 // we remove it from EE and will destruct it ourselves.
80 // It may make sense to move our module manager (based on SmallStPtr) back
81 // into EE if the JIT and Interpreter can live with it.
82 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
83 // runStaticConstructorsDestructors could be moved back to EE as well.
85 std::unique_ptr<Module> First = std::move(Modules[0]);
88 OwnedModules.addModule(std::move(First));
89 RegisterJITEventListener(JITEventListener::createGDBRegistrationListener());
93 MutexGuard locked(lock);
95 Dyld.deregisterEHFrames();
97 for (auto &Obj : LoadedObjects)
99 NotifyFreeingObject(*Obj);
104 void MCJIT::addModule(std::unique_ptr<Module> M) {
105 MutexGuard locked(lock);
106 OwnedModules.addModule(std::move(M));
109 bool MCJIT::removeModule(Module *M) {
110 MutexGuard locked(lock);
111 return OwnedModules.removeModule(M);
114 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
115 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L = Dyld.loadObject(*Obj);
117 report_fatal_error(Dyld.getErrorString());
119 NotifyObjectEmitted(*Obj, *L);
121 LoadedObjects.push_back(std::move(Obj));
124 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
125 std::unique_ptr<object::ObjectFile> ObjFile;
126 std::unique_ptr<MemoryBuffer> MemBuf;
127 std::tie(ObjFile, MemBuf) = Obj.takeBinary();
128 addObjectFile(std::move(ObjFile));
129 Buffers.push_back(std::move(MemBuf));
132 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
133 Archives.push_back(std::move(A));
136 void MCJIT::setObjectCache(ObjectCache* NewCache) {
137 MutexGuard locked(lock);
141 std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
142 MutexGuard locked(lock);
144 // This must be a module which has already been added but not loaded to this
145 // MCJIT instance, since these conditions are tested by our caller,
146 // generateCodeForModule.
148 legacy::PassManager PM;
150 // The RuntimeDyld will take ownership of this shortly
151 SmallVector<char, 4096> ObjBufferSV;
152 raw_svector_ostream ObjStream(ObjBufferSV);
154 // Turn the machine code intermediate representation into bytes in memory
155 // that may be executed.
156 if (TM->addPassesToEmitMC(PM, Ctx, ObjStream, !getVerifyModules()))
157 report_fatal_error("Target does not support MC emission!");
159 // Initialize passes.
161 // Flush the output buffer to get the generated code into memory
163 std::unique_ptr<MemoryBuffer> CompiledObjBuffer(
164 new ObjectMemoryBuffer(std::move(ObjBufferSV)));
166 // If we have an object cache, tell it about the new object.
167 // Note that we're using the compiled image, not the loaded image (as below).
169 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
170 // to create a temporary object here and delete it after the call.
171 MemoryBufferRef MB = CompiledObjBuffer->getMemBufferRef();
172 ObjCache->notifyObjectCompiled(M, MB);
175 return CompiledObjBuffer;
178 void MCJIT::generateCodeForModule(Module *M) {
179 // Get a thread lock to make sure we aren't trying to load multiple times
180 MutexGuard locked(lock);
182 // This must be a module which has already been added to this MCJIT instance.
183 assert(OwnedModules.ownsModule(M) &&
184 "MCJIT::generateCodeForModule: Unknown module.");
186 // Re-compilation is not supported
187 if (OwnedModules.hasModuleBeenLoaded(M))
190 std::unique_ptr<MemoryBuffer> ObjectToLoad;
191 // Try to load the pre-compiled object from cache if possible
193 ObjectToLoad = ObjCache->getObject(M);
195 if (M->getDataLayout().isDefault()) {
196 M->setDataLayout(getDataLayout());
198 assert(M->getDataLayout() == getDataLayout() && "DataLayout Mismatch");
201 // If the cache did not contain a suitable object, compile the object
203 ObjectToLoad = emitObject(M);
204 assert(ObjectToLoad && "Compilation did not produce an object.");
207 // Load the object into the dynamic linker.
208 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
209 ErrorOr<std::unique_ptr<object::ObjectFile>> LoadedObject =
210 object::ObjectFile::createObjectFile(ObjectToLoad->getMemBufferRef());
211 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> L =
212 Dyld.loadObject(*LoadedObject.get());
215 report_fatal_error(Dyld.getErrorString());
217 NotifyObjectEmitted(*LoadedObject.get(), *L);
219 Buffers.push_back(std::move(ObjectToLoad));
220 LoadedObjects.push_back(std::move(*LoadedObject));
222 OwnedModules.markModuleAsLoaded(M);
225 void MCJIT::finalizeLoadedModules() {
226 MutexGuard locked(lock);
228 // Resolve any outstanding relocations.
229 Dyld.resolveRelocations();
231 OwnedModules.markAllLoadedModulesAsFinalized();
233 // Register EH frame data for any module we own which has been loaded
234 Dyld.registerEHFrames();
236 // Set page permissions.
237 MemMgr->finalizeMemory();
240 // FIXME: Rename this.
241 void MCJIT::finalizeObject() {
242 MutexGuard locked(lock);
244 // Generate code for module is going to move objects out of the 'added' list,
245 // so we need to copy that out before using it:
246 SmallVector<Module*, 16> ModsToAdd;
247 for (auto M : OwnedModules.added())
248 ModsToAdd.push_back(M);
250 for (auto M : ModsToAdd)
251 generateCodeForModule(M);
253 finalizeLoadedModules();
256 void MCJIT::finalizeModule(Module *M) {
257 MutexGuard locked(lock);
259 // This must be a module which has already been added to this MCJIT instance.
260 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
262 // If the module hasn't been compiled, just do that.
263 if (!OwnedModules.hasModuleBeenLoaded(M))
264 generateCodeForModule(M);
266 finalizeLoadedModules();
269 RuntimeDyld::SymbolInfo MCJIT::findExistingSymbol(const std::string &Name) {
270 SmallString<128> FullName;
271 Mangler::getNameWithPrefix(FullName, Name, getDataLayout());
273 if (void *Addr = getPointerToGlobalIfAvailable(FullName))
274 return RuntimeDyld::SymbolInfo(static_cast<uint64_t>(
275 reinterpret_cast<uintptr_t>(Addr)),
276 JITSymbolFlags::Exported);
278 return Dyld.getSymbol(FullName);
281 Module *MCJIT::findModuleForSymbol(const std::string &Name,
282 bool CheckFunctionsOnly) {
283 MutexGuard locked(lock);
285 // If it hasn't already been generated, see if it's in one of our modules.
286 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
287 E = OwnedModules.end_added();
290 Function *F = M->getFunction(Name);
291 if (F && !F->isDeclaration())
293 if (!CheckFunctionsOnly) {
294 GlobalVariable *G = M->getGlobalVariable(Name);
295 if (G && !G->isDeclaration())
297 // FIXME: Do we need to worry about global aliases?
300 // We didn't find the symbol in any of our modules.
304 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
305 bool CheckFunctionsOnly) {
306 return findSymbol(Name, CheckFunctionsOnly).getAddress();
309 RuntimeDyld::SymbolInfo MCJIT::findSymbol(const std::string &Name,
310 bool CheckFunctionsOnly) {
311 MutexGuard locked(lock);
313 // First, check to see if we already have this symbol.
314 if (auto Sym = findExistingSymbol(Name))
317 for (object::OwningBinary<object::Archive> &OB : Archives) {
318 object::Archive *A = OB.getBinary();
319 // Look for our symbols in each Archive
320 object::Archive::child_iterator ChildIt = A->findSym(Name);
321 if (ChildIt != A->child_end()) {
322 // FIXME: Support nested archives?
323 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
324 ChildIt->getAsBinary();
325 if (ChildBinOrErr.getError())
327 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
328 if (ChildBin->isObject()) {
329 std::unique_ptr<object::ObjectFile> OF(
330 static_cast<object::ObjectFile *>(ChildBin.release()));
331 // This causes the object file to be loaded.
332 addObjectFile(std::move(OF));
333 // The address should be here now.
334 if (auto Sym = findExistingSymbol(Name))
340 // If it hasn't already been generated, see if it's in one of our modules.
341 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
343 generateCodeForModule(M);
345 // Check the RuntimeDyld table again, it should be there now.
346 return findExistingSymbol(Name);
349 // If a LazyFunctionCreator is installed, use it to get/create the function.
350 // FIXME: Should we instead have a LazySymbolCreator callback?
351 if (LazyFunctionCreator) {
352 auto Addr = static_cast<uint64_t>(
353 reinterpret_cast<uintptr_t>(LazyFunctionCreator(Name)));
354 return RuntimeDyld::SymbolInfo(Addr, JITSymbolFlags::Exported);
360 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
361 MutexGuard locked(lock);
362 uint64_t Result = getSymbolAddress(Name, false);
364 finalizeLoadedModules();
368 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
369 MutexGuard locked(lock);
370 uint64_t Result = getSymbolAddress(Name, true);
372 finalizeLoadedModules();
376 // Deprecated. Use getFunctionAddress instead.
377 void *MCJIT::getPointerToFunction(Function *F) {
378 MutexGuard locked(lock);
381 SmallString<128> Name;
382 TM->getNameWithPrefix(Name, F, Mang);
384 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
385 bool AbortOnFailure = !F->hasExternalWeakLinkage();
386 void *Addr = getPointerToNamedFunction(Name, AbortOnFailure);
387 updateGlobalMapping(F, Addr);
391 Module *M = F->getParent();
392 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
394 // Make sure the relevant module has been compiled and loaded.
395 if (HasBeenAddedButNotLoaded)
396 generateCodeForModule(M);
397 else if (!OwnedModules.hasModuleBeenLoaded(M)) {
398 // If this function doesn't belong to one of our modules, we're done.
399 // FIXME: Asking for the pointer to a function that hasn't been registered,
400 // and isn't a declaration (which is handled above) should probably
405 // FIXME: Should the Dyld be retaining module information? Probably not.
407 // This is the accessor for the target address, so make sure to check the
408 // load address of the symbol, not the local address.
409 return (void*)Dyld.getSymbol(Name).getAddress();
412 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
413 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
414 for (; I != E; ++I) {
415 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
419 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
420 // Execute global ctors/dtors for each module in the program.
421 runStaticConstructorsDestructorsInModulePtrSet(
422 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
423 runStaticConstructorsDestructorsInModulePtrSet(
424 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
425 runStaticConstructorsDestructorsInModulePtrSet(
426 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
429 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
430 ModulePtrSet::iterator I,
431 ModulePtrSet::iterator E) {
432 for (; I != E; ++I) {
433 Function *F = (*I)->getFunction(FnName);
434 if (F && !F->isDeclaration())
440 GlobalVariable *MCJIT::FindGlobalVariableNamedInModulePtrSet(const char *Name,
442 ModulePtrSet::iterator I,
443 ModulePtrSet::iterator E) {
444 for (; I != E; ++I) {
445 GlobalVariable *GV = (*I)->getGlobalVariable(Name, AllowInternal);
446 if (GV && !GV->isDeclaration())
453 Function *MCJIT::FindFunctionNamed(const char *FnName) {
454 Function *F = FindFunctionNamedInModulePtrSet(
455 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
457 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
458 OwnedModules.end_loaded());
460 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
461 OwnedModules.end_finalized());
465 GlobalVariable *MCJIT::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
466 GlobalVariable *GV = FindGlobalVariableNamedInModulePtrSet(
467 Name, AllowInternal, OwnedModules.begin_added(), OwnedModules.end_added());
469 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_loaded(),
470 OwnedModules.end_loaded());
472 GV = FindGlobalVariableNamedInModulePtrSet(Name, AllowInternal, OwnedModules.begin_finalized(),
473 OwnedModules.end_finalized());
477 GenericValue MCJIT::runFunction(Function *F, ArrayRef<GenericValue> ArgValues) {
478 assert(F && "Function *F was null at entry to run()");
480 void *FPtr = getPointerToFunction(F);
481 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
482 FunctionType *FTy = F->getFunctionType();
483 Type *RetTy = FTy->getReturnType();
485 assert((FTy->getNumParams() == ArgValues.size() ||
486 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
487 "Wrong number of arguments passed into function!");
488 assert(FTy->getNumParams() == ArgValues.size() &&
489 "This doesn't support passing arguments through varargs (yet)!");
491 // Handle some common cases first. These cases correspond to common `main'
493 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
494 switch (ArgValues.size()) {
496 if (FTy->getParamType(0)->isIntegerTy(32) &&
497 FTy->getParamType(1)->isPointerTy() &&
498 FTy->getParamType(2)->isPointerTy()) {
499 int (*PF)(int, char **, const char **) =
500 (int(*)(int, char **, const char **))(intptr_t)FPtr;
502 // Call the function.
504 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
505 (char **)GVTOP(ArgValues[1]),
506 (const char **)GVTOP(ArgValues[2])));
511 if (FTy->getParamType(0)->isIntegerTy(32) &&
512 FTy->getParamType(1)->isPointerTy()) {
513 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
515 // Call the function.
517 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
518 (char **)GVTOP(ArgValues[1])));
523 if (FTy->getNumParams() == 1 &&
524 FTy->getParamType(0)->isIntegerTy(32)) {
526 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
527 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
534 // Handle cases where no arguments are passed first.
535 if (ArgValues.empty()) {
537 switch (RetTy->getTypeID()) {
538 default: llvm_unreachable("Unknown return type for function call!");
539 case Type::IntegerTyID: {
540 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
542 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
543 else if (BitWidth <= 8)
544 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
545 else if (BitWidth <= 16)
546 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
547 else if (BitWidth <= 32)
548 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
549 else if (BitWidth <= 64)
550 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
552 llvm_unreachable("Integer types > 64 bits not supported");
556 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
558 case Type::FloatTyID:
559 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
561 case Type::DoubleTyID:
562 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
564 case Type::X86_FP80TyID:
565 case Type::FP128TyID:
566 case Type::PPC_FP128TyID:
567 llvm_unreachable("long double not supported yet");
568 case Type::PointerTyID:
569 return PTOGV(((void*(*)())(intptr_t)FPtr)());
573 llvm_unreachable("Full-featured argument passing not supported yet!");
576 void *MCJIT::getPointerToNamedFunction(StringRef Name, bool AbortOnFailure) {
577 if (!isSymbolSearchingDisabled()) {
579 reinterpret_cast<void*>(
580 static_cast<uintptr_t>(Resolver.findSymbol(Name).getAddress()));
585 /// If a LazyFunctionCreator is installed, use it to get/create the function.
586 if (LazyFunctionCreator)
587 if (void *RP = LazyFunctionCreator(Name))
590 if (AbortOnFailure) {
591 report_fatal_error("Program used external function '"+Name+
592 "' which could not be resolved!");
597 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
600 MutexGuard locked(lock);
601 EventListeners.push_back(L);
604 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
607 MutexGuard locked(lock);
608 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
609 if (I != EventListeners.rend()) {
610 std::swap(*I, EventListeners.back());
611 EventListeners.pop_back();
615 void MCJIT::NotifyObjectEmitted(const object::ObjectFile& Obj,
616 const RuntimeDyld::LoadedObjectInfo &L) {
617 MutexGuard locked(lock);
618 MemMgr->notifyObjectLoaded(this, Obj);
619 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
620 EventListeners[I]->NotifyObjectEmitted(Obj, L);
624 void MCJIT::NotifyFreeingObject(const object::ObjectFile& Obj) {
625 MutexGuard locked(lock);
626 for (JITEventListener *L : EventListeners)
627 L->NotifyFreeingObject(Obj);
630 RuntimeDyld::SymbolInfo
631 LinkingSymbolResolver::findSymbol(const std::string &Name) {
632 auto Result = ParentEngine.findSymbol(Name, false);
633 // If the symbols wasn't found and it begins with an underscore, try again
634 // without the underscore.
635 if (!Result && Name[0] == '_')
636 Result = ParentEngine.findSymbol(Name.substr(1), false);
639 if (ParentEngine.isSymbolSearchingDisabled())
641 return ClientResolver->findSymbol(Name);