blob: 66e0468f189a9a1a4e4ef68f6687251bf5a93fd0 [file] [log] [blame]
Chris Lattner4d326fa2003-12-20 01:46:27 +00001//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
Misha Brukmanf976c852005-04-21 22:55:34 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
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.
Misha Brukmanf976c852005-04-21 22:55:34 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
Chris Lattner4d326fa2003-12-20 01:46:27 +000010// This tool implements a just-in-time compiler for LLVM, allowing direct
11// execution of LLVM bytecode in an efficient manner.
Chris Lattnerbd199fb2002-12-24 00:01:05 +000012//
13//===----------------------------------------------------------------------===//
14
Chris Lattner4d326fa2003-12-20 01:46:27 +000015#include "JIT.h"
Chris Lattnercc22e9f2004-08-16 00:14:18 +000016#include "llvm/Constants.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000017#include "llvm/DerivedTypes.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000018#include "llvm/Function.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000019#include "llvm/GlobalVariable.h"
Chris Lattnercc22e9f2004-08-16 00:14:18 +000020#include "llvm/Instructions.h"
Misha Brukman0f4f7d92003-10-16 21:19:34 +000021#include "llvm/ModuleProvider.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000022#include "llvm/CodeGen/MachineCodeEmitter.h"
23#include "llvm/CodeGen/MachineFunction.h"
Brian Gaeke97222942003-09-05 19:39:22 +000024#include "llvm/ExecutionEngine/GenericValue.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000026#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000027#include "llvm/Target/TargetJITInfo.h"
Reid Spencer954da372004-07-04 12:19:56 +000028#include <iostream>
Chris Lattnerc19aade2003-12-08 08:06:28 +000029using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000030
Chris Lattner2fe4bb02006-03-22 06:07:50 +000031static struct RegisterJIT {
32 RegisterJIT() { JIT::Register(); }
33} JITRegistrator;
34
Chris Lattner4d326fa2003-12-20 01:46:27 +000035JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
Reid Spenceree448632005-07-12 15:51:55 +000036 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000037 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000038
39 // Initialize MCE
Misha Brukman906f5fa2003-06-02 03:23:16 +000040 MCE = createEmitter(*this);
Misha Brukmanf976c852005-04-21 22:55:34 +000041
Brian Gaeke50872d52004-04-14 17:45:52 +000042 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +000043 MutexGuard locked(lock);
44 FunctionPassManager& PM = state.getPM(locked);
Chris Lattnercc22e9f2004-08-16 00:14:18 +000045 PM.add(new TargetData(TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +000046
Chris Lattner4d326fa2003-12-20 01:46:27 +000047 // Compile LLVM Code down to machine code in the intermediate representation
48 TJI.addPassesToJITCompile(PM);
49
50 // Turn the machine code intermediate representation into bytes in memory that
51 // may be executed.
52 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
Chris Lattnercc22e9f2004-08-16 00:14:18 +000053 std::cerr << "Target '" << TM.getName()
Chris Lattner4d326fa2003-12-20 01:46:27 +000054 << "' doesn't support machine code emission!\n";
55 abort();
56 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000057}
58
Chris Lattner4d326fa2003-12-20 01:46:27 +000059JIT::~JIT() {
60 delete MCE;
61 delete &TM;
62}
63
Brian Gaeke70975ee2003-09-05 18:42:01 +000064/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000065///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000066GenericValue JIT::runFunction(Function *F,
67 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000068 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000069
70 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000071 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000072 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000073 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000074
Chris Lattnere5eab142004-08-15 23:53:06 +000075 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)!");
79
Misha Brukmanec843022004-10-22 23:35:57 +000080 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +000081 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000082 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000083 switch (ArgValues.size()) {
84 case 3:
Misha Brukmanf976c852005-04-21 22:55:34 +000085 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +000086 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;
Misha Brukmanec843022004-10-22 23:35:57 +000091
Chris Lattnerf7bedf42004-08-15 23:39:59 +000092 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000093 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000094 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
95 (const char **)GVTOP(ArgValues[2]));
96 return rv;
97 }
98 break;
Chris Lattner174f2262004-08-16 01:07:04 +000099 case 2:
Misha Brukmanf976c852005-04-21 22:55:34 +0000100 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattner174f2262004-08-16 01:07:04 +0000101 FTy->getParamType(0) == Type::UIntTy) &&
102 isa<PointerType>(FTy->getParamType(1))) {
103 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000104
Chris Lattner174f2262004-08-16 01:07:04 +0000105 // Call the function.
106 GenericValue rv;
107 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
108 return rv;
109 }
110 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000111 case 1:
112 if (FTy->getNumParams() == 1 &&
Misha Brukmanf976c852005-04-21 22:55:34 +0000113 (FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000114 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000115 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000116 int (*PF)(int) = (int(*)(int))FPtr;
117 rv.IntVal = PF(ArgValues[0].IntVal);
118 return rv;
119 }
120 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000121 }
122 }
123
124 // Handle cases where no arguments are passed first.
125 if (ArgValues.empty()) {
126 GenericValue rv;
127 switch (RetTy->getTypeID()) {
128 default: assert(0 && "Unknown return type for function call!");
129 case Type::BoolTyID:
130 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000131 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000132 case Type::SByteTyID:
133 case Type::UByteTyID:
134 rv.SByteVal = ((char(*)())FPtr)();
135 return rv;
136 case Type::ShortTyID:
137 case Type::UShortTyID:
138 rv.ShortVal = ((short(*)())FPtr)();
139 return rv;
140 case Type::VoidTyID:
141 case Type::IntTyID:
142 case Type::UIntTyID:
143 rv.IntVal = ((int(*)())FPtr)();
144 return rv;
145 case Type::LongTyID:
146 case Type::ULongTyID:
147 rv.LongVal = ((int64_t(*)())FPtr)();
148 return rv;
149 case Type::FloatTyID:
150 rv.FloatVal = ((float(*)())FPtr)();
151 return rv;
152 case Type::DoubleTyID:
153 rv.DoubleVal = ((double(*)())FPtr)();
154 return rv;
155 case Type::PointerTyID:
156 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000157 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000158 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000159
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000160 // 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.
164
165 // First, create the function.
166 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
167 Function *Stub = new Function(STy, Function::InternalLinkage, "",
168 F->getParent());
169
170 // Insert a basic block.
171 BasicBlock *StubBB = new BasicBlock("", Stub);
172
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) {
177 Constant *C = 0;
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);
197 } else {
198 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
199 }
200 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
201 break;
202 }
203 Args.push_back(C);
204 }
205
Chris Lattnera471e042005-05-06 06:48:54 +0000206 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
207 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000208 if (TheCall->getType() != Type::VoidTy)
209 new ReturnInst(TheCall, StubBB); // Return result of the call.
210 else
211 new ReturnInst(StubBB); // Just return void.
212
213 // Finally, return the value returned by our nullary stub function.
214 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000215}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000216
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.
220///
221void JIT::runJITOnFunction(Function *F) {
222 static bool isAlreadyCodeGenerating = false;
223 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Jeff Cohen00b168892005-07-27 06:12:32 +0000224
Reid Spenceree448632005-07-12 15:51:55 +0000225 MutexGuard locked(lock);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000226
227 // JIT the function
228 isAlreadyCodeGenerating = true;
Reid Spenceree448632005-07-12 15:51:55 +0000229 state.getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000230 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000231
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.
Reid Spenceree448632005-07-12 15:51:55 +0000235 while (!state.getPendingGlobals(locked).empty()) {
236 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
237 state.getPendingGlobals(locked).pop_back();
Chris Lattnerc07ed132003-12-20 03:36:47 +0000238 EmitGlobalVariable(GV);
239 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000240}
241
242/// getPointerToFunction - This method is used to get the address of the
243/// specified function, compiling it if neccesary.
244///
245void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000246 MutexGuard locked(lock);
247
Chris Lattnerc07ed132003-12-20 03:36:47 +0000248 if (void *Addr = getPointerToGlobalIfAvailable(F))
249 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000250
251 // Make sure we read in the function if it exists in this Module
Misha Brukmanf976c852005-04-21 22:55:34 +0000252 if (F->hasNotBeenReadFromBytecode())
Chris Lattner0050ef82004-11-15 23:18:09 +0000253 try {
254 MP->materializeFunction(F);
255 } catch ( std::string& errmsg ) {
256 std::cerr << "Error reading function '" << F->getName()
257 << "' from bytecode file: " << errmsg << "\n";
258 abort();
259 } catch (...) {
260 std::cerr << "Error reading function '" << F->getName()
261 << "from bytecode file!\n";
262 abort();
263 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000264
Chris Lattnerc07ed132003-12-20 03:36:47 +0000265 if (F->isExternal()) {
266 void *Addr = getPointerToNamedFunction(F->getName());
267 addGlobalMapping(F, Addr);
268 return Addr;
269 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000270
271 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000272
273 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000274 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
275 return Addr;
276}
277
Chris Lattnerc07ed132003-12-20 03:36:47 +0000278/// getOrEmitGlobalVariable - Return the address of the specified global
279/// variable, possibly emitting it to memory if needed. This is used by the
280/// Emitter.
281void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000282 MutexGuard locked(lock);
283
Chris Lattnerc07ed132003-12-20 03:36:47 +0000284 void *Ptr = getPointerToGlobalIfAvailable(GV);
285 if (Ptr) return Ptr;
286
287 // If the global is external, just remember the address.
288 if (GV->isExternal()) {
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000289 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000290 if (Ptr == 0) {
291 std::cerr << "Could not resolve external global address: "
292 << GV->getName() << "\n";
293 abort();
294 }
295 } else {
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
298 // compilation.
Chris Lattnera8101c12005-01-08 20:07:03 +0000299 uint64_t S = getTargetData().getTypeSize(GV->getType()->getElementType());
Chris Lattner51e6a382006-01-07 06:12:07 +0000300 unsigned char A =
301 getTargetData().getTypeAlignment(GV->getType()->getElementType());
Andrew Lenharth6a974612005-07-28 12:44:13 +0000302 Ptr = MCE->allocateGlobal(S, A);
Reid Spenceree448632005-07-12 15:51:55 +0000303 state.getPendingGlobals(locked).push_back(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000304 }
305 addGlobalMapping(GV, Ptr);
306 return Ptr;
307}
308
309
Chris Lattner4d326fa2003-12-20 01:46:27 +0000310/// 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().
315///
316void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000317 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000318
Chris Lattnerc07ed132003-12-20 03:36:47 +0000319 // If it's not already compiled there is no reason to patch it up.
320 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000321
Chris Lattnerc07ed132003-12-20 03:36:47 +0000322 // Delete the old function mapping.
323 addGlobalMapping(F, 0);
324
Chris Lattnerc07ed132003-12-20 03:36:47 +0000325 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000326 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000327
328 // Update state, forward the old function to the new function.
329 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000330 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
331 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
332 return Addr;
333}
Misha Brukman895eddf2004-11-07 23:58:46 +0000334
335/// freeMachineCodeForFunction - release machine code memory for given Function
336///
337void JIT::freeMachineCodeForFunction(Function *F) {
338 // currently a no-op
339}