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);
110 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
111 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
112 if (!LoadedObject || Dyld.hasError())
113 report_fatal_error(Dyld.getErrorString());
115 LoadedObjects.push_back(LoadedObject);
117 NotifyObjectEmitted(*LoadedObject);
120 void MCJIT::addObjectFile(object::OwningBinary<object::ObjectFile> Obj) {
121 addObjectFile(std::move(Obj.getBinary()));
122 Buffers.push_back(std::move(Obj.getBuffer()));
125 void MCJIT::addArchive(object::OwningBinary<object::Archive> A) {
126 Archives.push_back(std::move(A));
129 void MCJIT::setObjectCache(ObjectCache* NewCache) {
130 MutexGuard locked(lock);
134 ObjectBufferStream* MCJIT::emitObject(Module *M) {
135 MutexGuard locked(lock);
137 // This must be a module which has already been added but not loaded to this
138 // MCJIT instance, since these conditions are tested by our caller,
139 // generateCodeForModule.
143 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
144 PM.add(new DataLayoutPass(M));
146 // The RuntimeDyld will take ownership of this shortly
147 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
149 // Turn the machine code intermediate representation into bytes in memory
150 // that may be executed.
151 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
152 !getVerifyModules())) {
153 report_fatal_error("Target does not support MC emission!");
156 // Initialize passes.
158 // Flush the output buffer to get the generated code into memory
159 CompiledObject->flush();
161 // If we have an object cache, tell it about the new object.
162 // Note that we're using the compiled image, not the loaded image (as below).
164 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
165 // to create a temporary object here and delete it after the call.
166 MemoryBufferRef MB = CompiledObject->getMemBuffer();
167 ObjCache->notifyObjectCompiled(M, MB);
170 return CompiledObject.release();
173 void MCJIT::generateCodeForModule(Module *M) {
174 // Get a thread lock to make sure we aren't trying to load multiple times
175 MutexGuard locked(lock);
177 // This must be a module which has already been added to this MCJIT instance.
178 assert(OwnedModules.ownsModule(M) &&
179 "MCJIT::generateCodeForModule: Unknown module.");
181 // Re-compilation is not supported
182 if (OwnedModules.hasModuleBeenLoaded(M))
185 std::unique_ptr<ObjectBuffer> ObjectToLoad;
186 // Try to load the pre-compiled object from cache if possible
188 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
189 if (PreCompiledObject.get())
190 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
193 // If the cache did not contain a suitable object, compile the object
195 ObjectToLoad.reset(emitObject(M));
196 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
199 // Load the object into the dynamic linker.
200 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
201 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
202 LoadedObjects.push_back(LoadedObject);
204 report_fatal_error(Dyld.getErrorString());
206 // FIXME: Make this optional, maybe even move it to a JIT event listener
207 LoadedObject->registerWithDebugger();
209 NotifyObjectEmitted(*LoadedObject);
211 OwnedModules.markModuleAsLoaded(M);
214 void MCJIT::finalizeLoadedModules() {
215 MutexGuard locked(lock);
217 // Resolve any outstanding relocations.
218 Dyld.resolveRelocations();
220 OwnedModules.markAllLoadedModulesAsFinalized();
222 // Register EH frame data for any module we own which has been loaded
223 Dyld.registerEHFrames();
225 // Set page permissions.
226 MemMgr.finalizeMemory();
229 // FIXME: Rename this.
230 void MCJIT::finalizeObject() {
231 MutexGuard locked(lock);
233 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
234 E = OwnedModules.end_added();
237 generateCodeForModule(M);
240 finalizeLoadedModules();
243 void MCJIT::finalizeModule(Module *M) {
244 MutexGuard locked(lock);
246 // This must be a module which has already been added to this MCJIT instance.
247 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
249 // If the module hasn't been compiled, just do that.
250 if (!OwnedModules.hasModuleBeenLoaded(M))
251 generateCodeForModule(M);
253 finalizeLoadedModules();
256 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
257 report_fatal_error("not yet implemented");
260 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
261 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
262 SmallString<128> FullName;
263 Mang.getNameWithPrefix(FullName, Name);
264 return Dyld.getSymbolLoadAddress(FullName);
267 Module *MCJIT::findModuleForSymbol(const std::string &Name,
268 bool CheckFunctionsOnly) {
269 MutexGuard locked(lock);
271 // If it hasn't already been generated, see if it's in one of our modules.
272 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
273 E = OwnedModules.end_added();
276 Function *F = M->getFunction(Name);
277 if (F && !F->isDeclaration())
279 if (!CheckFunctionsOnly) {
280 GlobalVariable *G = M->getGlobalVariable(Name);
281 if (G && !G->isDeclaration())
283 // FIXME: Do we need to worry about global aliases?
286 // We didn't find the symbol in any of our modules.
290 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
291 bool CheckFunctionsOnly)
293 MutexGuard locked(lock);
295 // First, check to see if we already have this symbol.
296 uint64_t Addr = getExistingSymbolAddress(Name);
300 for (object::OwningBinary<object::Archive> &OB : Archives) {
301 object::Archive *A = OB.getBinary().get();
302 // Look for our symbols in each Archive
303 object::Archive::child_iterator ChildIt = A->findSym(Name);
304 if (ChildIt != A->child_end()) {
305 // FIXME: Support nested archives?
306 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
307 ChildIt->getAsBinary();
308 if (ChildBinOrErr.getError())
310 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
311 if (ChildBin->isObject()) {
312 std::unique_ptr<object::ObjectFile> OF(
313 static_cast<object::ObjectFile *>(ChildBin.release()));
314 // This causes the object file to be loaded.
315 addObjectFile(std::move(OF));
316 // The address should be here now.
317 Addr = getExistingSymbolAddress(Name);
324 // If it hasn't already been generated, see if it's in one of our modules.
325 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
327 generateCodeForModule(M);
329 // Check the RuntimeDyld table again, it should be there now.
330 return getExistingSymbolAddress(Name);
333 // If a LazyFunctionCreator is installed, use it to get/create the function.
334 // FIXME: Should we instead have a LazySymbolCreator callback?
335 if (LazyFunctionCreator)
336 Addr = (uint64_t)LazyFunctionCreator(Name);
341 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
342 MutexGuard locked(lock);
343 uint64_t Result = getSymbolAddress(Name, false);
345 finalizeLoadedModules();
349 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
350 MutexGuard locked(lock);
351 uint64_t Result = getSymbolAddress(Name, true);
353 finalizeLoadedModules();
357 // Deprecated. Use getFunctionAddress instead.
358 void *MCJIT::getPointerToFunction(Function *F) {
359 MutexGuard locked(lock);
361 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
362 bool AbortOnFailure = !F->hasExternalWeakLinkage();
363 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
364 addGlobalMapping(F, Addr);
368 Module *M = F->getParent();
369 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
371 // Make sure the relevant module has been compiled and loaded.
372 if (HasBeenAddedButNotLoaded)
373 generateCodeForModule(M);
374 else if (!OwnedModules.hasModuleBeenLoaded(M))
375 // If this function doesn't belong to one of our modules, we're done.
378 // FIXME: Should the Dyld be retaining module information? Probably not.
380 // This is the accessor for the target address, so make sure to check the
381 // load address of the symbol, not the local address.
382 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
383 SmallString<128> Name;
384 TM->getNameWithPrefix(Name, F, Mang);
385 return (void*)Dyld.getSymbolLoadAddress(Name);
388 void *MCJIT::recompileAndRelinkFunction(Function *F) {
389 report_fatal_error("not yet implemented");
392 void MCJIT::freeMachineCodeForFunction(Function *F) {
393 report_fatal_error("not yet implemented");
396 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
397 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
398 for (; I != E; ++I) {
399 ExecutionEngine::runStaticConstructorsDestructors(**I, isDtors);
403 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
404 // Execute global ctors/dtors for each module in the program.
405 runStaticConstructorsDestructorsInModulePtrSet(
406 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
407 runStaticConstructorsDestructorsInModulePtrSet(
408 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
409 runStaticConstructorsDestructorsInModulePtrSet(
410 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
413 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
414 ModulePtrSet::iterator I,
415 ModulePtrSet::iterator E) {
416 for (; I != E; ++I) {
417 if (Function *F = (*I)->getFunction(FnName))
423 Function *MCJIT::FindFunctionNamed(const char *FnName) {
424 Function *F = FindFunctionNamedInModulePtrSet(
425 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
427 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
428 OwnedModules.end_loaded());
430 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
431 OwnedModules.end_finalized());
435 GenericValue MCJIT::runFunction(Function *F,
436 const std::vector<GenericValue> &ArgValues) {
437 assert(F && "Function *F was null at entry to run()");
439 void *FPtr = getPointerToFunction(F);
440 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
441 FunctionType *FTy = F->getFunctionType();
442 Type *RetTy = FTy->getReturnType();
444 assert((FTy->getNumParams() == ArgValues.size() ||
445 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
446 "Wrong number of arguments passed into function!");
447 assert(FTy->getNumParams() == ArgValues.size() &&
448 "This doesn't support passing arguments through varargs (yet)!");
450 // Handle some common cases first. These cases correspond to common `main'
452 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
453 switch (ArgValues.size()) {
455 if (FTy->getParamType(0)->isIntegerTy(32) &&
456 FTy->getParamType(1)->isPointerTy() &&
457 FTy->getParamType(2)->isPointerTy()) {
458 int (*PF)(int, char **, const char **) =
459 (int(*)(int, char **, const char **))(intptr_t)FPtr;
461 // Call the function.
463 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
464 (char **)GVTOP(ArgValues[1]),
465 (const char **)GVTOP(ArgValues[2])));
470 if (FTy->getParamType(0)->isIntegerTy(32) &&
471 FTy->getParamType(1)->isPointerTy()) {
472 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
474 // Call the function.
476 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
477 (char **)GVTOP(ArgValues[1])));
482 if (FTy->getNumParams() == 1 &&
483 FTy->getParamType(0)->isIntegerTy(32)) {
485 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
486 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
493 // Handle cases where no arguments are passed first.
494 if (ArgValues.empty()) {
496 switch (RetTy->getTypeID()) {
497 default: llvm_unreachable("Unknown return type for function call!");
498 case Type::IntegerTyID: {
499 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
501 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
502 else if (BitWidth <= 8)
503 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
504 else if (BitWidth <= 16)
505 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
506 else if (BitWidth <= 32)
507 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
508 else if (BitWidth <= 64)
509 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
511 llvm_unreachable("Integer types > 64 bits not supported");
515 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
517 case Type::FloatTyID:
518 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
520 case Type::DoubleTyID:
521 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
523 case Type::X86_FP80TyID:
524 case Type::FP128TyID:
525 case Type::PPC_FP128TyID:
526 llvm_unreachable("long double not supported yet");
527 case Type::PointerTyID:
528 return PTOGV(((void*(*)())(intptr_t)FPtr)());
532 llvm_unreachable("Full-featured argument passing not supported yet!");
535 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
536 bool AbortOnFailure) {
537 if (!isSymbolSearchingDisabled()) {
538 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
543 /// If a LazyFunctionCreator is installed, use it to get/create the function.
544 if (LazyFunctionCreator)
545 if (void *RP = LazyFunctionCreator(Name))
548 if (AbortOnFailure) {
549 report_fatal_error("Program used external function '"+Name+
550 "' which could not be resolved!");
555 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
558 MutexGuard locked(lock);
559 EventListeners.push_back(L);
561 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
564 MutexGuard locked(lock);
565 SmallVector<JITEventListener*, 2>::reverse_iterator I=
566 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
567 if (I != EventListeners.rend()) {
568 std::swap(*I, EventListeners.back());
569 EventListeners.pop_back();
572 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
573 MutexGuard locked(lock);
574 MemMgr.notifyObjectLoaded(this, &Obj);
575 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
576 EventListeners[I]->NotifyObjectEmitted(Obj);
579 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
580 MutexGuard locked(lock);
581 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
582 EventListeners[I]->NotifyFreeingObject(Obj);
586 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
587 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
588 // If the symbols wasn't found and it begins with an underscore, try again
589 // without the underscore.
590 if (!Result && Name[0] == '_')
591 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
594 if (ParentEngine->isSymbolSearchingDisabled())
596 return ClientMM->getSymbolAddress(Name);