1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bitcode in an efficient manner.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/CodeGen/MachineCodeEmitter.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/ExecutionEngine/GenericValue.h"
25 #include "llvm/Support/MutexGuard.h"
26 #include "llvm/System/DynamicLibrary.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Config/config.h"
36 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
37 // of atexit). It passes the address of linker generated symbol __dso_handle
39 // This configuration change happened at version 5330.
40 # include <AvailabilityMacros.h>
41 # if defined(MAC_OS_X_VERSION_10_4) && \
42 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
43 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
44 __APPLE_CC__ >= 5330))
45 # ifndef HAVE___DSO_HANDLE
46 # define HAVE___DSO_HANDLE 1
52 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
55 static struct RegisterJIT {
56 RegisterJIT() { JIT::Register(); }
64 /// createJIT - This is the factory method for creating a JIT for the current
65 /// machine, it does not fall back to the interpreter. This takes ownership
66 /// of the module provider.
67 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
68 std::string *ErrorStr,
69 JITMemoryManager *JMM) {
70 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
74 // Make sure we can resolve symbols in the program as well. The zero arg
75 // to the function tells DynamicLibrary to load the program, not a library.
76 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
80 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
81 JITMemoryManager *JMM)
82 : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
83 setTargetData(TM.getTargetData());
86 MCE = createEmitter(*this, JMM);
89 MutexGuard locked(lock);
90 FunctionPassManager &PM = jitstate.getPM(locked);
91 PM.add(new TargetData(*TM.getTargetData()));
93 // Turn the machine code intermediate representation into bytes in memory that
95 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
96 cerr << "Target does not support machine code emission!\n";
100 // Initialize passes.
101 PM.doInitialization();
109 /// run - Start execution with the specified function and arguments.
111 GenericValue JIT::runFunction(Function *F,
112 const std::vector<GenericValue> &ArgValues) {
113 assert(F && "Function *F was null at entry to run()");
115 void *FPtr = getPointerToFunction(F);
116 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
117 const FunctionType *FTy = F->getFunctionType();
118 const Type *RetTy = FTy->getReturnType();
120 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
121 "Too many arguments passed into function!");
122 assert(FTy->getNumParams() == ArgValues.size() &&
123 "This doesn't support passing arguments through varargs (yet)!");
125 // Handle some common cases first. These cases correspond to common `main'
127 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
128 switch (ArgValues.size()) {
130 if (FTy->getParamType(0) == Type::Int32Ty &&
131 isa<PointerType>(FTy->getParamType(1)) &&
132 isa<PointerType>(FTy->getParamType(2))) {
133 int (*PF)(int, char **, const char **) =
134 (int(*)(int, char **, const char **))(intptr_t)FPtr;
136 // Call the function.
138 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
139 (char **)GVTOP(ArgValues[1]),
140 (const char **)GVTOP(ArgValues[2])));
145 if (FTy->getParamType(0) == Type::Int32Ty &&
146 isa<PointerType>(FTy->getParamType(1))) {
147 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
149 // Call the function.
151 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
152 (char **)GVTOP(ArgValues[1])));
157 if (FTy->getNumParams() == 1 &&
158 FTy->getParamType(0) == Type::Int32Ty) {
160 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
161 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
168 // Handle cases where no arguments are passed first.
169 if (ArgValues.empty()) {
171 switch (RetTy->getTypeID()) {
172 default: assert(0 && "Unknown return type for function call!");
173 case Type::IntegerTyID: {
174 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
176 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
177 else if (BitWidth <= 8)
178 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
179 else if (BitWidth <= 16)
180 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
181 else if (BitWidth <= 32)
182 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
183 else if (BitWidth <= 64)
184 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
186 assert(0 && "Integer types > 64 bits not supported");
190 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
192 case Type::FloatTyID:
193 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
195 case Type::DoubleTyID:
196 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
198 case Type::X86_FP80TyID:
199 case Type::FP128TyID:
200 case Type::PPC_FP128TyID:
201 assert(0 && "long double not supported yet");
203 case Type::PointerTyID:
204 return PTOGV(((void*(*)())(intptr_t)FPtr)());
208 // Okay, this is not one of our quick and easy cases. Because we don't have a
209 // full FFI, we have to codegen a nullary stub function that just calls the
210 // function we are interested in, passing in constants for all of the
211 // arguments. Make this function and return.
213 // First, create the function.
214 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
215 Function *Stub = new Function(STy, Function::InternalLinkage, "",
218 // Insert a basic block.
219 BasicBlock *StubBB = new BasicBlock("", Stub);
221 // Convert all of the GenericValue arguments over to constants. Note that we
222 // currently don't support varargs.
223 SmallVector<Value*, 8> Args;
224 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
226 const Type *ArgTy = FTy->getParamType(i);
227 const GenericValue &AV = ArgValues[i];
228 switch (ArgTy->getTypeID()) {
229 default: assert(0 && "Unknown argument type for function call!");
230 case Type::IntegerTyID: C = ConstantInt::get(AV.IntVal); break;
231 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, APFloat(AV.FloatVal));
233 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, APFloat(AV.DoubleVal));
235 case Type::PPC_FP128TyID:
236 case Type::X86_FP80TyID:
237 case Type::FP128TyID: C = ConstantFP ::get(ArgTy, APFloat(AV.IntVal));
239 case Type::PointerTyID:
240 void *ArgPtr = GVTOP(AV);
241 if (sizeof(void*) == 4) {
242 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
244 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
246 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
252 CallInst *TheCall = new CallInst(F, Args.begin(), Args.end(), "", StubBB);
253 TheCall->setTailCall();
254 if (TheCall->getType() != Type::VoidTy)
255 new ReturnInst(TheCall, StubBB); // Return result of the call.
257 new ReturnInst(StubBB); // Just return void.
259 // Finally, return the value returned by our nullary stub function.
260 return runFunction(Stub, std::vector<GenericValue>());
263 /// runJITOnFunction - Run the FunctionPassManager full of
264 /// just-in-time compilation passes on F, hopefully filling in
265 /// GlobalAddress[F] with the address of F's machine code.
267 void JIT::runJITOnFunction(Function *F) {
268 static bool isAlreadyCodeGenerating = false;
270 MutexGuard locked(lock);
271 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
274 isAlreadyCodeGenerating = true;
275 jitstate.getPM(locked).run(*F);
276 isAlreadyCodeGenerating = false;
278 // If the function referred to a global variable that had not yet been
279 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
280 // all of these globals now.
281 while (!jitstate.getPendingGlobals(locked).empty()) {
282 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
283 jitstate.getPendingGlobals(locked).pop_back();
284 EmitGlobalVariable(GV);
288 /// getPointerToFunction - This method is used to get the address of the
289 /// specified function, compiling it if neccesary.
291 void *JIT::getPointerToFunction(Function *F) {
292 MutexGuard locked(lock);
294 if (void *Addr = getPointerToGlobalIfAvailable(F))
295 return Addr; // Check if function already code gen'd
297 // Make sure we read in the function if it exists in this Module.
298 if (F->hasNotBeenReadFromBitcode()) {
299 // Determine the module provider this function is provided by.
300 Module *M = F->getParent();
301 ModuleProvider *MP = 0;
302 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
303 if (Modules[i]->getModule() == M) {
308 assert(MP && "Function isn't in a module we know about!");
310 std::string ErrorMsg;
311 if (MP->materializeFunction(F, &ErrorMsg)) {
312 cerr << "Error reading function '" << F->getName()
313 << "' from bitcode file: " << ErrorMsg << "\n";
318 if (F->isDeclaration()) {
319 void *Addr = getPointerToNamedFunction(F->getName());
320 addGlobalMapping(F, Addr);
326 void *Addr = getPointerToGlobalIfAvailable(F);
327 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
331 /// getOrEmitGlobalVariable - Return the address of the specified global
332 /// variable, possibly emitting it to memory if needed. This is used by the
334 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
335 MutexGuard locked(lock);
337 void *Ptr = getPointerToGlobalIfAvailable(GV);
340 // If the global is external, just remember the address.
341 if (GV->isDeclaration()) {
342 #if HAVE___DSO_HANDLE
343 if (GV->getName() == "__dso_handle")
344 return (void*)&__dso_handle;
346 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
348 cerr << "Could not resolve external global address: "
349 << GV->getName() << "\n";
353 // If the global hasn't been emitted to memory yet, allocate space. We will
354 // actually initialize the global after current function has finished
356 const Type *GlobalType = GV->getType()->getElementType();
357 size_t S = getTargetData()->getABITypeSize(GlobalType);
358 size_t A = getTargetData()->getPrefTypeAlignment(GlobalType);
362 // Allocate S+A bytes of memory, then use an aligned pointer within that
365 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
366 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
368 jitstate.getPendingGlobals(locked).push_back(GV);
370 addGlobalMapping(GV, Ptr);
375 /// recompileAndRelinkFunction - This method is used to force a function
376 /// which has already been compiled, to be compiled again, possibly
377 /// after it has been modified. Then the entry to the old copy is overwritten
378 /// with a branch to the new copy. If there was no old copy, this acts
379 /// just like JIT::getPointerToFunction().
381 void *JIT::recompileAndRelinkFunction(Function *F) {
382 void *OldAddr = getPointerToGlobalIfAvailable(F);
384 // If it's not already compiled there is no reason to patch it up.
385 if (OldAddr == 0) { return getPointerToFunction(F); }
387 // Delete the old function mapping.
388 addGlobalMapping(F, 0);
390 // Recodegen the function
393 // Update state, forward the old function to the new function.
394 void *Addr = getPointerToGlobalIfAvailable(F);
395 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
396 TJI.replaceMachineCodeForFunction(OldAddr, Addr);