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/Module.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Support/DynamicLibrary.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/MutexGuard.h"
32 static struct RegisterJIT {
33 RegisterJIT() { MCJIT::Register(); }
38 extern "C" void LLVMLinkInMCJIT() {
41 ExecutionEngine *MCJIT::createJIT(Module *M,
42 std::string *ErrorStr,
43 RTDyldMemoryManager *MemMgr,
46 // Try to register the program as a source of symbols to resolve against.
48 // FIXME: Don't do this here.
49 sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
51 return new MCJIT(M, TM, MemMgr ? MemMgr : new SectionMemoryManager(),
55 MCJIT::MCJIT(Module *m, TargetMachine *tm, RTDyldMemoryManager *MM,
56 bool AllocateGVsWithCode)
57 : ExecutionEngine(m), TM(tm), Ctx(0), MemMgr(this, MM), Dyld(&MemMgr),
60 ModuleStates[m] = ModuleAdded;
61 setDataLayout(TM->getDataLayout());
65 Dyld.deregisterEHFrames();
67 LoadedObjectMap::iterator it, end = LoadedObjects.end();
68 for (it = LoadedObjects.begin(); it != end; ++it) {
69 ObjectImage *Obj = it->second;
71 NotifyFreeingObject(*Obj);
75 LoadedObjects.clear();
79 void MCJIT::addModule(Module *M) {
81 ModuleStates[M] = MCJITModuleState();
84 void MCJIT::setObjectCache(ObjectCache* NewCache) {
88 ObjectBufferStream* MCJIT::emitObject(Module *M) {
89 // This must be a module which has already been added to this MCJIT instance.
90 assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
91 assert(ModuleStates.find(M) != ModuleStates.end());
93 // Get a thread lock to make sure we aren't trying to compile multiple times
94 MutexGuard locked(lock);
96 // Re-compilation is not supported
97 assert(!ModuleStates[M].hasBeenEmitted());
101 PM.add(new DataLayout(*TM->getDataLayout()));
103 // The RuntimeDyld will take ownership of this shortly
104 OwningPtr<ObjectBufferStream> CompiledObject(new ObjectBufferStream());
106 // Turn the machine code intermediate representation into bytes in memory
107 // that may be executed.
108 if (TM->addPassesToEmitMC(PM, Ctx, CompiledObject->getOStream(), false)) {
109 report_fatal_error("Target does not support MC emission!");
112 // Initialize passes.
114 // Flush the output buffer to get the generated code into memory
115 CompiledObject->flush();
117 // If we have an object cache, tell it about the new object.
118 // Note that we're using the compiled image, not the loaded image (as below).
120 // MemoryBuffer is a thin wrapper around the actual memory, so it's OK
121 // to create a temporary object here and delete it after the call.
122 OwningPtr<MemoryBuffer> MB(CompiledObject->getMemBuffer());
123 ObjCache->notifyObjectCompiled(M, MB.get());
126 return CompiledObject.take();
129 void MCJIT::generateCodeForModule(Module *M) {
130 // This must be a module which has already been added to this MCJIT instance.
131 assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
132 assert(ModuleStates.find(M) != ModuleStates.end());
134 // Get a thread lock to make sure we aren't trying to load multiple times
135 MutexGuard locked(lock);
137 // Re-compilation is not supported
138 if (ModuleStates[M].hasBeenLoaded())
141 OwningPtr<ObjectBuffer> ObjectToLoad;
142 // Try to load the pre-compiled object from cache if possible
144 OwningPtr<MemoryBuffer> PreCompiledObject(ObjCache->getObject(M));
145 if (0 != PreCompiledObject.get())
146 ObjectToLoad.reset(new ObjectBuffer(PreCompiledObject.take()));
149 // If the cache did not contain a suitable object, compile the object
151 ObjectToLoad.reset(emitObject(M));
152 assert(ObjectToLoad.get() && "Compilation did not produce an object.");
155 // Load the object into the dynamic linker.
156 // MCJIT now owns the ObjectImage pointer (via its LoadedObjects map).
157 ObjectImage *LoadedObject = Dyld.loadObject(ObjectToLoad.take());
158 LoadedObjects[M] = LoadedObject;
160 report_fatal_error(Dyld.getErrorString());
162 // FIXME: Make this optional, maybe even move it to a JIT event listener
163 LoadedObject->registerWithDebugger();
165 NotifyObjectEmitted(*LoadedObject);
167 ModuleStates[M] = ModuleLoaded;
170 void MCJIT::finalizeLoadedModules() {
171 // Resolve any outstanding relocations.
172 Dyld.resolveRelocations();
174 // Register EH frame data for any module we own which has been loaded
175 SmallVector<Module *, 1>::iterator end = Modules.end();
176 SmallVector<Module *, 1>::iterator it;
177 for (it = Modules.begin(); it != end; ++it) {
179 assert(ModuleStates.find(M) != ModuleStates.end());
181 if (ModuleStates[M].hasBeenLoaded() &&
182 !ModuleStates[M].hasBeenFinalized()) {
183 ModuleStates[M] = ModuleFinalized;
187 Dyld.registerEHFrames();
189 // Set page permissions.
190 MemMgr.finalizeMemory();
193 // FIXME: Rename this.
194 void MCJIT::finalizeObject() {
195 // FIXME: This is a temporary hack to get around problems with calling
196 // finalize multiple times.
197 bool finalizeNeeded = false;
198 SmallVector<Module *, 1>::iterator end = Modules.end();
199 SmallVector<Module *, 1>::iterator it;
200 for (it = Modules.begin(); it != end; ++it) {
202 assert(ModuleStates.find(M) != ModuleStates.end());
203 if (!ModuleStates[M].hasBeenFinalized())
204 finalizeNeeded = true;
206 // I don't really like this, but the C API depends on this behavior.
207 // I suppose it's OK for a deprecated function.
208 if (!ModuleStates[M].hasBeenLoaded())
209 generateCodeForModule(M);
214 // Resolve any outstanding relocations.
215 Dyld.resolveRelocations();
217 // Register EH frame data for any module we own which has been loaded
218 for (it = Modules.begin(); it != end; ++it) {
220 assert(ModuleStates.find(M) != ModuleStates.end());
222 if (ModuleStates[M].hasBeenLoaded() &&
223 !ModuleStates[M].hasBeenFinalized()) {
224 ModuleStates[M] = ModuleFinalized;
228 Dyld.registerEHFrames();
230 // Set page permissions.
231 MemMgr.finalizeMemory();
234 void MCJIT::finalizeModule(Module *M) {
235 // This must be a module which has already been added to this MCJIT instance.
236 assert(std::find(Modules.begin(), Modules.end(), M) != Modules.end());
237 assert(ModuleStates.find(M) != ModuleStates.end());
239 if (ModuleStates[M].hasBeenFinalized())
242 // If the module hasn't been compiled, just do that.
243 if (!ModuleStates[M].hasBeenLoaded())
244 generateCodeForModule(M);
246 // Resolve any outstanding relocations.
247 Dyld.resolveRelocations();
249 Dyld.registerEHFrames();
251 // Set page permissions.
252 MemMgr.finalizeMemory();
254 ModuleStates[M] = ModuleFinalized;
257 void *MCJIT::getPointerToBasicBlock(BasicBlock *BB) {
258 report_fatal_error("not yet implemented");
261 uint64_t MCJIT::getExistingSymbolAddress(const std::string &Name) {
262 // Check with the RuntimeDyld to see if we already have this symbol.
264 return Dyld.getSymbolLoadAddress(Name.substr(1));
265 return Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
269 Module *MCJIT::findModuleForSymbol(const std::string &Name,
270 bool CheckFunctionsOnly) {
271 // If it hasn't already been generated, see if it's in one of our modules.
272 SmallVector<Module *, 1>::iterator end = Modules.end();
273 SmallVector<Module *, 1>::iterator it;
274 for (it = Modules.begin(); it != end; ++it) {
276 Function *F = M->getFunction(Name);
277 if (F && !F->empty())
279 if (!CheckFunctionsOnly) {
280 GlobalVariable *G = M->getGlobalVariable(Name);
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 // First, check to see if we already have this symbol.
294 uint64_t Addr = getExistingSymbolAddress(Name);
298 // If it hasn't already been generated, see if it's in one of our modules.
299 Module *M = findModuleForSymbol(Name, CheckFunctionsOnly);
303 // If this is in one of our modules, generate code for that module.
304 assert(ModuleStates.find(M) != ModuleStates.end());
305 // If the module code has already been generated, we won't find the symbol.
306 if (ModuleStates[M].hasBeenLoaded())
309 // FIXME: We probably need to make sure we aren't in the process of
310 // loading or finalizing this module.
311 generateCodeForModule(M);
313 // Check the RuntimeDyld table again, it should be there now.
314 return getExistingSymbolAddress(Name);
317 uint64_t MCJIT::getGlobalValueAddress(const std::string &Name) {
318 uint64_t Result = getSymbolAddress(Name, false);
320 finalizeLoadedModules();
324 uint64_t MCJIT::getFunctionAddress(const std::string &Name) {
325 uint64_t Result = getSymbolAddress(Name, true);
327 finalizeLoadedModules();
331 // Deprecated. Use getFunctionAddress instead.
332 void *MCJIT::getPointerToFunction(Function *F) {
334 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
335 bool AbortOnFailure = !F->hasExternalWeakLinkage();
336 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
337 addGlobalMapping(F, Addr);
341 // If this function doesn't belong to one of our modules, we're done.
342 Module *M = F->getParent();
343 if (std::find(Modules.begin(), Modules.end(), M) == Modules.end())
346 assert(ModuleStates.find(M) != ModuleStates.end());
348 // Make sure the relevant module has been compiled and loaded.
349 if (!ModuleStates[M].hasBeenLoaded())
350 generateCodeForModule(M);
352 // FIXME: Should the Dyld be retaining module information? Probably not.
353 // FIXME: Should we be using the mangler for this? Probably.
355 // This is the accessor for the target address, so make sure to check the
356 // load address of the symbol, not the local address.
357 StringRef BaseName = F->getName();
358 if (BaseName[0] == '\1')
359 return (void*)Dyld.getSymbolLoadAddress(BaseName.substr(1));
360 return (void*)Dyld.getSymbolLoadAddress((TM->getMCAsmInfo()->getGlobalPrefix()
364 void *MCJIT::recompileAndRelinkFunction(Function *F) {
365 report_fatal_error("not yet implemented");
368 void MCJIT::freeMachineCodeForFunction(Function *F) {
369 report_fatal_error("not yet implemented");
372 GenericValue MCJIT::runFunction(Function *F,
373 const std::vector<GenericValue> &ArgValues) {
374 assert(F && "Function *F was null at entry to run()");
376 void *FPtr = getPointerToFunction(F);
377 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
378 FunctionType *FTy = F->getFunctionType();
379 Type *RetTy = FTy->getReturnType();
381 assert((FTy->getNumParams() == ArgValues.size() ||
382 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
383 "Wrong number of arguments passed into function!");
384 assert(FTy->getNumParams() == ArgValues.size() &&
385 "This doesn't support passing arguments through varargs (yet)!");
387 // Handle some common cases first. These cases correspond to common `main'
389 if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
390 switch (ArgValues.size()) {
392 if (FTy->getParamType(0)->isIntegerTy(32) &&
393 FTy->getParamType(1)->isPointerTy() &&
394 FTy->getParamType(2)->isPointerTy()) {
395 int (*PF)(int, char **, const char **) =
396 (int(*)(int, char **, const char **))(intptr_t)FPtr;
398 // Call the function.
400 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
401 (char **)GVTOP(ArgValues[1]),
402 (const char **)GVTOP(ArgValues[2])));
407 if (FTy->getParamType(0)->isIntegerTy(32) &&
408 FTy->getParamType(1)->isPointerTy()) {
409 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
411 // Call the function.
413 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
414 (char **)GVTOP(ArgValues[1])));
419 if (FTy->getNumParams() == 1 &&
420 FTy->getParamType(0)->isIntegerTy(32)) {
422 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
423 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
430 // Handle cases where no arguments are passed first.
431 if (ArgValues.empty()) {
433 switch (RetTy->getTypeID()) {
434 default: llvm_unreachable("Unknown return type for function call!");
435 case Type::IntegerTyID: {
436 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
438 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
439 else if (BitWidth <= 8)
440 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
441 else if (BitWidth <= 16)
442 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
443 else if (BitWidth <= 32)
444 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
445 else if (BitWidth <= 64)
446 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
448 llvm_unreachable("Integer types > 64 bits not supported");
452 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
454 case Type::FloatTyID:
455 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
457 case Type::DoubleTyID:
458 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
460 case Type::X86_FP80TyID:
461 case Type::FP128TyID:
462 case Type::PPC_FP128TyID:
463 llvm_unreachable("long double not supported yet");
464 case Type::PointerTyID:
465 return PTOGV(((void*(*)())(intptr_t)FPtr)());
469 llvm_unreachable("Full-featured argument passing not supported yet!");
472 void *MCJIT::getPointerToNamedFunction(const std::string &Name,
473 bool AbortOnFailure) {
474 if (!isSymbolSearchingDisabled()) {
475 void *ptr = MemMgr.getPointerToNamedFunction(Name, false);
480 /// If a LazyFunctionCreator is installed, use it to get/create the function.
481 if (LazyFunctionCreator)
482 if (void *RP = LazyFunctionCreator(Name))
485 if (AbortOnFailure) {
486 report_fatal_error("Program used external function '"+Name+
487 "' which could not be resolved!");
492 void MCJIT::RegisterJITEventListener(JITEventListener *L) {
495 MutexGuard locked(lock);
496 EventListeners.push_back(L);
498 void MCJIT::UnregisterJITEventListener(JITEventListener *L) {
501 MutexGuard locked(lock);
502 SmallVector<JITEventListener*, 2>::reverse_iterator I=
503 std::find(EventListeners.rbegin(), EventListeners.rend(), L);
504 if (I != EventListeners.rend()) {
505 std::swap(*I, EventListeners.back());
506 EventListeners.pop_back();
509 void MCJIT::NotifyObjectEmitted(const ObjectImage& Obj) {
510 MutexGuard locked(lock);
511 MemMgr.notifyObjectLoaded(this, &Obj);
512 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
513 EventListeners[I]->NotifyObjectEmitted(Obj);
516 void MCJIT::NotifyFreeingObject(const ObjectImage& Obj) {
517 MutexGuard locked(lock);
518 for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
519 EventListeners[I]->NotifyFreeingObject(Obj);
523 uint64_t LinkingMemoryManager::getSymbolAddress(const std::string &Name) {
524 uint64_t Result = ParentEngine->getSymbolAddress(Name, false);
525 // If the symbols wasn't found and it begins with an underscore, try again
526 // without the underscore.
527 if (!Result && Name[0] == '_')
528 Result = ParentEngine->getSymbolAddress(Name.substr(1), false);
531 return ClientMM->getSymbolAddress(Name);