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/System/DynamicLibrary.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetJITInfo.h"
31 static struct RegisterJIT {
32 RegisterJIT() { JIT::Register(); }
35 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
36 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
37 setTargetData(TM.getTargetData());
40 MCE = createEmitter(*this);
43 MutexGuard locked(lock);
44 FunctionPassManager& PM = state.getPM(locked);
45 PM.add(new TargetData(TM.getTargetData()));
47 // Compile LLVM Code down to machine code in the intermediate representation
48 TJI.addPassesToJITCompile(PM);
50 // Turn the machine code intermediate representation into bytes in memory that
52 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
53 std::cerr << "Target '" << TM.getName()
54 << "' doesn't support machine code emission!\n";
64 /// run - Start execution with the specified function and arguments.
66 GenericValue JIT::runFunction(Function *F,
67 const std::vector<GenericValue> &ArgValues) {
68 assert(F && "Function *F was null at entry to run()");
70 void *FPtr = getPointerToFunction(F);
71 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
72 const FunctionType *FTy = F->getFunctionType();
73 const Type *RetTy = FTy->getReturnType();
75 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
76 "Too many arguments passed into function!");
77 assert(FTy->getNumParams() == ArgValues.size() &&
78 "This doesn't support passing arguments through varargs (yet)!");
80 // Handle some common cases first. These cases correspond to common `main'
82 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
83 switch (ArgValues.size()) {
85 if ((FTy->getParamType(0) == Type::IntTy ||
86 FTy->getParamType(0) == Type::UIntTy) &&
87 isa<PointerType>(FTy->getParamType(1)) &&
88 isa<PointerType>(FTy->getParamType(2))) {
89 int (*PF)(int, char **, const char **) =
90 (int(*)(int, char **, const char **))FPtr;
94 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
95 (const char **)GVTOP(ArgValues[2]));
100 if ((FTy->getParamType(0) == Type::IntTy ||
101 FTy->getParamType(0) == Type::UIntTy) &&
102 isa<PointerType>(FTy->getParamType(1))) {
103 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
105 // Call the function.
107 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
112 if (FTy->getNumParams() == 1 &&
113 (FTy->getParamType(0) == Type::IntTy ||
114 FTy->getParamType(0) == Type::UIntTy)) {
116 int (*PF)(int) = (int(*)(int))FPtr;
117 rv.IntVal = PF(ArgValues[0].IntVal);
124 // Handle cases where no arguments are passed first.
125 if (ArgValues.empty()) {
127 switch (RetTy->getTypeID()) {
128 default: assert(0 && "Unknown return type for function call!");
130 rv.BoolVal = ((bool(*)())FPtr)();
132 case Type::SByteTyID:
133 case Type::UByteTyID:
134 rv.SByteVal = ((char(*)())FPtr)();
136 case Type::ShortTyID:
137 case Type::UShortTyID:
138 rv.ShortVal = ((short(*)())FPtr)();
143 rv.IntVal = ((int(*)())FPtr)();
146 case Type::ULongTyID:
147 rv.LongVal = ((int64_t(*)())FPtr)();
149 case Type::FloatTyID:
150 rv.FloatVal = ((float(*)())FPtr)();
152 case Type::DoubleTyID:
153 rv.DoubleVal = ((double(*)())FPtr)();
155 case Type::PointerTyID:
156 return PTOGV(((void*(*)())FPtr)());
160 // Okay, this is not one of our quick and easy cases. Because we don't have a
161 // full FFI, we have to codegen a nullary stub function that just calls the
162 // function we are interested in, passing in constants for all of the
163 // arguments. Make this function and return.
165 // First, create the function.
166 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
167 Function *Stub = new Function(STy, Function::InternalLinkage, "",
170 // Insert a basic block.
171 BasicBlock *StubBB = new BasicBlock("", Stub);
173 // Convert all of the GenericValue arguments over to constants. Note that we
174 // currently don't support varargs.
175 std::vector<Value*> Args;
176 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
178 const Type *ArgTy = FTy->getParamType(i);
179 const GenericValue &AV = ArgValues[i];
180 switch (ArgTy->getTypeID()) {
181 default: assert(0 && "Unknown argument type for function call!");
182 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
183 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
184 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
185 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
186 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
187 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
188 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
189 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
190 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
191 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
192 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
193 case Type::PointerTyID:
194 void *ArgPtr = GVTOP(AV);
195 if (sizeof(void*) == 4) {
196 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
198 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
200 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
206 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
207 TheCall->setTailCall();
208 if (TheCall->getType() != Type::VoidTy)
209 new ReturnInst(TheCall, StubBB); // Return result of the call.
211 new ReturnInst(StubBB); // Just return void.
213 // Finally, return the value returned by our nullary stub function.
214 return runFunction(Stub, std::vector<GenericValue>());
217 /// runJITOnFunction - Run the FunctionPassManager full of
218 /// just-in-time compilation passes on F, hopefully filling in
219 /// GlobalAddress[F] with the address of F's machine code.
221 void JIT::runJITOnFunction(Function *F) {
222 static bool isAlreadyCodeGenerating = false;
223 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
225 MutexGuard locked(lock);
228 isAlreadyCodeGenerating = true;
229 state.getPM(locked).run(*F);
230 isAlreadyCodeGenerating = false;
232 // If the function referred to a global variable that had not yet been
233 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
234 // all of these globals now.
235 while (!state.getPendingGlobals(locked).empty()) {
236 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
237 state.getPendingGlobals(locked).pop_back();
238 EmitGlobalVariable(GV);
242 /// getPointerToFunction - This method is used to get the address of the
243 /// specified function, compiling it if neccesary.
245 void *JIT::getPointerToFunction(Function *F) {
246 MutexGuard locked(lock);
248 if (void *Addr = getPointerToGlobalIfAvailable(F))
249 return Addr; // Check if function already code gen'd
251 // Make sure we read in the function if it exists in this Module
252 if (F->hasNotBeenReadFromBytecode())
254 MP->materializeFunction(F);
255 } catch ( std::string& errmsg ) {
256 std::cerr << "Error reading function '" << F->getName()
257 << "' from bytecode file: " << errmsg << "\n";
260 std::cerr << "Error reading function '" << F->getName()
261 << "from bytecode file!\n";
265 if (F->isExternal()) {
266 void *Addr = getPointerToNamedFunction(F->getName());
267 addGlobalMapping(F, Addr);
273 void *Addr = getPointerToGlobalIfAvailable(F);
274 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
278 /// getOrEmitGlobalVariable - Return the address of the specified global
279 /// variable, possibly emitting it to memory if needed. This is used by the
281 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
282 MutexGuard locked(lock);
284 void *Ptr = getPointerToGlobalIfAvailable(GV);
287 // If the global is external, just remember the address.
288 if (GV->isExternal()) {
289 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
291 std::cerr << "Could not resolve external global address: "
292 << GV->getName() << "\n";
296 // If the global hasn't been emitted to memory yet, allocate space. We will
297 // actually initialize the global after current function has finished
299 uint64_t S = getTargetData().getTypeSize(GV->getType()->getElementType());
301 getTargetData().getTypeAlignment(GV->getType()->getElementType());
302 Ptr = MCE->allocateGlobal(S, A);
303 state.getPendingGlobals(locked).push_back(GV);
305 addGlobalMapping(GV, Ptr);
310 /// recompileAndRelinkFunction - This method is used to force a function
311 /// which has already been compiled, to be compiled again, possibly
312 /// after it has been modified. Then the entry to the old copy is overwritten
313 /// with a branch to the new copy. If there was no old copy, this acts
314 /// just like JIT::getPointerToFunction().
316 void *JIT::recompileAndRelinkFunction(Function *F) {
317 void *OldAddr = getPointerToGlobalIfAvailable(F);
319 // If it's not already compiled there is no reason to patch it up.
320 if (OldAddr == 0) { return getPointerToFunction(F); }
322 // Delete the old function mapping.
323 addGlobalMapping(F, 0);
325 // Recodegen the function
328 // Update state, forward the old function to the new function.
329 void *Addr = getPointerToGlobalIfAvailable(F);
330 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
331 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
335 /// freeMachineCodeForFunction - release machine code memory for given Function
337 void JIT::freeMachineCodeForFunction(Function *F) {