1 //===-- JIT.cpp - LLVM 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 //===----------------------------------------------------------------------===//
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 #if defined (__GNUC__)
65 extern "C" void __register_frame(void*);
68 /// createJIT - This is the factory method for creating a JIT for the current
69 /// machine, it does not fall back to the interpreter. This takes ownership
70 /// of the module provider.
71 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
72 std::string *ErrorStr,
73 JITMemoryManager *JMM) {
74 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
77 // Register routine for informing unwinding runtime about new EH frames
79 EE->InstallExceptionTableRegister(__register_frame);
82 // Make sure we can resolve symbols in the program as well. The zero arg
83 // to the function tells DynamicLibrary to load the program, not a library.
84 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
88 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
89 JITMemoryManager *JMM)
90 : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
91 setTargetData(TM.getTargetData());
94 MCE = createEmitter(*this, JMM);
97 MutexGuard locked(lock);
98 FunctionPassManager &PM = jitstate.getPM(locked);
99 PM.add(new TargetData(*TM.getTargetData()));
101 // Turn the machine code intermediate representation into bytes in memory that
103 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
104 cerr << "Target does not support machine code emission!\n";
108 // Initialize passes.
109 PM.doInitialization();
117 /// run - Start execution with the specified function and arguments.
119 GenericValue JIT::runFunction(Function *F,
120 const std::vector<GenericValue> &ArgValues) {
121 assert(F && "Function *F was null at entry to run()");
123 void *FPtr = getPointerToFunction(F);
124 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
125 const FunctionType *FTy = F->getFunctionType();
126 const Type *RetTy = FTy->getReturnType();
128 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
129 "Too many arguments passed into function!");
130 assert(FTy->getNumParams() == ArgValues.size() &&
131 "This doesn't support passing arguments through varargs (yet)!");
133 // Handle some common cases first. These cases correspond to common `main'
135 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
136 switch (ArgValues.size()) {
138 if (FTy->getParamType(0) == Type::Int32Ty &&
139 isa<PointerType>(FTy->getParamType(1)) &&
140 isa<PointerType>(FTy->getParamType(2))) {
141 int (*PF)(int, char **, const char **) =
142 (int(*)(int, char **, const char **))(intptr_t)FPtr;
144 // Call the function.
146 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
147 (char **)GVTOP(ArgValues[1]),
148 (const char **)GVTOP(ArgValues[2])));
153 if (FTy->getParamType(0) == Type::Int32Ty &&
154 isa<PointerType>(FTy->getParamType(1))) {
155 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
157 // Call the function.
159 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
160 (char **)GVTOP(ArgValues[1])));
165 if (FTy->getNumParams() == 1 &&
166 FTy->getParamType(0) == Type::Int32Ty) {
168 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
169 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
176 // Handle cases where no arguments are passed first.
177 if (ArgValues.empty()) {
179 switch (RetTy->getTypeID()) {
180 default: assert(0 && "Unknown return type for function call!");
181 case Type::IntegerTyID: {
182 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
184 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
185 else if (BitWidth <= 8)
186 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
187 else if (BitWidth <= 16)
188 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
189 else if (BitWidth <= 32)
190 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
191 else if (BitWidth <= 64)
192 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
194 assert(0 && "Integer types > 64 bits not supported");
198 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
200 case Type::FloatTyID:
201 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
203 case Type::DoubleTyID:
204 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
206 case Type::X86_FP80TyID:
207 case Type::FP128TyID:
208 case Type::PPC_FP128TyID:
209 assert(0 && "long double not supported yet");
211 case Type::PointerTyID:
212 return PTOGV(((void*(*)())(intptr_t)FPtr)());
216 // Okay, this is not one of our quick and easy cases. Because we don't have a
217 // full FFI, we have to codegen a nullary stub function that just calls the
218 // function we are interested in, passing in constants for all of the
219 // arguments. Make this function and return.
221 // First, create the function.
222 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
223 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
226 // Insert a basic block.
227 BasicBlock *StubBB = BasicBlock::Create("", Stub);
229 // Convert all of the GenericValue arguments over to constants. Note that we
230 // currently don't support varargs.
231 SmallVector<Value*, 8> Args;
232 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
234 const Type *ArgTy = FTy->getParamType(i);
235 const GenericValue &AV = ArgValues[i];
236 switch (ArgTy->getTypeID()) {
237 default: assert(0 && "Unknown argument type for function call!");
238 case Type::IntegerTyID: C = ConstantInt::get(AV.IntVal); break;
239 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, APFloat(AV.FloatVal));
241 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, APFloat(AV.DoubleVal));
243 case Type::PPC_FP128TyID:
244 case Type::X86_FP80TyID:
245 case Type::FP128TyID: C = ConstantFP ::get(ArgTy, APFloat(AV.IntVal));
247 case Type::PointerTyID:
248 void *ArgPtr = GVTOP(AV);
249 if (sizeof(void*) == 4) {
250 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
252 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
254 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
260 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(), "", StubBB);
261 TheCall->setTailCall();
262 if (TheCall->getType() != Type::VoidTy)
263 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
265 ReturnInst::Create(StubBB); // Just return void.
267 // Finally, return the value returned by our nullary stub function.
268 return runFunction(Stub, std::vector<GenericValue>());
271 /// runJITOnFunction - Run the FunctionPassManager full of
272 /// just-in-time compilation passes on F, hopefully filling in
273 /// GlobalAddress[F] with the address of F's machine code.
275 void JIT::runJITOnFunction(Function *F) {
276 static bool isAlreadyCodeGenerating = false;
278 MutexGuard locked(lock);
279 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
282 isAlreadyCodeGenerating = true;
283 jitstate.getPM(locked).run(*F);
284 isAlreadyCodeGenerating = false;
286 // If the function referred to a global variable that had not yet been
287 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
288 // all of these globals now.
289 while (!jitstate.getPendingGlobals(locked).empty()) {
290 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
291 jitstate.getPendingGlobals(locked).pop_back();
292 EmitGlobalVariable(GV);
296 /// getPointerToFunction - This method is used to get the address of the
297 /// specified function, compiling it if neccesary.
299 void *JIT::getPointerToFunction(Function *F) {
300 MutexGuard locked(lock);
302 if (void *Addr = getPointerToGlobalIfAvailable(F))
303 return Addr; // Check if function already code gen'd
305 // Make sure we read in the function if it exists in this Module.
306 if (F->hasNotBeenReadFromBitcode()) {
307 // Determine the module provider this function is provided by.
308 Module *M = F->getParent();
309 ModuleProvider *MP = 0;
310 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
311 if (Modules[i]->getModule() == M) {
316 assert(MP && "Function isn't in a module we know about!");
318 std::string ErrorMsg;
319 if (MP->materializeFunction(F, &ErrorMsg)) {
320 cerr << "Error reading function '" << F->getName()
321 << "' from bitcode file: " << ErrorMsg << "\n";
326 if (F->isDeclaration()) {
327 void *Addr = getPointerToNamedFunction(F->getName());
328 addGlobalMapping(F, Addr);
334 void *Addr = getPointerToGlobalIfAvailable(F);
335 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
339 /// getOrEmitGlobalVariable - Return the address of the specified global
340 /// variable, possibly emitting it to memory if needed. This is used by the
342 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
343 MutexGuard locked(lock);
345 void *Ptr = getPointerToGlobalIfAvailable(GV);
348 // If the global is external, just remember the address.
349 if (GV->isDeclaration()) {
350 #if HAVE___DSO_HANDLE
351 if (GV->getName() == "__dso_handle")
352 return (void*)&__dso_handle;
354 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
356 cerr << "Could not resolve external global address: "
357 << GV->getName() << "\n";
361 // If the global hasn't been emitted to memory yet, allocate space. We will
362 // actually initialize the global after current function has finished
364 const Type *GlobalType = GV->getType()->getElementType();
365 size_t S = getTargetData()->getABITypeSize(GlobalType);
366 size_t A = getTargetData()->getPreferredAlignment(GV);
370 // Allocate S+A bytes of memory, then use an aligned pointer within that
373 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
374 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
376 jitstate.getPendingGlobals(locked).push_back(GV);
378 addGlobalMapping(GV, Ptr);
383 /// recompileAndRelinkFunction - This method is used to force a function
384 /// which has already been compiled, to be compiled again, possibly
385 /// after it has been modified. Then the entry to the old copy is overwritten
386 /// with a branch to the new copy. If there was no old copy, this acts
387 /// just like JIT::getPointerToFunction().
389 void *JIT::recompileAndRelinkFunction(Function *F) {
390 void *OldAddr = getPointerToGlobalIfAvailable(F);
392 // If it's not already compiled there is no reason to patch it up.
393 if (OldAddr == 0) { return getPointerToFunction(F); }
395 // Delete the old function mapping.
396 addGlobalMapping(F, 0);
398 // Recodegen the function
401 // Update state, forward the old function to the new function.
402 void *Addr = getPointerToGlobalIfAvailable(F);
403 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
404 TJI.replaceMachineCodeForFunction(OldAddr, Addr);