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(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(M, TM, MemMgr ? MemMgr : new SectionMemoryManager());
58 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM)
59 : ExecutionEngine(m), TM(tm), Ctx(nullptr), MemMgr(this, MM), Dyld(&MemMgr),
62 OwnedModules.addModule(m);
63 setDataLayout(TM->getSubtargetImpl()->getDataLayout());
67 MutexGuard locked(lock);
68 // FIXME: We are managing our modules, so we do not want the base class
69 // ExecutionEngine to manage them as well. To avoid double destruction
70 // of the first (and only) module added in ExecutionEngine constructor
71 // we remove it from EE and will destruct it ourselves.
73 // It may make sense to move our module manager (based on SmallStPtr) back
74 // into EE if the JIT and Interpreter can live with it.
75 // If so, additional functions: addModule, removeModule, FindFunctionNamed,
76 // runStaticConstructorsDestructors could be moved back to EE as well.
79 Dyld.deregisterEHFrames();
81 LoadedObjectList::iterator it, end;
82 for (it = LoadedObjects.begin(), end = LoadedObjects.end(); it != end; ++it) {
83 ObjectImage *Obj = *it;
85 NotifyFreeingObject(*Obj);
89 LoadedObjects.clear();
96 void MCJIT::addModule(Module *M) {
97 MutexGuard locked(lock);
98 OwnedModules.addModule(M);
101 bool MCJIT::removeModule(Module *M) {
102 MutexGuard locked(lock);
103 return OwnedModules.removeModule(M);
108 void MCJIT::addObjectFile(std::unique_ptr<object::ObjectFile> Obj) {
109 ObjectImage *LoadedObject = Dyld.loadObject(std::move(Obj));
110 if (!LoadedObject || Dyld.hasError())
111 report_fatal_error(Dyld.getErrorString());
113 LoadedObjects.push_back(LoadedObject);
115 NotifyObjectEmitted(*LoadedObject);
118 void MCJIT::addArchive(std::unique_ptr<object::Archive> A) {
119 Archives.push_back(std::move(A));
123 void MCJIT::setObjectCache(ObjectCache* NewCache) {
124 MutexGuard locked(lock);
128 ObjectBufferStream* MCJIT::emitObject(Module *M) {
129 MutexGuard locked(lock);
131 // This must be a module which has already been added but not loaded to this
132 // MCJIT instance, since these conditions are tested by our caller,
133 // generateCodeForModule.
137 M->setDataLayout(TM->getSubtargetImpl()->getDataLayout());
138 PM.add(new DataLayoutPass(M));
140 // The RuntimeDyld will take ownership of this shortly
141 std::unique_ptr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
143 // Turn the machine code intermediate representation into bytes in memory
144 // that may be executed.
145 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(),
146 !getVerifyModules())) {
147 report_fatal_error("Target does not support MC emission!");
150 // Initialize passes.
152 // Flush the output buffer to get the generated code into memory
153 CompiledObject->flush();
155 // If we have an object cache, tell it about the new object.
156 // Note that we're using the compiled image, not the loaded image (as below).
158 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
159 // to create a temporary object here and delete it after the call.
160 std::unique_ptr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
161 ObjCache->notifyObjectCompiled(M, MB.get());
164 return CompiledObject.release();
167 void MCJIT::generateCodeForModule(Module *M) {
168 // Get a thread lock to make sure we aren't trying to load multiple times
169 MutexGuard locked(lock);
171 // This must be a module which has already been added to this MCJIT instance.
172 assert(OwnedModules.ownsModule(M) &&
173 "MCJIT::generateCodeForModule: Unknown module.");
175 // Re-compilation is not supported
176 if (OwnedModules.hasModuleBeenLoaded(M))
179 std::unique_ptr<ObjectBuffer> ObjectToLoad;
180 // Try to load the pre-compiled object from cache if possible
182 std::unique_ptr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
183 if (PreCompiledObject.get())
184 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.release()));
187 // If the cache did not contain a suitable object, compile the object
189 ObjectToLoad.reset(emitObject(M));
190 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
193 // Load the object into the dynamic linker.
194 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects list).
195 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.release());
196 LoadedObjects.push_back(LoadedObject);
198 report_fatal_error(Dyld.getErrorString());
200 // FIXME: Make this optional, maybe even move it to a JIT event listener
201 LoadedObject->registerWithDebugger();
203 NotifyObjectEmitted(*LoadedObject);
205 OwnedModules.markModuleAsLoaded(M);
208 void MCJIT::finalizeLoadedModules() {
209 MutexGuard locked(lock);
211 // Resolve any outstanding relocations.
212 Dyld.resolveRelocations();
214 OwnedModules.markAllLoadedModulesAsFinalized();
216 // Register EH frame data for any module we own which has been loaded
217 Dyld.registerEHFrames();
219 // Set page permissions.
220 MemMgr.finalizeMemory();
223 // FIXME: Rename this.
224 void MCJIT::finalizeObject() {
225 MutexGuard locked(lock);
227 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
228 E = OwnedModules.end_added();
231 generateCodeForModule(M);
234 finalizeLoadedModules();
237 void MCJIT::finalizeModule(Module *M) {
238 MutexGuard locked(lock);
240 // This must be a module which has already been added to this MCJIT instance.
241 assert(OwnedModules.ownsModule(M) && "MCJIT::finalizeModule: Unknown module.");
243 // If the module hasn't been compiled, just do that.
244 if (!OwnedModules.hasModuleBeenLoaded(M))
245 generateCodeForModule(M);
247 finalizeLoadedModules();
250 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
251 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
252 SmallString<128> FullName;
253 Mang.getNameWithPrefix(FullName, Name);
254 return Dyld.getSymbolLoadAddress(FullName);
257 Module *MCJIT::findModuleForSymbol(const std::string &Name,
258 bool CheckFunctionsOnly) {
259 MutexGuard locked(lock);
261 // If it hasn't already been generated, see if it's in one of our modules.
262 for (ModulePtrSet::iterator I = OwnedModules.begin_added(),
263 E = OwnedModules.end_added();
266 Function *F = M->getFunction(Name);
267 if (F && !F->isDeclaration())
269 if (!CheckFunctionsOnly) {
270 GlobalVariable *G = M->getGlobalVariable(Name);
271 if (G && !G->isDeclaration())
273 // FIXME: Do we need to worry about global aliases?
276 // We didn't find the symbol in any of our modules.
280 uint64_t MCJIT::getSymbolAddress(const std::string &Name,
281 bool CheckFunctionsOnly)
283 MutexGuard locked(lock);
285 // First, check to see if we already have this symbol.
286 uint64_t Addr = getExistingSymbolAddress(Name);
290 for (std::unique_ptr<object::Archive> &A : Archives) {
291 // Look for our symbols in each Archive
292 object::Archive::child_iterator ChildIt = A->findSym(Name);
293 if (ChildIt != A->child_end()) {
294 // FIXME: Support nested archives?
295 ErrorOr<std::unique_ptr<object::Binary>> ChildBinOrErr =
296 ChildIt->getAsBinary();
297 if (ChildBinOrErr.getError())
299 std::unique_ptr<object::Binary> &ChildBin = ChildBinOrErr.get();
300 if (ChildBin->isObject()) {
301 std::unique_ptr<object::ObjectFile> OF(
302 static_cast<object::ObjectFile *>(ChildBin.release()));
303 // This causes the object file to be loaded.
304 addObjectFile(std::move(OF));
305 // The address should be here now.
306 Addr = getExistingSymbolAddress(Name);
313 // If it hasn't already been generated, see if it's in one of our modules.
314 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
318 generateCodeForModule(M);
320 // Check the RuntimeDyld table again, it should be there now.
321 return getExistingSymbolAddress(Name);
324 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
325 MutexGuard locked(lock);
326 uint64_t Result = getSymbolAddress(Name, false);
328 finalizeLoadedModules();
332 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
333 MutexGuard locked(lock);
334 uint64_t Result = getSymbolAddress(Name, true);
336 finalizeLoadedModules();
340 // Deprecated. Use getFunctionAddress instead.
341 void *MCJIT::getPointerToFunction(Function *F) {
342 MutexGuard locked(lock);
344 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
345 bool AbortOnFailure = !F->hasExternalWeakLinkage();
346 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
347 addGlobalMapping(F, Addr);
351 Module *M = F->getParent();
352 bool HasBeenAddedButNotLoaded = OwnedModules.hasModuleBeenAddedButNotLoaded(M);
354 // Make sure the relevant module has been compiled and loaded.
355 if (HasBeenAddedButNotLoaded)
356 generateCodeForModule(M);
357 else if (!OwnedModules.hasModuleBeenLoaded(M))
358 // If this function doesn't belong to one of our modules, we're done.
361 // FIXME: Should the Dyld be retaining module information? Probably not.
363 // This is the accessor for the target address, so make sure to check the
364 // load address of the symbol, not the local address.
365 Mangler Mang(TM->getSubtargetImpl()->getDataLayout());
366 SmallString<128> Name;
367 TM->getNameWithPrefix(Name, F, Mang);
368 return (void*)Dyld.getSymbolLoadAddress(Name);
371 void MCJIT::runStaticConstructorsDestructorsInModulePtrSet(
372 bool isDtors, ModulePtrSet::iterator I, ModulePtrSet::iterator E) {
373 for (; I != E; ++I) {
374 ExecutionEngine::runStaticConstructorsDestructors(*I, isDtors);
378 void MCJIT::runStaticConstructorsDestructors(bool isDtors) {
379 // Execute global ctors/dtors for each module in the program.
380 runStaticConstructorsDestructorsInModulePtrSet(
381 isDtors, OwnedModules.begin_added(), OwnedModules.end_added());
382 runStaticConstructorsDestructorsInModulePtrSet(
383 isDtors, OwnedModules.begin_loaded(), OwnedModules.end_loaded());
384 runStaticConstructorsDestructorsInModulePtrSet(
385 isDtors, OwnedModules.begin_finalized(), OwnedModules.end_finalized());
388 Function *MCJIT::FindFunctionNamedInModulePtrSet(const char *FnName,
389 ModulePtrSet::iterator I,
390 ModulePtrSet::iterator E) {
391 for (; I != E; ++I) {
392 if (Function *F = (*I)->getFunction(FnName))
398 Function *MCJIT::FindFunctionNamed(const char *FnName) {
399 Function *F = FindFunctionNamedInModulePtrSet(
400 FnName, OwnedModules.begin_added(), OwnedModules.end_added());
402 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_loaded(),
403 OwnedModules.end_loaded());
405 F = FindFunctionNamedInModulePtrSet(FnName, OwnedModules.begin_finalized(),
406 OwnedModules.end_finalized());
410 GenericValue MCJIT::runFunction(Function *F,
411 const std::vector<GenericValue> &ArgValues) {
412 assert(F && "Function *F was null at entry to run()");
414 void *FPtr = getPointerToFunction(F);
415 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
416 FunctionType *FTy = F->getFunctionType();
417 Type *RetTy = FTy->getReturnType();
419 assert((FTy->getNumParams() == ArgValues.size() ||
420 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
421 "Wrong number of arguments passed into function!");
422 assert(FTy->getNumParams() == ArgValues.size() &&
423 "This doesn't support passing arguments through varargs (yet)!");
425 // Handle some common cases first. These cases correspond to common `main'
427 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
428 switch (ArgValues.size()) {
430 if (FTy->getParamType(0)->isIntegerTy(32) &&
431 FTy->getParamType(1)->isPointerTy() &&
432 FTy->getParamType(2)->isPointerTy()) {
433 int (*PF)(int, char **, const char **) =
434 (int(*)(int, char **, const char **))(intptr_t)FPtr;
436 // Call the function.
438 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
439 (char **)GVTOP(ArgValues[1]),
440 (const char **)GVTOP(ArgValues[2])));
445 if (FTy->getParamType(0)->isIntegerTy(32) &&
446 FTy->getParamType(1)->isPointerTy()) {
447 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
449 // Call the function.
451 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
452 (char **)GVTOP(ArgValues[1])));
457 if (FTy->getNumParams() == 1 &&
458 FTy->getParamType(0)->isIntegerTy(32)) {
460 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
461 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
468 // Handle cases where no arguments are passed first.
469 if (ArgValues.empty()) {
471 switch (RetTy->getTypeID()) {
472 default: llvm_unreachable("Unknown return type for function call!");
473 case Type::IntegerTyID: {
474 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
476 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
477 else if (BitWidth <= 8)
478 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
479 else if (BitWidth <= 16)
480 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
481 else if (BitWidth <= 32)
482 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
483 else if (BitWidth <= 64)
484 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
486 llvm_unreachable("Integer types > 64 bits not supported");
490 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
492 case Type::FloatTyID:
493 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
495 case Type::DoubleTyID:
496 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
498 case Type::X86_FP80TyID:
499 case Type::FP128TyID:
500 case Type::PPC_FP128TyID:
501 llvm_unreachable("long double not supported yet");
502 case Type::PointerTyID:
503 return PTOGV(((void*(*)())(intptr_t)FPtr)());
507 llvm_unreachable("Full-featured argument passing not supported yet!");
510 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
511 bool AbortOnFailure) {
512 if (!isSymbolSearchingDisabled()) {
513 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
518 /// If a LazyFunctionCreator is installed, use it to get/create the function.
519 if (LazyFunctionCreator)
520 if (void *RP = LazyFunctionCreator(Name))
523 if (AbortOnFailure) {
524 report_fatal_error("Program used external function '"+Name+
525 "' which could not be resolved!");
530 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
533 MutexGuard locked(lock);
534 EventListeners.push_back(L);
536 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
539 MutexGuard locked(lock);
540 auto I = std::find(EventListeners.rbegin(), EventListeners.rend(), L);
541 if (I != EventListeners.rend()) {
542 std::swap(*I, EventListeners.back());
543 EventListeners.pop_back();
546 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
547 MutexGuard locked(lock);
548 MemMgr.notifyObjectLoaded(this, &Obj);
549 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
550 EventListeners[I]->NotifyObjectEmitted(Obj);
553 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
554 MutexGuard locked(lock);
555 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
556 JITEventListener *L = EventListeners[I];
557 L->NotifyFreeingObject(Obj);
561 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
562 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
563 // If the symbols wasn't found and it begins with an underscore, try again
564 // without the underscore.
565 if (!Result && Name[0] == '_')
566 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
569 return ClientMM->getSymbolAddress(Name);