blob: d185e00d87c0674390bb76f084e7141e98f8ef79 [file] [log] [blame]
Chris Lattner4d326fa2003-12-20 01:46:27 +00001//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000025#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000026#include "llvm/Target/TargetJITInfo.h"
Chris Lattnerc07ed132003-12-20 03:36:47 +000027#include "Support/DynamicLinker.h"
Reid Spencer954da372004-07-04 12:19:56 +000028#include <iostream>
29
Chris Lattnerc19aade2003-12-08 08:06:28 +000030using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000031
Chris Lattner4d326fa2003-12-20 01:46:27 +000032JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
Chris Lattner1e60a912003-12-20 01:22:19 +000033 : ExecutionEngine(MP), TM(tm), TJI(tji), PM(MP) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000034 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000035
36 // Initialize MCE
Misha Brukman906f5fa2003-06-02 03:23:16 +000037 MCE = createEmitter(*this);
Chris Lattner1e60a912003-12-20 01:22:19 +000038
Brian Gaeke50872d52004-04-14 17:45:52 +000039 // Add target data
Chris Lattnercc22e9f2004-08-16 00:14:18 +000040 PM.add(new TargetData(TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +000041
Chris Lattner4d326fa2003-12-20 01:46:27 +000042 // Compile LLVM Code down to machine code in the intermediate representation
43 TJI.addPassesToJITCompile(PM);
44
45 // Turn the machine code intermediate representation into bytes in memory that
46 // may be executed.
47 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
Chris Lattnercc22e9f2004-08-16 00:14:18 +000048 std::cerr << "Target '" << TM.getName()
Chris Lattner4d326fa2003-12-20 01:46:27 +000049 << "' doesn't support machine code emission!\n";
50 abort();
51 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000052}
53
Chris Lattner4d326fa2003-12-20 01:46:27 +000054JIT::~JIT() {
55 delete MCE;
56 delete &TM;
57}
58
Brian Gaeke70975ee2003-09-05 18:42:01 +000059/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000060///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000061GenericValue JIT::runFunction(Function *F,
62 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000063 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000064
65 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000066 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000067 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000068 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000069
Chris Lattnere5eab142004-08-15 23:53:06 +000070 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
71 "Too many arguments passed into function!");
72 assert(FTy->getNumParams() == ArgValues.size() &&
73 "This doesn't support passing arguments through varargs (yet)!");
74
75 // Handle some common cases first. These cases correspond to common 'main'
76 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000077 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000078 switch (ArgValues.size()) {
79 case 3:
80 if (FTy->getNumParams() == 3 &&
81 (FTy->getParamType(0) == Type::IntTy ||
82 FTy->getParamType(0) == Type::UIntTy) &&
83 isa<PointerType>(FTy->getParamType(1)) &&
84 isa<PointerType>(FTy->getParamType(2))) {
85 int (*PF)(int, char **, const char **) =
86 (int(*)(int, char **, const char **))FPtr;
87
88 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000089 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000090 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
91 (const char **)GVTOP(ArgValues[2]));
92 return rv;
93 }
94 break;
95 case 1:
96 if (FTy->getNumParams() == 1 &&
97 (FTy->getParamType(0) == Type::IntTy ||
98 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +000099 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000100 int (*PF)(int) = (int(*)(int))FPtr;
101 rv.IntVal = PF(ArgValues[0].IntVal);
102 return rv;
103 }
104 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000105 }
106 }
107
108 // Handle cases where no arguments are passed first.
109 if (ArgValues.empty()) {
110 GenericValue rv;
111 switch (RetTy->getTypeID()) {
112 default: assert(0 && "Unknown return type for function call!");
113 case Type::BoolTyID:
114 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000115 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000116 case Type::SByteTyID:
117 case Type::UByteTyID:
118 rv.SByteVal = ((char(*)())FPtr)();
119 return rv;
120 case Type::ShortTyID:
121 case Type::UShortTyID:
122 rv.ShortVal = ((short(*)())FPtr)();
123 return rv;
124 case Type::VoidTyID:
125 case Type::IntTyID:
126 case Type::UIntTyID:
127 rv.IntVal = ((int(*)())FPtr)();
128 return rv;
129 case Type::LongTyID:
130 case Type::ULongTyID:
131 rv.LongVal = ((int64_t(*)())FPtr)();
132 return rv;
133 case Type::FloatTyID:
134 rv.FloatVal = ((float(*)())FPtr)();
135 return rv;
136 case Type::DoubleTyID:
137 rv.DoubleVal = ((double(*)())FPtr)();
138 return rv;
139 case Type::PointerTyID:
140 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000141 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000142 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000143
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000144 // Okay, this is not one of our quick and easy cases. Because we don't have a
145 // full FFI, we have to codegen a nullary stub function that just calls the
146 // function we are interested in, passing in constants for all of the
147 // arguments. Make this function and return.
148
149 // First, create the function.
150 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
151 Function *Stub = new Function(STy, Function::InternalLinkage, "",
152 F->getParent());
153
154 // Insert a basic block.
155 BasicBlock *StubBB = new BasicBlock("", Stub);
156
157 // Convert all of the GenericValue arguments over to constants. Note that we
158 // currently don't support varargs.
159 std::vector<Value*> Args;
160 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
161 Constant *C = 0;
162 const Type *ArgTy = FTy->getParamType(i);
163 const GenericValue &AV = ArgValues[i];
164 switch (ArgTy->getTypeID()) {
165 default: assert(0 && "Unknown argument type for function call!");
166 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
167 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
168 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
169 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
170 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
171 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
172 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
173 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
174 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
175 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
176 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
177 case Type::PointerTyID:
178 void *ArgPtr = GVTOP(AV);
179 if (sizeof(void*) == 4) {
180 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
181 } else {
182 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
183 }
184 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
185 break;
186 }
187 Args.push_back(C);
188 }
189
190 Value *TheCall = new CallInst(F, Args, "", StubBB);
191 if (TheCall->getType() != Type::VoidTy)
192 new ReturnInst(TheCall, StubBB); // Return result of the call.
193 else
194 new ReturnInst(StubBB); // Just return void.
195
196 // Finally, return the value returned by our nullary stub function.
197 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000198}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000199
200/// runJITOnFunction - Run the FunctionPassManager full of
201/// just-in-time compilation passes on F, hopefully filling in
202/// GlobalAddress[F] with the address of F's machine code.
203///
204void JIT::runJITOnFunction(Function *F) {
205 static bool isAlreadyCodeGenerating = false;
206 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
207
208 // JIT the function
209 isAlreadyCodeGenerating = true;
210 PM.run(*F);
211 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000212
213 // If the function referred to a global variable that had not yet been
214 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
215 // all of these globals now.
216 while (!PendingGlobals.empty()) {
217 const GlobalVariable *GV = PendingGlobals.back();
218 PendingGlobals.pop_back();
219 EmitGlobalVariable(GV);
220 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000221}
222
223/// getPointerToFunction - This method is used to get the address of the
224/// specified function, compiling it if neccesary.
225///
226void *JIT::getPointerToFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000227 if (void *Addr = getPointerToGlobalIfAvailable(F))
228 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000229
230 // Make sure we read in the function if it exists in this Module
Chris Lattnerda79bd22004-02-01 00:32:35 +0000231 try {
232 MP->materializeFunction(F);
Reid Spencere2947532004-07-07 21:01:38 +0000233 } catch ( std::string& errmsg ) {
Reid Spencerf86cafd2004-07-07 21:20:28 +0000234 std::cerr << "Error reading bytecode file: " << errmsg << "\n";
Reid Spencere2947532004-07-07 21:01:38 +0000235 abort();
Chris Lattnerda79bd22004-02-01 00:32:35 +0000236 } catch (...) {
Reid Spencerf86cafd2004-07-07 21:20:28 +0000237 std::cerr << "Error reading bytecode file!\n";
Chris Lattnerda79bd22004-02-01 00:32:35 +0000238 abort();
239 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000240
Chris Lattnerc07ed132003-12-20 03:36:47 +0000241 if (F->isExternal()) {
242 void *Addr = getPointerToNamedFunction(F->getName());
243 addGlobalMapping(F, Addr);
244 return Addr;
245 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000246
247 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000248
249 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000250 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
251 return Addr;
252}
253
254// getPointerToFunctionOrStub - If the specified function has been
255// code-gen'd, return a pointer to the function. If not, compile it, or use
256// a stub to implement lazy compilation if available.
257//
258void *JIT::getPointerToFunctionOrStub(Function *F) {
259 // If we have already code generated the function, just return the address.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000260 if (void *Addr = getPointerToGlobalIfAvailable(F))
261 return Addr;
Chris Lattner4d326fa2003-12-20 01:46:27 +0000262
263 // If the target supports "stubs" for functions, get a stub now.
264 if (void *Ptr = TJI.getJITStubForFunction(F, *MCE))
265 return Ptr;
266
267 // Otherwise, if the target doesn't support it, just codegen the function.
268 return getPointerToFunction(F);
269}
270
Chris Lattnerc07ed132003-12-20 03:36:47 +0000271/// getOrEmitGlobalVariable - Return the address of the specified global
272/// variable, possibly emitting it to memory if needed. This is used by the
273/// Emitter.
274void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
275 void *Ptr = getPointerToGlobalIfAvailable(GV);
276 if (Ptr) return Ptr;
277
278 // If the global is external, just remember the address.
279 if (GV->isExternal()) {
280 Ptr = GetAddressOfSymbol(GV->getName().c_str());
281 if (Ptr == 0) {
282 std::cerr << "Could not resolve external global address: "
283 << GV->getName() << "\n";
284 abort();
285 }
286 } else {
287 // If the global hasn't been emitted to memory yet, allocate space. We will
288 // actually initialize the global after current function has finished
289 // compilation.
290 Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
291 PendingGlobals.push_back(GV);
292 }
293 addGlobalMapping(GV, Ptr);
294 return Ptr;
295}
296
297
Chris Lattner4d326fa2003-12-20 01:46:27 +0000298/// recompileAndRelinkFunction - This method is used to force a function
299/// which has already been compiled, to be compiled again, possibly
300/// after it has been modified. Then the entry to the old copy is overwritten
301/// with a branch to the new copy. If there was no old copy, this acts
302/// just like JIT::getPointerToFunction().
303///
304void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000305 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000306
Chris Lattnerc07ed132003-12-20 03:36:47 +0000307 // If it's not already compiled there is no reason to patch it up.
308 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000309
Chris Lattnerc07ed132003-12-20 03:36:47 +0000310 // Delete the old function mapping.
311 addGlobalMapping(F, 0);
312
Chris Lattnerc07ed132003-12-20 03:36:47 +0000313 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000314 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000315
316 // Update state, forward the old function to the new function.
317 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000318 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
319 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
320 return Addr;
321}