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(); }
40 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
41 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
42 setTargetData(TM.getTargetData());
45 MCE = createEmitter(*this);
48 MutexGuard locked(lock);
49 FunctionPassManager& PM = state.getPM(locked);
50 PM.add(new TargetData(*TM.getTargetData()));
52 // Compile LLVM Code down to machine code in the intermediate representation
53 TJI.addPassesToJITCompile(PM);
55 // Turn the machine code intermediate representation into bytes in memory that
57 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
58 std::cerr << "Target '" << TM.getName()
59 << "' doesn't support machine code emission!\n";
69 /// run - Start execution with the specified function and arguments.
71 GenericValue JIT::runFunction(Function *F,
72 const std::vector<GenericValue> &ArgValues) {
73 assert(F && "Function *F was null at entry to run()");
75 void *FPtr = getPointerToFunction(F);
76 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
77 const FunctionType *FTy = F->getFunctionType();
78 const Type *RetTy = FTy->getReturnType();
80 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
81 "Too many arguments passed into function!");
82 assert(FTy->getNumParams() == ArgValues.size() &&
83 "This doesn't support passing arguments through varargs (yet)!");
85 // Handle some common cases first. These cases correspond to common `main'
87 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
88 switch (ArgValues.size()) {
90 if ((FTy->getParamType(0) == Type::IntTy ||
91 FTy->getParamType(0) == Type::UIntTy) &&
92 isa<PointerType>(FTy->getParamType(1)) &&
93 isa<PointerType>(FTy->getParamType(2))) {
94 int (*PF)(int, char **, const char **) =
95 (int(*)(int, char **, const char **))FPtr;
99 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
100 (const char **)GVTOP(ArgValues[2]));
105 if ((FTy->getParamType(0) == Type::IntTy ||
106 FTy->getParamType(0) == Type::UIntTy) &&
107 isa<PointerType>(FTy->getParamType(1))) {
108 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
110 // Call the function.
112 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
117 if (FTy->getNumParams() == 1 &&
118 (FTy->getParamType(0) == Type::IntTy ||
119 FTy->getParamType(0) == Type::UIntTy)) {
121 int (*PF)(int) = (int(*)(int))FPtr;
122 rv.IntVal = PF(ArgValues[0].IntVal);
129 // Handle cases where no arguments are passed first.
130 if (ArgValues.empty()) {
132 switch (RetTy->getTypeID()) {
133 default: assert(0 && "Unknown return type for function call!");
135 rv.BoolVal = ((bool(*)())FPtr)();
137 case Type::SByteTyID:
138 case Type::UByteTyID:
139 rv.SByteVal = ((char(*)())FPtr)();
141 case Type::ShortTyID:
142 case Type::UShortTyID:
143 rv.ShortVal = ((short(*)())FPtr)();
148 rv.IntVal = ((int(*)())FPtr)();
151 case Type::ULongTyID:
152 rv.LongVal = ((int64_t(*)())FPtr)();
154 case Type::FloatTyID:
155 rv.FloatVal = ((float(*)())FPtr)();
157 case Type::DoubleTyID:
158 rv.DoubleVal = ((double(*)())FPtr)();
160 case Type::PointerTyID:
161 return PTOGV(((void*(*)())FPtr)());
165 // Okay, this is not one of our quick and easy cases. Because we don't have a
166 // full FFI, we have to codegen a nullary stub function that just calls the
167 // function we are interested in, passing in constants for all of the
168 // arguments. Make this function and return.
170 // First, create the function.
171 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
172 Function *Stub = new Function(STy, Function::InternalLinkage, "",
175 // Insert a basic block.
176 BasicBlock *StubBB = new BasicBlock("", Stub);
178 // Convert all of the GenericValue arguments over to constants. Note that we
179 // currently don't support varargs.
180 std::vector<Value*> Args;
181 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
183 const Type *ArgTy = FTy->getParamType(i);
184 const GenericValue &AV = ArgValues[i];
185 switch (ArgTy->getTypeID()) {
186 default: assert(0 && "Unknown argument type for function call!");
187 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
188 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
189 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
190 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
191 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
192 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
193 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
194 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
195 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
196 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
197 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
198 case Type::PointerTyID:
199 void *ArgPtr = GVTOP(AV);
200 if (sizeof(void*) == 4) {
201 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
203 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
205 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
211 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
212 TheCall->setTailCall();
213 if (TheCall->getType() != Type::VoidTy)
214 new ReturnInst(TheCall, StubBB); // Return result of the call.
216 new ReturnInst(StubBB); // Just return void.
218 // Finally, return the value returned by our nullary stub function.
219 return runFunction(Stub, std::vector<GenericValue>());
222 /// runJITOnFunction - Run the FunctionPassManager full of
223 /// just-in-time compilation passes on F, hopefully filling in
224 /// GlobalAddress[F] with the address of F's machine code.
226 void JIT::runJITOnFunction(Function *F) {
227 static bool isAlreadyCodeGenerating = false;
228 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
230 MutexGuard locked(lock);
233 isAlreadyCodeGenerating = true;
234 state.getPM(locked).run(*F);
235 isAlreadyCodeGenerating = false;
237 // If the function referred to a global variable that had not yet been
238 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
239 // all of these globals now.
240 while (!state.getPendingGlobals(locked).empty()) {
241 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
242 state.getPendingGlobals(locked).pop_back();
243 EmitGlobalVariable(GV);
247 /// getPointerToFunction - This method is used to get the address of the
248 /// specified function, compiling it if neccesary.
250 void *JIT::getPointerToFunction(Function *F) {
251 MutexGuard locked(lock);
253 if (void *Addr = getPointerToGlobalIfAvailable(F))
254 return Addr; // Check if function already code gen'd
256 // Make sure we read in the function if it exists in this Module
257 if (F->hasNotBeenReadFromBytecode())
259 MP->materializeFunction(F);
260 } catch ( std::string& errmsg ) {
261 std::cerr << "Error reading function '" << F->getName()
262 << "' from bytecode file: " << errmsg << "\n";
265 std::cerr << "Error reading function '" << F->getName()
266 << "from bytecode file!\n";
270 if (F->isExternal()) {
271 void *Addr = getPointerToNamedFunction(F->getName());
272 addGlobalMapping(F, Addr);
278 void *Addr = getPointerToGlobalIfAvailable(F);
279 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
283 /// getOrEmitGlobalVariable - Return the address of the specified global
284 /// variable, possibly emitting it to memory if needed. This is used by the
286 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
287 MutexGuard locked(lock);
289 void *Ptr = getPointerToGlobalIfAvailable(GV);
292 // If the global is external, just remember the address.
293 if (GV->isExternal()) {
294 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
296 std::cerr << "Could not resolve external global address: "
297 << GV->getName() << "\n";
301 // If the global hasn't been emitted to memory yet, allocate space. We will
302 // actually initialize the global after current function has finished
304 const Type *GlobalType = GV->getType()->getElementType();
305 size_t S = getTargetData()->getTypeSize(GlobalType);
306 size_t A = getTargetData()->getTypeAlignment(GlobalType);
310 // Allocate S+A bytes of memory, then use an aligned pointer within that
313 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
314 unsigned Offset = MisAligned ? (A-MisAligned) : 0;
316 // Trim the tail off the memory block.
317 realloc(Ptr, S+Offset);
318 Ptr = (char*)Ptr + Offset;
320 state.getPendingGlobals(locked).push_back(GV);
322 addGlobalMapping(GV, Ptr);
327 /// recompileAndRelinkFunction - This method is used to force a function
328 /// which has already been compiled, to be compiled again, possibly
329 /// after it has been modified. Then the entry to the old copy is overwritten
330 /// with a branch to the new copy. If there was no old copy, this acts
331 /// just like JIT::getPointerToFunction().
333 void *JIT::recompileAndRelinkFunction(Function *F) {
334 void *OldAddr = getPointerToGlobalIfAvailable(F);
336 // If it's not already compiled there is no reason to patch it up.
337 if (OldAddr == 0) { return getPointerToFunction(F); }
339 // Delete the old function mapping.
340 addGlobalMapping(F, 0);
342 // Recodegen the function
345 // Update state, forward the old function to the new function.
346 void *Addr = getPointerToGlobalIfAvailable(F);
347 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
348 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
352 /// freeMachineCodeForFunction - release machine code memory for given Function
354 void JIT::freeMachineCodeForFunction(Function *F) {