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 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
65 : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
66 setTargetData(TM.getTargetData());
69 MCE = createEmitter(*this);
72 MutexGuard locked(lock);
73 FunctionPassManager &PM = jitstate.getPM(locked);
74 PM.add(new TargetData(*TM.getTargetData()));
76 // Turn the machine code intermediate representation into bytes in memory that
78 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
79 cerr << "Target does not support machine code emission!\n";
84 PM.doInitialization();
92 /// run - Start execution with the specified function and arguments.
94 GenericValue JIT::runFunction(Function *F,
95 const std::vector<GenericValue> &ArgValues) {
96 assert(F && "Function *F was null at entry to run()");
98 void *FPtr = getPointerToFunction(F);
99 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
100 const FunctionType *FTy = F->getFunctionType();
101 const Type *RetTy = FTy->getReturnType();
103 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
104 "Too many arguments passed into function!");
105 assert(FTy->getNumParams() == ArgValues.size() &&
106 "This doesn't support passing arguments through varargs (yet)!");
108 // Handle some common cases first. These cases correspond to common `main'
110 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
111 switch (ArgValues.size()) {
113 if (FTy->getParamType(0) == Type::Int32Ty &&
114 isa<PointerType>(FTy->getParamType(1)) &&
115 isa<PointerType>(FTy->getParamType(2))) {
116 int (*PF)(int, char **, const char **) =
117 (int(*)(int, char **, const char **))(intptr_t)FPtr;
119 // Call the function.
121 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
122 (char **)GVTOP(ArgValues[1]),
123 (const char **)GVTOP(ArgValues[2])));
128 if (FTy->getParamType(0) == Type::Int32Ty &&
129 isa<PointerType>(FTy->getParamType(1))) {
130 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
132 // Call the function.
134 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
135 (char **)GVTOP(ArgValues[1])));
140 if (FTy->getNumParams() == 1 &&
141 FTy->getParamType(0) == Type::Int32Ty) {
143 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
144 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
151 // Handle cases where no arguments are passed first.
152 if (ArgValues.empty()) {
154 switch (RetTy->getTypeID()) {
155 default: assert(0 && "Unknown return type for function call!");
156 case Type::IntegerTyID: {
157 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
159 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
160 else if (BitWidth <= 8)
161 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
162 else if (BitWidth <= 16)
163 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
164 else if (BitWidth <= 32)
165 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
166 else if (BitWidth <= 64)
167 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
169 assert(0 && "Integer types > 64 bits not supported");
173 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
175 case Type::FloatTyID:
176 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
178 case Type::DoubleTyID:
179 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
181 case Type::X86_FP80TyID:
182 case Type::FP128TyID:
183 case Type::PPC_FP128TyID:
184 assert(0 && "long double not supported yet");
186 case Type::PointerTyID:
187 return PTOGV(((void*(*)())(intptr_t)FPtr)());
191 // Okay, this is not one of our quick and easy cases. Because we don't have a
192 // full FFI, we have to codegen a nullary stub function that just calls the
193 // function we are interested in, passing in constants for all of the
194 // arguments. Make this function and return.
196 // First, create the function.
197 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
198 Function *Stub = new Function(STy, Function::InternalLinkage, "",
201 // Insert a basic block.
202 BasicBlock *StubBB = new BasicBlock("", Stub);
204 // Convert all of the GenericValue arguments over to constants. Note that we
205 // currently don't support varargs.
206 SmallVector<Value*, 8> Args;
207 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
209 const Type *ArgTy = FTy->getParamType(i);
210 const GenericValue &AV = ArgValues[i];
211 switch (ArgTy->getTypeID()) {
212 default: assert(0 && "Unknown argument type for function call!");
213 case Type::IntegerTyID: C = ConstantInt::get(AV.IntVal); break;
214 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, APFloat(AV.FloatVal));
216 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, APFloat(AV.DoubleVal));
218 case Type::PPC_FP128TyID:
219 case Type::X86_FP80TyID:
220 case Type::FP128TyID: C = ConstantFP ::get(ArgTy, APFloat(AV.IntVal));
222 case Type::PointerTyID:
223 void *ArgPtr = GVTOP(AV);
224 if (sizeof(void*) == 4) {
225 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
227 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
229 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
235 CallInst *TheCall = new CallInst(F, Args.begin(), Args.end(), "", StubBB);
236 TheCall->setTailCall();
237 if (TheCall->getType() != Type::VoidTy)
238 new ReturnInst(TheCall, StubBB); // Return result of the call.
240 new ReturnInst(StubBB); // Just return void.
242 // Finally, return the value returned by our nullary stub function.
243 return runFunction(Stub, std::vector<GenericValue>());
246 /// runJITOnFunction - Run the FunctionPassManager full of
247 /// just-in-time compilation passes on F, hopefully filling in
248 /// GlobalAddress[F] with the address of F's machine code.
250 void JIT::runJITOnFunction(Function *F) {
251 static bool isAlreadyCodeGenerating = false;
253 MutexGuard locked(lock);
254 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
257 isAlreadyCodeGenerating = true;
258 jitstate.getPM(locked).run(*F);
259 isAlreadyCodeGenerating = false;
261 // If the function referred to a global variable that had not yet been
262 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
263 // all of these globals now.
264 while (!jitstate.getPendingGlobals(locked).empty()) {
265 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
266 jitstate.getPendingGlobals(locked).pop_back();
267 EmitGlobalVariable(GV);
271 /// getPointerToFunction - This method is used to get the address of the
272 /// specified function, compiling it if neccesary.
274 void *JIT::getPointerToFunction(Function *F) {
275 MutexGuard locked(lock);
277 if (void *Addr = getPointerToGlobalIfAvailable(F))
278 return Addr; // Check if function already code gen'd
280 // Make sure we read in the function if it exists in this Module.
281 if (F->hasNotBeenReadFromBitcode()) {
282 // Determine the module provider this function is provided by.
283 Module *M = F->getParent();
284 ModuleProvider *MP = 0;
285 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
286 if (Modules[i]->getModule() == M) {
291 assert(MP && "Function isn't in a module we know about!");
293 std::string ErrorMsg;
294 if (MP->materializeFunction(F, &ErrorMsg)) {
295 cerr << "Error reading function '" << F->getName()
296 << "' from bitcode file: " << ErrorMsg << "\n";
301 if (F->isDeclaration()) {
302 void *Addr = getPointerToNamedFunction(F->getName());
303 addGlobalMapping(F, Addr);
309 void *Addr = getPointerToGlobalIfAvailable(F);
310 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
314 /// getOrEmitGlobalVariable - Return the address of the specified global
315 /// variable, possibly emitting it to memory if needed. This is used by the
317 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
318 MutexGuard locked(lock);
320 void *Ptr = getPointerToGlobalIfAvailable(GV);
323 // If the global is external, just remember the address.
324 if (GV->isDeclaration()) {
325 #if HAVE___DSO_HANDLE
326 if (GV->getName() == "__dso_handle")
327 return (void*)&__dso_handle;
329 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
331 cerr << "Could not resolve external global address: "
332 << GV->getName() << "\n";
336 // If the global hasn't been emitted to memory yet, allocate space. We will
337 // actually initialize the global after current function has finished
339 const Type *GlobalType = GV->getType()->getElementType();
340 size_t S = getTargetData()->getTypeSize(GlobalType);
341 size_t A = getTargetData()->getPrefTypeAlignment(GlobalType);
345 // Allocate S+A bytes of memory, then use an aligned pointer within that
348 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
349 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
351 jitstate.getPendingGlobals(locked).push_back(GV);
353 addGlobalMapping(GV, Ptr);
358 /// recompileAndRelinkFunction - This method is used to force a function
359 /// which has already been compiled, to be compiled again, possibly
360 /// after it has been modified. Then the entry to the old copy is overwritten
361 /// with a branch to the new copy. If there was no old copy, this acts
362 /// just like JIT::getPointerToFunction().
364 void *JIT::recompileAndRelinkFunction(Function *F) {
365 void *OldAddr = getPointerToGlobalIfAvailable(F);
367 // If it's not already compiled there is no reason to patch it up.
368 if (OldAddr == 0) { return getPointerToFunction(F); }
370 // Delete the old function mapping.
371 addGlobalMapping(F, 0);
373 // Recodegen the function
376 // Update state, forward the old function to the new function.
377 void *Addr = getPointerToGlobalIfAvailable(F);
378 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
379 TJI.replaceMachineCodeForFunction(OldAddr, Addr);