blob: d97f1970d51010e601803674c0d5511d0c5b5f3f [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>
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)
Reid Spenceree448632005-07-12 15:51:55 +000033 : ExecutionEngine(MP), TM(tm), TJI(tji), state(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);
Misha Brukmanf976c852005-04-21 22:55:34 +000038
Brian Gaeke50872d52004-04-14 17:45:52 +000039 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +000040 MutexGuard locked(lock);
41 FunctionPassManager& PM = state.getPM(locked);
Chris Lattnercc22e9f2004-08-16 00:14:18 +000042 PM.add(new TargetData(TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +000043
Chris Lattner4d326fa2003-12-20 01:46:27 +000044 // Compile LLVM Code down to machine code in the intermediate representation
45 TJI.addPassesToJITCompile(PM);
46
47 // Turn the machine code intermediate representation into bytes in memory that
48 // may be executed.
49 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
Chris Lattnercc22e9f2004-08-16 00:14:18 +000050 std::cerr << "Target '" << TM.getName()
Chris Lattner4d326fa2003-12-20 01:46:27 +000051 << "' doesn't support machine code emission!\n";
52 abort();
53 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000054}
55
Chris Lattner4d326fa2003-12-20 01:46:27 +000056JIT::~JIT() {
57 delete MCE;
58 delete &TM;
59}
60
Brian Gaeke70975ee2003-09-05 18:42:01 +000061/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000062///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000063GenericValue JIT::runFunction(Function *F,
64 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000065 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000066
67 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000068 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000069 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000070 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000071
Chris Lattnere5eab142004-08-15 23:53:06 +000072 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
73 "Too many arguments passed into function!");
74 assert(FTy->getNumParams() == ArgValues.size() &&
75 "This doesn't support passing arguments through varargs (yet)!");
76
Misha Brukmanec843022004-10-22 23:35:57 +000077 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +000078 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000079 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000080 switch (ArgValues.size()) {
81 case 3:
Misha Brukmanf976c852005-04-21 22:55:34 +000082 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +000083 FTy->getParamType(0) == Type::UIntTy) &&
84 isa<PointerType>(FTy->getParamType(1)) &&
85 isa<PointerType>(FTy->getParamType(2))) {
86 int (*PF)(int, char **, const char **) =
87 (int(*)(int, char **, const char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +000088
Chris Lattnerf7bedf42004-08-15 23:39:59 +000089 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000090 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +000091 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
92 (const char **)GVTOP(ArgValues[2]));
93 return rv;
94 }
95 break;
Chris Lattner174f2262004-08-16 01:07:04 +000096 case 2:
Misha Brukmanf976c852005-04-21 22:55:34 +000097 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattner174f2262004-08-16 01:07:04 +000098 FTy->getParamType(0) == Type::UIntTy) &&
99 isa<PointerType>(FTy->getParamType(1))) {
100 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000101
Chris Lattner174f2262004-08-16 01:07:04 +0000102 // Call the function.
103 GenericValue rv;
104 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
105 return rv;
106 }
107 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000108 case 1:
109 if (FTy->getNumParams() == 1 &&
Misha Brukmanf976c852005-04-21 22:55:34 +0000110 (FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000111 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000112 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000113 int (*PF)(int) = (int(*)(int))FPtr;
114 rv.IntVal = PF(ArgValues[0].IntVal);
115 return rv;
116 }
117 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000118 }
119 }
120
121 // Handle cases where no arguments are passed first.
122 if (ArgValues.empty()) {
123 GenericValue rv;
124 switch (RetTy->getTypeID()) {
125 default: assert(0 && "Unknown return type for function call!");
126 case Type::BoolTyID:
127 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000128 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000129 case Type::SByteTyID:
130 case Type::UByteTyID:
131 rv.SByteVal = ((char(*)())FPtr)();
132 return rv;
133 case Type::ShortTyID:
134 case Type::UShortTyID:
135 rv.ShortVal = ((short(*)())FPtr)();
136 return rv;
137 case Type::VoidTyID:
138 case Type::IntTyID:
139 case Type::UIntTyID:
140 rv.IntVal = ((int(*)())FPtr)();
141 return rv;
142 case Type::LongTyID:
143 case Type::ULongTyID:
144 rv.LongVal = ((int64_t(*)())FPtr)();
145 return rv;
146 case Type::FloatTyID:
147 rv.FloatVal = ((float(*)())FPtr)();
148 return rv;
149 case Type::DoubleTyID:
150 rv.DoubleVal = ((double(*)())FPtr)();
151 return rv;
152 case Type::PointerTyID:
153 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000154 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000155 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000156
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000157 // Okay, this is not one of our quick and easy cases. Because we don't have a
158 // full FFI, we have to codegen a nullary stub function that just calls the
159 // function we are interested in, passing in constants for all of the
160 // arguments. Make this function and return.
161
162 // First, create the function.
163 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
164 Function *Stub = new Function(STy, Function::InternalLinkage, "",
165 F->getParent());
166
167 // Insert a basic block.
168 BasicBlock *StubBB = new BasicBlock("", Stub);
169
170 // Convert all of the GenericValue arguments over to constants. Note that we
171 // currently don't support varargs.
172 std::vector<Value*> Args;
173 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
174 Constant *C = 0;
175 const Type *ArgTy = FTy->getParamType(i);
176 const GenericValue &AV = ArgValues[i];
177 switch (ArgTy->getTypeID()) {
178 default: assert(0 && "Unknown argument type for function call!");
179 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
180 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
181 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
182 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
183 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
184 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
185 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
186 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
187 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
188 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
189 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
190 case Type::PointerTyID:
191 void *ArgPtr = GVTOP(AV);
192 if (sizeof(void*) == 4) {
193 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
194 } else {
195 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
196 }
197 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
198 break;
199 }
200 Args.push_back(C);
201 }
202
Chris Lattnera471e042005-05-06 06:48:54 +0000203 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
204 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000205 if (TheCall->getType() != Type::VoidTy)
206 new ReturnInst(TheCall, StubBB); // Return result of the call.
207 else
208 new ReturnInst(StubBB); // Just return void.
209
210 // Finally, return the value returned by our nullary stub function.
211 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000212}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000213
214/// runJITOnFunction - Run the FunctionPassManager full of
215/// just-in-time compilation passes on F, hopefully filling in
216/// GlobalAddress[F] with the address of F's machine code.
217///
218void JIT::runJITOnFunction(Function *F) {
219 static bool isAlreadyCodeGenerating = false;
220 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Reid Spenceree448632005-07-12 15:51:55 +0000221
222 MutexGuard locked(lock);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000223
224 // JIT the function
225 isAlreadyCodeGenerating = true;
Reid Spenceree448632005-07-12 15:51:55 +0000226 state.getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000227 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000228
229 // If the function referred to a global variable that had not yet been
230 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
231 // all of these globals now.
Reid Spenceree448632005-07-12 15:51:55 +0000232 while (!state.getPendingGlobals(locked).empty()) {
233 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
234 state.getPendingGlobals(locked).pop_back();
Chris Lattnerc07ed132003-12-20 03:36:47 +0000235 EmitGlobalVariable(GV);
236 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000237}
238
239/// getPointerToFunction - This method is used to get the address of the
240/// specified function, compiling it if neccesary.
241///
242void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000243 MutexGuard locked(lock);
244
Chris Lattnerc07ed132003-12-20 03:36:47 +0000245 if (void *Addr = getPointerToGlobalIfAvailable(F))
246 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000247
248 // Make sure we read in the function if it exists in this Module
Misha Brukmanf976c852005-04-21 22:55:34 +0000249 if (F->hasNotBeenReadFromBytecode())
Chris Lattner0050ef82004-11-15 23:18:09 +0000250 try {
251 MP->materializeFunction(F);
252 } catch ( std::string& errmsg ) {
253 std::cerr << "Error reading function '" << F->getName()
254 << "' from bytecode file: " << errmsg << "\n";
255 abort();
256 } catch (...) {
257 std::cerr << "Error reading function '" << F->getName()
258 << "from bytecode file!\n";
259 abort();
260 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000261
Chris Lattnerc07ed132003-12-20 03:36:47 +0000262 if (F->isExternal()) {
263 void *Addr = getPointerToNamedFunction(F->getName());
264 addGlobalMapping(F, Addr);
265 return Addr;
266 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000267
268 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000269
270 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000271 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
272 return Addr;
273}
274
Chris Lattnerc07ed132003-12-20 03:36:47 +0000275/// getOrEmitGlobalVariable - Return the address of the specified global
276/// variable, possibly emitting it to memory if needed. This is used by the
277/// Emitter.
278void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000279 MutexGuard locked(lock);
280
Chris Lattnerc07ed132003-12-20 03:36:47 +0000281 void *Ptr = getPointerToGlobalIfAvailable(GV);
282 if (Ptr) return Ptr;
283
284 // If the global is external, just remember the address.
285 if (GV->isExternal()) {
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000286 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000287 if (Ptr == 0) {
288 std::cerr << "Could not resolve external global address: "
289 << GV->getName() << "\n";
290 abort();
291 }
292 } else {
293 // If the global hasn't been emitted to memory yet, allocate space. We will
294 // actually initialize the global after current function has finished
295 // compilation.
Chris Lattnera8101c12005-01-08 20:07:03 +0000296 uint64_t S = getTargetData().getTypeSize(GV->getType()->getElementType());
297 Ptr = new char[(size_t)S];
Reid Spenceree448632005-07-12 15:51:55 +0000298 state.getPendingGlobals(locked).push_back(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000299 }
300 addGlobalMapping(GV, Ptr);
301 return Ptr;
302}
303
304
Chris Lattner4d326fa2003-12-20 01:46:27 +0000305/// recompileAndRelinkFunction - This method is used to force a function
306/// which has already been compiled, to be compiled again, possibly
307/// after it has been modified. Then the entry to the old copy is overwritten
308/// with a branch to the new copy. If there was no old copy, this acts
309/// just like JIT::getPointerToFunction().
310///
311void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000312 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000313
Chris Lattnerc07ed132003-12-20 03:36:47 +0000314 // If it's not already compiled there is no reason to patch it up.
315 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000316
Chris Lattnerc07ed132003-12-20 03:36:47 +0000317 // Delete the old function mapping.
318 addGlobalMapping(F, 0);
319
Chris Lattnerc07ed132003-12-20 03:36:47 +0000320 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000321 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000322
323 // Update state, forward the old function to the new function.
324 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000325 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
326 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
327 return Addr;
328}
Misha Brukman895eddf2004-11-07 23:58:46 +0000329
330/// freeMachineCodeForFunction - release machine code memory for given Function
331///
332void JIT::freeMachineCodeForFunction(Function *F) {
333 // currently a no-op
334}