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"
36 static struct RegisterJIT {
37 RegisterJIT() { MCJIT::Register(); }
42 extern "C" void LLVMLinkInMCJIT() {
45 ExecutionEngine *MCJIT::createJIT(Module *M,
46 std::string *ErrorStr,
47 RTDyldMemoryManager *MemMgr,
49 // Try to register the program as a source of symbols to resolve against.
51 // FIXME: Don't do this here.
52 sys::DynamicLibrary::LoadLibraryPermanently(nullptr, nullptr);
54 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager());
57 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM)
58 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
61 OwnedModules.addModule(m);
62 setDataLayout(TM->getDataLayout());
66 MutexGuard locked(lock);
67 // FIXME: We are managing our modules, so we do not want the base class
68 // ExecutionEngine to manage them as well. To avoid double destruction
69 // of the first (and only) module added in ExecutionEngine constructor
70 // we remove it from EE and will destruct it ourselves.
72 // It may make sense to move our module manager (based on SmallStPtr) back
73 // into EE if the JIT and Interpreter can live with it.
74 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
75 // runStaticConstructorsDestructors could be moved back to EE as well.
78 Dyld.deregisterEHFrames();
80 LoadedObjectList::iterator it, end;
81 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
82 ObjectImage *Obj = *it;
84 NotifyFreeingObject(*Obj);
88 LoadedObjects.clear();
91 SmallVector<object::Archive *, 2>::iterator ArIt, ArEnd;
92 for (ArIt = Archives.begin(), ArEnd = Archives.end(); ArIt != ArEnd; ++ArIt) {
93 object::Archive *A = *ArIt;
101 void MCJIT::addModule(Module *M) {
102 MutexGuard locked(lock);
103 OwnedModules.addModule(M);
106 bool MCJIT::removeModule(Module *M) {
107 MutexGuard locked(lock);
108 return OwnedModules.removeModule(M);
113 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
114 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
115 if (!LoadedObject || Dyld.hasError())
116 report_fatal_error(Dyld.getErrorString());
118 LoadedObjects.push_back(LoadedObject);
120 NotifyObjectEmitted(*LoadedObject);
123 void MCJIT::addArchive(object::Archive *A) {
124 Archives.push_back(A);
128 void MCJIT::setObjectCache(ObjectCache* NewCache) {
129 MutexGuard locked(lock);
133 ObjectBufferStream* MCJIT::emitObject(Module *M) {
134 MutexGuard locked(lock);
136 // This must be a module which has already been added but not loaded to this
137 // MCJIT instance, since these conditions are tested by our caller,
138 // generateCodeForModule.
142 M->setDataLayout(TM->getDataLayout());
143 PM.add(new DataLayoutPass(M));
145 // The RuntimeDyld will take ownership of this shortly
146 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
148 // Turn the machine code intermediate representation into bytes in memory
149 // that may be executed.
150 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
151 !getVerifyModules())) {
152 report_fatal_error("Target does not support MC emission!");
155 // Initialize passes.
157 // Flush the output buffer to get the generated code into memory
158 CompiledObject->flush();
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 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
166 ObjCache->notifyObjectCompiled(M, MB.get());
169 return CompiledObject.release();
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<ObjectBuffer> ObjectToLoad;
185 // Try to load the pre-compiled object from cache if possible
187 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
188 if (PreCompiledObject.get())
189 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
192 // If the cache did not contain a suitable object, compile the object
194 ObjectToLoad.reset(emitObject(M));
195 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
198 // Load the object into the dynamic linker.
199 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
200 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
201 LoadedObjects.push_back(LoadedObject);
203 report_fatal_error(Dyld.getErrorString());
205 // FIXME: Make this optional, maybe even move it to a JIT event listener
206 LoadedObject->registerWithDebugger();
208 NotifyObjectEmitted(*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 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
233 E = OwnedModules.end_added();
236 generateCodeForModule(M);
239 finalizeLoadedModules();
242 void MCJIT::finalizeModule(Module *M) {
243 MutexGuard locked(lock);
245 // This must be a module which has already been added to this MCJIT instance.
246 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
248 // If the module hasn't been compiled, just do that.
249 if (!OwnedModules.hasModuleBeenLoaded(M))
250 generateCodeForModule(M);
252 finalizeLoadedModules();
255 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
256 report_fatal_error("not yet implemented");
259 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
260 Mangler Mang(TM->getDataLayout());
261 SmallString<128> FullName;
262 Mang.getNameWithPrefix(FullName, Name);
263 return Dyld.getSymbolLoadAddress(FullName);
266 Module *MCJIT::findModuleForSymbol(const std::string &Name,
267 bool CheckFunctionsOnly) {
268 MutexGuard locked(lock);
270 // If it hasn't already been generated, see if it's in one of our modules.
271 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
272 E = OwnedModules.end_added();
275 Function *F = M->getFunction(Name);
276 if (F && !F->isDeclaration())
278 if (!CheckFunctionsOnly) {
279 GlobalVariable *G = M->getGlobalVariable(Name);
280 if (G && !G->isDeclaration())
282 // FIXME: Do we need to worry about global aliases?
285 // We didn't find the symbol in any of our modules.
289 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
290 bool CheckFunctionsOnly)
292 MutexGuard locked(lock);
294 // First, check to see if we already have this symbol.
295 uint64_t Addr = getExistingSymbolAddress(Name);
299 SmallVector<object::Archive*, 2>::iterator I, E;
300 for (I = Archives.begin(), E = Archives.end(); I != E; ++I) {
301 object::Archive *A = *I;
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 = std::move(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);
329 generateCodeForModule(M);
331 // Check the RuntimeDyld table again, it should be there now.
332 return getExistingSymbolAddress(Name);
335 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
336 MutexGuard locked(lock);
337 uint64_t Result = getSymbolAddress(Name, false);
339 finalizeLoadedModules();
343 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
344 MutexGuard locked(lock);
345 uint64_t Result = getSymbolAddress(Name, true);
347 finalizeLoadedModules();
351 // Deprecated. Use getFunctionAddress instead.
352 void *MCJIT::getPointerToFunction(Function *F) {
353 MutexGuard locked(lock);
355 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
356 bool AbortOnFailure = !F->hasExternalWeakLinkage();
357 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
358 addGlobalMapping(F, Addr);
362 Module *M = F->getParent();
363 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
365 // Make sure the relevant module has been compiled and loaded.
366 if (HasBeenAddedButNotLoaded)
367 generateCodeForModule(M);
368 else if (!OwnedModules.hasModuleBeenLoaded(M))
369 // If this function doesn't belong to one of our modules, we're done.
372 // FIXME: Should the Dyld be retaining module information? Probably not.
374 // This is the accessor for the target address, so make sure to check the
375 // load address of the symbol, not the local address.
376 Mangler Mang(TM->getDataLayout());
377 SmallString<128> Name;
378 TM->getNameWithPrefix(Name, F, Mang);
379 return (void*)Dyld.getSymbolLoadAddress(Name);
382 void *MCJIT::recompileAndRelinkFunction(Function *F) {
383 report_fatal_error("not yet implemented");
386 void MCJIT::freeMachineCodeForFunction(Function *F) {
387 report_fatal_error("not yet implemented");
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 if (Function *F = (*I)->getFunction(FnName))
417 Function *MCJIT::FindFunctionNamed(const char *FnName) {
418 Function *F = FindFunctionNamedInModulePtrSet(
419 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
421 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
422 OwnedModules.end_loaded());
424 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
425 OwnedModules.end_finalized());
429 GenericValue MCJIT::runFunction(Function *F,
430 const std::vector<GenericValue> &ArgValues) {
431 assert(F && "Function *F was null at entry to run()");
433 void *FPtr = getPointerToFunction(F);
434 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
435 FunctionType *FTy = F->getFunctionType();
436 Type *RetTy = FTy->getReturnType();
438 assert((FTy->getNumParams() == ArgValues.size() ||
439 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
440 "Wrong number of arguments passed into function!");
441 assert(FTy->getNumParams() == ArgValues.size() &&
442 "This doesn't support passing arguments through varargs (yet)!");
444 // Handle some common cases first. These cases correspond to common `main'
446 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
447 switch (ArgValues.size()) {
449 if (FTy->getParamType(0)->isIntegerTy(32) &&
450 FTy->getParamType(1)->isPointerTy() &&
451 FTy->getParamType(2)->isPointerTy()) {
452 int (*PF)(int, char **, const char **) =
453 (int(*)(int, char **, const char **))(intptr_t)FPtr;
455 // Call the function.
457 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
458 (char **)GVTOP(ArgValues[1]),
459 (const char **)GVTOP(ArgValues[2])));
464 if (FTy->getParamType(0)->isIntegerTy(32) &&
465 FTy->getParamType(1)->isPointerTy()) {
466 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
468 // Call the function.
470 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
471 (char **)GVTOP(ArgValues[1])));
476 if (FTy->getNumParams() == 1 &&
477 FTy->getParamType(0)->isIntegerTy(32)) {
479 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
480 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
487 // Handle cases where no arguments are passed first.
488 if (ArgValues.empty()) {
490 switch (RetTy->getTypeID()) {
491 default: llvm_unreachable("Unknown return type for function call!");
492 case Type::IntegerTyID: {
493 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
495 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
496 else if (BitWidth <= 8)
497 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
498 else if (BitWidth <= 16)
499 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
500 else if (BitWidth <= 32)
501 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
502 else if (BitWidth <= 64)
503 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
505 llvm_unreachable("Integer types > 64 bits not supported");
509 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
511 case Type::FloatTyID:
512 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
514 case Type::DoubleTyID:
515 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
517 case Type::X86_FP80TyID:
518 case Type::FP128TyID:
519 case Type::PPC_FP128TyID:
520 llvm_unreachable("long double not supported yet");
521 case Type::PointerTyID:
522 return PTOGV(((void*(*)())(intptr_t)FPtr)());
526 llvm_unreachable("Full-featured argument passing not supported yet!");
529 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
530 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);
555 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
558 MutexGuard locked(lock);
559 SmallVector<JITEventListener*, 2>::reverse_iterator I=
560 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
561 if (I != EventListeners.rend()) {
562 std::swap(*I, EventListeners.back());
563 EventListeners.pop_back();
566 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
567 MutexGuard locked(lock);
568 MemMgr.notifyObjectLoaded(this, &Obj);
569 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
570 EventListeners[I]->NotifyObjectEmitted(Obj);
573 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
574 MutexGuard locked(lock);
575 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
576 EventListeners[I]->NotifyFreeingObject(Obj);
580 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
581 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
582 // If the symbols wasn't found and it begins with an underscore, try again
583 // without the underscore.
584 if (!Result && Name[0] == '_')
585 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
588 return ClientMM->getSymbolAddress(Name);