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"
33 static struct RegisterJIT {
34 RegisterJIT() { JIT::Register(); }
42 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
43 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
44 setTargetData(TM.getTargetData());
47 MCE = createEmitter(*this);
50 MutexGuard locked(lock);
51 FunctionPassManager& PM = state.getPM(locked);
52 PM.add(new TargetData(*TM.getTargetData()));
54 // Compile LLVM Code down to machine code in the intermediate representation
55 TJI.addPassesToJITCompile(PM);
57 // Turn the machine code intermediate representation into bytes in memory that
59 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
60 std::cerr << "Target '" << TM.getName()
61 << "' doesn't support machine code emission!\n";
71 /// run - Start execution with the specified function and arguments.
73 GenericValue JIT::runFunction(Function *F,
74 const std::vector<GenericValue> &ArgValues) {
75 assert(F && "Function *F was null at entry to run()");
77 void *FPtr = getPointerToFunction(F);
78 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
79 const FunctionType *FTy = F->getFunctionType();
80 const Type *RetTy = FTy->getReturnType();
82 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
83 "Too many arguments passed into function!");
84 assert(FTy->getNumParams() == ArgValues.size() &&
85 "This doesn't support passing arguments through varargs (yet)!");
87 // Handle some common cases first. These cases correspond to common `main'
89 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
90 switch (ArgValues.size()) {
92 if ((FTy->getParamType(0) == Type::IntTy ||
93 FTy->getParamType(0) == Type::UIntTy) &&
94 isa<PointerType>(FTy->getParamType(1)) &&
95 isa<PointerType>(FTy->getParamType(2))) {
96 int (*PF)(int, char **, const char **) =
97 (int(*)(int, char **, const char **))(intptr_t)FPtr;
101 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
102 (const char **)GVTOP(ArgValues[2]));
107 if ((FTy->getParamType(0) == Type::IntTy ||
108 FTy->getParamType(0) == Type::UIntTy) &&
109 isa<PointerType>(FTy->getParamType(1))) {
110 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
112 // Call the function.
114 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
119 if (FTy->getNumParams() == 1 &&
120 (FTy->getParamType(0) == Type::IntTy ||
121 FTy->getParamType(0) == Type::UIntTy)) {
123 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
124 rv.IntVal = PF(ArgValues[0].IntVal);
131 // Handle cases where no arguments are passed first.
132 if (ArgValues.empty()) {
134 switch (RetTy->getTypeID()) {
135 default: assert(0 && "Unknown return type for function call!");
137 rv.BoolVal = ((bool(*)())(intptr_t)FPtr)();
139 case Type::SByteTyID:
140 case Type::UByteTyID:
141 rv.SByteVal = ((char(*)())(intptr_t)FPtr)();
143 case Type::ShortTyID:
144 case Type::UShortTyID:
145 rv.ShortVal = ((short(*)())(intptr_t)FPtr)();
150 rv.IntVal = ((int(*)())(intptr_t)FPtr)();
153 case Type::ULongTyID:
154 rv.LongVal = ((int64_t(*)())(intptr_t)FPtr)();
156 case Type::FloatTyID:
157 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
159 case Type::DoubleTyID:
160 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
162 case Type::PointerTyID:
163 return PTOGV(((void*(*)())(intptr_t)FPtr)());
167 // Okay, this is not one of our quick and easy cases. Because we don't have a
168 // full FFI, we have to codegen a nullary stub function that just calls the
169 // function we are interested in, passing in constants for all of the
170 // arguments. Make this function and return.
172 // First, create the function.
173 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
174 Function *Stub = new Function(STy, Function::InternalLinkage, "",
177 // Insert a basic block.
178 BasicBlock *StubBB = new BasicBlock("", Stub);
180 // Convert all of the GenericValue arguments over to constants. Note that we
181 // currently don't support varargs.
182 std::vector<Value*> Args;
183 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
185 const Type *ArgTy = FTy->getParamType(i);
186 const GenericValue &AV = ArgValues[i];
187 switch (ArgTy->getTypeID()) {
188 default: assert(0 && "Unknown argument type for function call!");
189 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
190 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
191 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
192 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
193 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
194 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
195 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
196 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
197 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
198 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
199 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
200 case Type::PointerTyID:
201 void *ArgPtr = GVTOP(AV);
202 if (sizeof(void*) == 4) {
203 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
205 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
207 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
213 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
214 TheCall->setTailCall();
215 if (TheCall->getType() != Type::VoidTy)
216 new ReturnInst(TheCall, StubBB); // Return result of the call.
218 new ReturnInst(StubBB); // Just return void.
220 // Finally, return the value returned by our nullary stub function.
221 return runFunction(Stub, std::vector<GenericValue>());
224 /// runJITOnFunction - Run the FunctionPassManager full of
225 /// just-in-time compilation passes on F, hopefully filling in
226 /// GlobalAddress[F] with the address of F's machine code.
228 void JIT::runJITOnFunction(Function *F) {
229 static bool isAlreadyCodeGenerating = false;
230 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
232 MutexGuard locked(lock);
235 isAlreadyCodeGenerating = true;
236 state.getPM(locked).run(*F);
237 isAlreadyCodeGenerating = false;
239 // If the function referred to a global variable that had not yet been
240 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
241 // all of these globals now.
242 while (!state.getPendingGlobals(locked).empty()) {
243 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
244 state.getPendingGlobals(locked).pop_back();
245 EmitGlobalVariable(GV);
249 /// getPointerToFunction - This method is used to get the address of the
250 /// specified function, compiling it if neccesary.
252 void *JIT::getPointerToFunction(Function *F) {
253 MutexGuard locked(lock);
255 if (void *Addr = getPointerToGlobalIfAvailable(F))
256 return Addr; // Check if function already code gen'd
258 // Make sure we read in the function if it exists in this Module
259 if (F->hasNotBeenReadFromBytecode()) {
260 std::string ErrorMsg;
261 if (MP->materializeFunction(F, &ErrorMsg)) {
262 std::cerr << "Error reading function '" << F->getName()
263 << "' from bytecode file: " << ErrorMsg << "\n";
268 if (F->isExternal()) {
269 void *Addr = getPointerToNamedFunction(F->getName());
270 addGlobalMapping(F, Addr);
276 void *Addr = getPointerToGlobalIfAvailable(F);
277 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
281 /// getOrEmitGlobalVariable - Return the address of the specified global
282 /// variable, possibly emitting it to memory if needed. This is used by the
284 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
285 MutexGuard locked(lock);
287 void *Ptr = getPointerToGlobalIfAvailable(GV);
290 // If the global is external, just remember the address.
291 if (GV->isExternal()) {
292 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
294 std::cerr << "Could not resolve external global address: "
295 << GV->getName() << "\n";
299 // If the global hasn't been emitted to memory yet, allocate space. We will
300 // actually initialize the global after current function has finished
302 const Type *GlobalType = GV->getType()->getElementType();
303 size_t S = getTargetData()->getTypeSize(GlobalType);
304 size_t A = getTargetData()->getTypeAlignment(GlobalType);
308 // Allocate S+A bytes of memory, then use an aligned pointer within that
311 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
312 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
314 state.getPendingGlobals(locked).push_back(GV);
316 addGlobalMapping(GV, Ptr);
321 /// recompileAndRelinkFunction - This method is used to force a function
322 /// which has already been compiled, to be compiled again, possibly
323 /// after it has been modified. Then the entry to the old copy is overwritten
324 /// with a branch to the new copy. If there was no old copy, this acts
325 /// just like JIT::getPointerToFunction().
327 void *JIT::recompileAndRelinkFunction(Function *F) {
328 void *OldAddr = getPointerToGlobalIfAvailable(F);
330 // If it's not already compiled there is no reason to patch it up.
331 if (OldAddr == 0) { return getPointerToFunction(F); }
333 // Delete the old function mapping.
334 addGlobalMapping(F, 0);
336 // Recodegen the function
339 // Update state, forward the old function to the new function.
340 void *Addr = getPointerToGlobalIfAvailable(F);
341 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
342 TJI.replaceMachineCodeForFunction(OldAddr, Addr);