blob: 537ca56e024839b4e3930fb344ad5eff6cd262a8 [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"
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>
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
Misha Brukmanec843022004-10-22 23:35:57 +000075 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +000076 // 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:
Chris Lattner174f2262004-08-16 01:07:04 +000080 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +000081 FTy->getParamType(0) == Type::UIntTy) &&
82 isa<PointerType>(FTy->getParamType(1)) &&
83 isa<PointerType>(FTy->getParamType(2))) {
84 int (*PF)(int, char **, const char **) =
85 (int(*)(int, char **, const char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +000086
Chris Lattnerf7bedf42004-08-15 23:39:59 +000087 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000088 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000089 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
90 (const char **)GVTOP(ArgValues[2]));
91 return rv;
92 }
93 break;
Chris Lattner174f2262004-08-16 01:07:04 +000094 case 2:
95 if ((FTy->getParamType(0) == Type::IntTy ||
96 FTy->getParamType(0) == Type::UIntTy) &&
97 isa<PointerType>(FTy->getParamType(1))) {
98 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +000099
Chris Lattner174f2262004-08-16 01:07:04 +0000100 // Call the function.
101 GenericValue rv;
102 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
103 return rv;
104 }
105 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000106 case 1:
107 if (FTy->getNumParams() == 1 &&
108 (FTy->getParamType(0) == Type::IntTy ||
109 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000110 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000111 int (*PF)(int) = (int(*)(int))FPtr;
112 rv.IntVal = PF(ArgValues[0].IntVal);
113 return rv;
114 }
115 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000116 }
117 }
118
119 // Handle cases where no arguments are passed first.
120 if (ArgValues.empty()) {
121 GenericValue rv;
122 switch (RetTy->getTypeID()) {
123 default: assert(0 && "Unknown return type for function call!");
124 case Type::BoolTyID:
125 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000126 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000127 case Type::SByteTyID:
128 case Type::UByteTyID:
129 rv.SByteVal = ((char(*)())FPtr)();
130 return rv;
131 case Type::ShortTyID:
132 case Type::UShortTyID:
133 rv.ShortVal = ((short(*)())FPtr)();
134 return rv;
135 case Type::VoidTyID:
136 case Type::IntTyID:
137 case Type::UIntTyID:
138 rv.IntVal = ((int(*)())FPtr)();
139 return rv;
140 case Type::LongTyID:
141 case Type::ULongTyID:
142 rv.LongVal = ((int64_t(*)())FPtr)();
143 return rv;
144 case Type::FloatTyID:
145 rv.FloatVal = ((float(*)())FPtr)();
146 return rv;
147 case Type::DoubleTyID:
148 rv.DoubleVal = ((double(*)())FPtr)();
149 return rv;
150 case Type::PointerTyID:
151 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000152 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000153 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000154
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000155 // Okay, this is not one of our quick and easy cases. Because we don't have a
156 // full FFI, we have to codegen a nullary stub function that just calls the
157 // function we are interested in, passing in constants for all of the
158 // arguments. Make this function and return.
159
160 // First, create the function.
161 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
162 Function *Stub = new Function(STy, Function::InternalLinkage, "",
163 F->getParent());
164
165 // Insert a basic block.
166 BasicBlock *StubBB = new BasicBlock("", Stub);
167
168 // Convert all of the GenericValue arguments over to constants. Note that we
169 // currently don't support varargs.
170 std::vector<Value*> Args;
171 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
172 Constant *C = 0;
173 const Type *ArgTy = FTy->getParamType(i);
174 const GenericValue &AV = ArgValues[i];
175 switch (ArgTy->getTypeID()) {
176 default: assert(0 && "Unknown argument type for function call!");
177 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
178 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
179 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
180 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
181 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
182 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
183 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
184 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
185 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
186 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
187 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
188 case Type::PointerTyID:
189 void *ArgPtr = GVTOP(AV);
190 if (sizeof(void*) == 4) {
191 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
192 } else {
193 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
194 }
195 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
196 break;
197 }
198 Args.push_back(C);
199 }
200
201 Value *TheCall = new CallInst(F, Args, "", StubBB);
202 if (TheCall->getType() != Type::VoidTy)
203 new ReturnInst(TheCall, StubBB); // Return result of the call.
204 else
205 new ReturnInst(StubBB); // Just return void.
206
207 // Finally, return the value returned by our nullary stub function.
208 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000209}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000210
211/// runJITOnFunction - Run the FunctionPassManager full of
212/// just-in-time compilation passes on F, hopefully filling in
213/// GlobalAddress[F] with the address of F's machine code.
214///
215void JIT::runJITOnFunction(Function *F) {
216 static bool isAlreadyCodeGenerating = false;
217 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
218
219 // JIT the function
220 isAlreadyCodeGenerating = true;
221 PM.run(*F);
222 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000223
224 // If the function referred to a global variable that had not yet been
225 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
226 // all of these globals now.
227 while (!PendingGlobals.empty()) {
228 const GlobalVariable *GV = PendingGlobals.back();
229 PendingGlobals.pop_back();
230 EmitGlobalVariable(GV);
231 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000232}
233
234/// getPointerToFunction - This method is used to get the address of the
235/// specified function, compiling it if neccesary.
236///
237void *JIT::getPointerToFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000238 if (void *Addr = getPointerToGlobalIfAvailable(F))
239 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000240
241 // Make sure we read in the function if it exists in this Module
Chris Lattner0050ef82004-11-15 23:18:09 +0000242 if (F->hasNotBeenReadFromBytecode())
243 try {
244 MP->materializeFunction(F);
245 } catch ( std::string& errmsg ) {
246 std::cerr << "Error reading function '" << F->getName()
247 << "' from bytecode file: " << errmsg << "\n";
248 abort();
249 } catch (...) {
250 std::cerr << "Error reading function '" << F->getName()
251 << "from bytecode file!\n";
252 abort();
253 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000254
Chris Lattnerc07ed132003-12-20 03:36:47 +0000255 if (F->isExternal()) {
256 void *Addr = getPointerToNamedFunction(F->getName());
257 addGlobalMapping(F, Addr);
258 return Addr;
259 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000260
261 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000262
263 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000264 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
265 return Addr;
266}
267
268// getPointerToFunctionOrStub - If the specified function has been
269// code-gen'd, return a pointer to the function. If not, compile it, or use
270// a stub to implement lazy compilation if available.
271//
272void *JIT::getPointerToFunctionOrStub(Function *F) {
273 // If we have already code generated the function, just return the address.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000274 if (void *Addr = getPointerToGlobalIfAvailable(F))
275 return Addr;
Chris Lattner4d326fa2003-12-20 01:46:27 +0000276
Chris Lattner4d326fa2003-12-20 01:46:27 +0000277 // Otherwise, if the target doesn't support it, just codegen the function.
278 return getPointerToFunction(F);
279}
280
Chris Lattnerc07ed132003-12-20 03:36:47 +0000281/// getOrEmitGlobalVariable - Return the address of the specified global
282/// variable, possibly emitting it to memory if needed. This is used by the
283/// Emitter.
284void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
285 void *Ptr = getPointerToGlobalIfAvailable(GV);
286 if (Ptr) return Ptr;
287
288 // If the global is external, just remember the address.
289 if (GV->isExternal()) {
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000290 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000291 if (Ptr == 0) {
292 std::cerr << "Could not resolve external global address: "
293 << GV->getName() << "\n";
294 abort();
295 }
296 } else {
297 // If the global hasn't been emitted to memory yet, allocate space. We will
298 // actually initialize the global after current function has finished
299 // compilation.
300 Ptr =new char[getTargetData().getTypeSize(GV->getType()->getElementType())];
301 PendingGlobals.push_back(GV);
302 }
303 addGlobalMapping(GV, Ptr);
304 return Ptr;
305}
306
307
Chris Lattner4d326fa2003-12-20 01:46:27 +0000308/// recompileAndRelinkFunction - This method is used to force a function
309/// which has already been compiled, to be compiled again, possibly
310/// after it has been modified. Then the entry to the old copy is overwritten
311/// with a branch to the new copy. If there was no old copy, this acts
312/// just like JIT::getPointerToFunction().
313///
314void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000315 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000316
Chris Lattnerc07ed132003-12-20 03:36:47 +0000317 // If it's not already compiled there is no reason to patch it up.
318 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000319
Chris Lattnerc07ed132003-12-20 03:36:47 +0000320 // Delete the old function mapping.
321 addGlobalMapping(F, 0);
322
Chris Lattnerc07ed132003-12-20 03:36:47 +0000323 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000324 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000325
326 // Update state, forward the old function to the new function.
327 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000328 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
329 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
330 return Addr;
331}
Misha Brukman895eddf2004-11-07 23:58:46 +0000332
333/// freeMachineCodeForFunction - release machine code memory for given Function
334///
335void JIT::freeMachineCodeForFunction(Function *F) {
336 // currently a no-op
337}