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 bytecode 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"
34 #include <AvailabilityMacros.h>
35 #if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
36 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
38 // __dso_handle is resolved by Mac OS X dynamic linker.
39 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
43 static struct RegisterJIT {
44 RegisterJIT() { JIT::Register(); }
52 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
53 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
54 setTargetData(TM.getTargetData());
57 MCE = createEmitter(*this);
60 MutexGuard locked(lock);
61 FunctionPassManager &PM = state.getPM(locked);
62 PM.add(new TargetData(*TM.getTargetData()));
64 // Turn the machine code intermediate representation into bytes in memory that
66 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
67 std::cerr << "Target does not support machine code emission!\n";
72 PM.doInitialization();
80 /// run - Start execution with the specified function and arguments.
82 GenericValue JIT::runFunction(Function *F,
83 const std::vector<GenericValue> &ArgValues) {
84 assert(F && "Function *F was null at entry to run()");
86 void *FPtr = getPointerToFunction(F);
87 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
88 const FunctionType *FTy = F->getFunctionType();
89 const Type *RetTy = FTy->getReturnType();
91 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
92 "Too many arguments passed into function!");
93 assert(FTy->getNumParams() == ArgValues.size() &&
94 "This doesn't support passing arguments through varargs (yet)!");
96 // Handle some common cases first. These cases correspond to common `main'
98 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
99 switch (ArgValues.size()) {
101 if ((FTy->getParamType(0) == Type::IntTy ||
102 FTy->getParamType(0) == Type::UIntTy) &&
103 isa<PointerType>(FTy->getParamType(1)) &&
104 isa<PointerType>(FTy->getParamType(2))) {
105 int (*PF)(int, char **, const char **) =
106 (int(*)(int, char **, const char **))(intptr_t)FPtr;
108 // Call the function.
110 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
111 (const char **)GVTOP(ArgValues[2]));
116 if ((FTy->getParamType(0) == Type::IntTy ||
117 FTy->getParamType(0) == Type::UIntTy) &&
118 isa<PointerType>(FTy->getParamType(1))) {
119 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
121 // Call the function.
123 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
128 if (FTy->getNumParams() == 1 &&
129 (FTy->getParamType(0) == Type::IntTy ||
130 FTy->getParamType(0) == Type::UIntTy)) {
132 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
133 rv.IntVal = PF(ArgValues[0].IntVal);
140 // Handle cases where no arguments are passed first.
141 if (ArgValues.empty()) {
143 switch (RetTy->getTypeID()) {
144 default: assert(0 && "Unknown return type for function call!");
146 rv.BoolVal = ((bool(*)())(intptr_t)FPtr)();
148 case Type::SByteTyID:
149 case Type::UByteTyID:
150 rv.SByteVal = ((char(*)())(intptr_t)FPtr)();
152 case Type::ShortTyID:
153 case Type::UShortTyID:
154 rv.ShortVal = ((short(*)())(intptr_t)FPtr)();
159 rv.IntVal = ((int(*)())(intptr_t)FPtr)();
162 case Type::ULongTyID:
163 rv.LongVal = ((int64_t(*)())(intptr_t)FPtr)();
165 case Type::FloatTyID:
166 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
168 case Type::DoubleTyID:
169 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
171 case Type::PointerTyID:
172 return PTOGV(((void*(*)())(intptr_t)FPtr)());
176 // Okay, this is not one of our quick and easy cases. Because we don't have a
177 // full FFI, we have to codegen a nullary stub function that just calls the
178 // function we are interested in, passing in constants for all of the
179 // arguments. Make this function and return.
181 // First, create the function.
182 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
183 Function *Stub = new Function(STy, Function::InternalLinkage, "",
186 // Insert a basic block.
187 BasicBlock *StubBB = new BasicBlock("", Stub);
189 // Convert all of the GenericValue arguments over to constants. Note that we
190 // currently don't support varargs.
191 std::vector<Value*> Args;
192 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
194 const Type *ArgTy = FTy->getParamType(i);
195 const GenericValue &AV = ArgValues[i];
196 switch (ArgTy->getTypeID()) {
197 default: assert(0 && "Unknown argument type for function call!");
198 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
199 case Type::SByteTyID: C = ConstantInt::get(ArgTy, AV.SByteVal); break;
200 case Type::UByteTyID: C = ConstantInt::get(ArgTy, AV.UByteVal); break;
201 case Type::ShortTyID: C = ConstantInt::get(ArgTy, AV.ShortVal); break;
202 case Type::UShortTyID: C = ConstantInt::get(ArgTy, AV.UShortVal); break;
203 case Type::IntTyID: C = ConstantInt::get(ArgTy, AV.IntVal); break;
204 case Type::UIntTyID: C = ConstantInt::get(ArgTy, AV.UIntVal); break;
205 case Type::LongTyID: C = ConstantInt::get(ArgTy, AV.LongVal); break;
206 case Type::ULongTyID: C = ConstantInt::get(ArgTy, AV.ULongVal); break;
207 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
208 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
209 case Type::PointerTyID:
210 void *ArgPtr = GVTOP(AV);
211 if (sizeof(void*) == 4) {
212 C = ConstantInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
214 C = ConstantInt::get(Type::LongTy, (intptr_t)ArgPtr);
216 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
222 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
223 TheCall->setTailCall();
224 if (TheCall->getType() != Type::VoidTy)
225 new ReturnInst(TheCall, StubBB); // Return result of the call.
227 new ReturnInst(StubBB); // Just return void.
229 // Finally, return the value returned by our nullary stub function.
230 return runFunction(Stub, std::vector<GenericValue>());
233 /// runJITOnFunction - Run the FunctionPassManager full of
234 /// just-in-time compilation passes on F, hopefully filling in
235 /// GlobalAddress[F] with the address of F's machine code.
237 void JIT::runJITOnFunction(Function *F) {
238 static bool isAlreadyCodeGenerating = false;
239 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
241 MutexGuard locked(lock);
244 isAlreadyCodeGenerating = true;
245 state.getPM(locked).run(*F);
246 isAlreadyCodeGenerating = false;
248 // If the function referred to a global variable that had not yet been
249 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
250 // all of these globals now.
251 while (!state.getPendingGlobals(locked).empty()) {
252 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
253 state.getPendingGlobals(locked).pop_back();
254 EmitGlobalVariable(GV);
258 /// getPointerToFunction - This method is used to get the address of the
259 /// specified function, compiling it if neccesary.
261 void *JIT::getPointerToFunction(Function *F) {
262 MutexGuard locked(lock);
264 if (void *Addr = getPointerToGlobalIfAvailable(F))
265 return Addr; // Check if function already code gen'd
267 // Make sure we read in the function if it exists in this Module.
268 if (F->hasNotBeenReadFromBytecode()) {
269 // Determine the module provider this function is provided by.
270 Module *M = F->getParent();
271 ModuleProvider *MP = 0;
272 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
273 if (Modules[i]->getModule() == M) {
278 assert(MP && "Function isn't in a module we know about!");
280 std::string ErrorMsg;
281 if (MP->materializeFunction(F, &ErrorMsg)) {
282 std::cerr << "Error reading function '" << F->getName()
283 << "' from bytecode file: " << ErrorMsg << "\n";
288 if (F->isExternal()) {
289 void *Addr = getPointerToNamedFunction(F->getName());
290 addGlobalMapping(F, Addr);
296 void *Addr = getPointerToGlobalIfAvailable(F);
297 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
301 /// getOrEmitGlobalVariable - Return the address of the specified global
302 /// variable, possibly emitting it to memory if needed. This is used by the
304 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
305 MutexGuard locked(lock);
307 void *Ptr = getPointerToGlobalIfAvailable(GV);
310 // If the global is external, just remember the address.
311 if (GV->isExternal()) {
313 #if (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
314 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
315 __APPLE_CC__ >= 5330)
316 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
317 // of atexit). It passes the address of linker generated symbol __dso_handle
319 // This configuration change happened at version 5330.
320 if (GV->getName() == "__dso_handle")
321 return (void*)&__dso_handle;
324 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
326 std::cerr << "Could not resolve external global address: "
327 << GV->getName() << "\n";
331 // If the global hasn't been emitted to memory yet, allocate space. We will
332 // actually initialize the global after current function has finished
334 const Type *GlobalType = GV->getType()->getElementType();
335 size_t S = getTargetData()->getTypeSize(GlobalType);
336 size_t A = getTargetData()->getTypeAlignment(GlobalType);
340 // Allocate S+A bytes of memory, then use an aligned pointer within that
343 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
344 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
346 state.getPendingGlobals(locked).push_back(GV);
348 addGlobalMapping(GV, Ptr);
353 /// recompileAndRelinkFunction - This method is used to force a function
354 /// which has already been compiled, to be compiled again, possibly
355 /// after it has been modified. Then the entry to the old copy is overwritten
356 /// with a branch to the new copy. If there was no old copy, this acts
357 /// just like JIT::getPointerToFunction().
359 void *JIT::recompileAndRelinkFunction(Function *F) {
360 void *OldAddr = getPointerToGlobalIfAvailable(F);
362 // If it's not already compiled there is no reason to patch it up.
363 if (OldAddr == 0) { return getPointerToFunction(F); }
365 // Delete the old function mapping.
366 addGlobalMapping(F, 0);
368 // Recodegen the function
371 // Update state, forward the old function to the new function.
372 void *Addr = getPointerToGlobalIfAvailable(F);
373 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
374 TJI.replaceMachineCodeForFunction(OldAddr, Addr);