blob: 022bd658c211718946b149669c239da27a96f6c9 [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"
Chris Lattnere7fd5532006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000026#include "llvm/System/DynamicLibrary.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000027#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000028#include "llvm/Target/TargetJITInfo.h"
Reid Spencer954da372004-07-04 12:19:56 +000029#include <iostream>
Chris Lattnerc19aade2003-12-08 08:06:28 +000030using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000031
Chris Lattner2fe4bb02006-03-22 06:07:50 +000032static struct RegisterJIT {
33 RegisterJIT() { JIT::Register(); }
34} JITRegistrator;
35
Jeff Cohen2f519142006-03-24 02:53:49 +000036namespace llvm {
37 void LinkInJIT() {
38 }
39}
40
Chris Lattner4d326fa2003-12-20 01:46:27 +000041JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
Reid Spenceree448632005-07-12 15:51:55 +000042 : ExecutionEngine(MP), TM(tm), TJI(tji), state(MP) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000043 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000044
45 // Initialize MCE
Misha Brukman906f5fa2003-06-02 03:23:16 +000046 MCE = createEmitter(*this);
Misha Brukmanf976c852005-04-21 22:55:34 +000047
Brian Gaeke50872d52004-04-14 17:45:52 +000048 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +000049 MutexGuard locked(lock);
50 FunctionPassManager& PM = state.getPM(locked);
Chris Lattnerb93b0342006-05-04 21:18:40 +000051 PM.add(new TargetData(*TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +000052
Chris Lattner4d326fa2003-12-20 01:46:27 +000053 // Compile LLVM Code down to machine code in the intermediate representation
54 TJI.addPassesToJITCompile(PM);
55
56 // Turn the machine code intermediate representation into bytes in memory that
57 // may be executed.
58 if (TM.addPassesToEmitMachineCode(PM, *MCE)) {
Chris Lattnercc22e9f2004-08-16 00:14:18 +000059 std::cerr << "Target '" << TM.getName()
Chris Lattner4d326fa2003-12-20 01:46:27 +000060 << "' doesn't support machine code emission!\n";
61 abort();
62 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +000063}
64
Chris Lattner4d326fa2003-12-20 01:46:27 +000065JIT::~JIT() {
66 delete MCE;
67 delete &TM;
68}
69
Brian Gaeke70975ee2003-09-05 18:42:01 +000070/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +000071///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +000072GenericValue JIT::runFunction(Function *F,
73 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +000074 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +000075
76 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +000077 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +000078 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +000079 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +000080
Chris Lattnere5eab142004-08-15 23:53:06 +000081 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
82 "Too many arguments passed into function!");
83 assert(FTy->getNumParams() == ArgValues.size() &&
84 "This doesn't support passing arguments through varargs (yet)!");
85
Misha Brukmanec843022004-10-22 23:35:57 +000086 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +000087 // prototypes.
Chris Lattnerd297aea2004-08-15 23:34:48 +000088 if (RetTy == Type::IntTy || RetTy == Type::UIntTy || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +000089 switch (ArgValues.size()) {
90 case 3:
Misha Brukmanf976c852005-04-21 22:55:34 +000091 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +000092 FTy->getParamType(0) == Type::UIntTy) &&
93 isa<PointerType>(FTy->getParamType(1)) &&
94 isa<PointerType>(FTy->getParamType(2))) {
95 int (*PF)(int, char **, const char **) =
96 (int(*)(int, char **, const char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +000097
Chris Lattnerf7bedf42004-08-15 23:39:59 +000098 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +000099 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000100 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]),
101 (const char **)GVTOP(ArgValues[2]));
102 return rv;
103 }
104 break;
Chris Lattner174f2262004-08-16 01:07:04 +0000105 case 2:
Misha Brukmanf976c852005-04-21 22:55:34 +0000106 if ((FTy->getParamType(0) == Type::IntTy ||
Chris Lattner174f2262004-08-16 01:07:04 +0000107 FTy->getParamType(0) == Type::UIntTy) &&
108 isa<PointerType>(FTy->getParamType(1))) {
109 int (*PF)(int, char **) = (int(*)(int, char **))FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000110
Chris Lattner174f2262004-08-16 01:07:04 +0000111 // Call the function.
112 GenericValue rv;
113 rv.IntVal = PF(ArgValues[0].IntVal, (char **)GVTOP(ArgValues[1]));
114 return rv;
115 }
116 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000117 case 1:
118 if (FTy->getNumParams() == 1 &&
Misha Brukmanf976c852005-04-21 22:55:34 +0000119 (FTy->getParamType(0) == Type::IntTy ||
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000120 FTy->getParamType(0) == Type::UIntTy)) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000121 GenericValue rv;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000122 int (*PF)(int) = (int(*)(int))FPtr;
123 rv.IntVal = PF(ArgValues[0].IntVal);
124 return rv;
125 }
126 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000127 }
128 }
129
130 // Handle cases where no arguments are passed first.
131 if (ArgValues.empty()) {
132 GenericValue rv;
133 switch (RetTy->getTypeID()) {
134 default: assert(0 && "Unknown return type for function call!");
135 case Type::BoolTyID:
136 rv.BoolVal = ((bool(*)())FPtr)();
Chris Lattnerd297aea2004-08-15 23:34:48 +0000137 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000138 case Type::SByteTyID:
139 case Type::UByteTyID:
140 rv.SByteVal = ((char(*)())FPtr)();
141 return rv;
142 case Type::ShortTyID:
143 case Type::UShortTyID:
144 rv.ShortVal = ((short(*)())FPtr)();
145 return rv;
146 case Type::VoidTyID:
147 case Type::IntTyID:
148 case Type::UIntTyID:
149 rv.IntVal = ((int(*)())FPtr)();
150 return rv;
151 case Type::LongTyID:
152 case Type::ULongTyID:
153 rv.LongVal = ((int64_t(*)())FPtr)();
154 return rv;
155 case Type::FloatTyID:
156 rv.FloatVal = ((float(*)())FPtr)();
157 return rv;
158 case Type::DoubleTyID:
159 rv.DoubleVal = ((double(*)())FPtr)();
160 return rv;
161 case Type::PointerTyID:
162 return PTOGV(((void*(*)())FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000163 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000164 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000165
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000166 // Okay, this is not one of our quick and easy cases. Because we don't have a
167 // full FFI, we have to codegen a nullary stub function that just calls the
168 // function we are interested in, passing in constants for all of the
169 // arguments. Make this function and return.
170
171 // First, create the function.
172 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
173 Function *Stub = new Function(STy, Function::InternalLinkage, "",
174 F->getParent());
175
176 // Insert a basic block.
177 BasicBlock *StubBB = new BasicBlock("", Stub);
178
179 // Convert all of the GenericValue arguments over to constants. Note that we
180 // currently don't support varargs.
181 std::vector<Value*> Args;
182 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
183 Constant *C = 0;
184 const Type *ArgTy = FTy->getParamType(i);
185 const GenericValue &AV = ArgValues[i];
186 switch (ArgTy->getTypeID()) {
187 default: assert(0 && "Unknown argument type for function call!");
188 case Type::BoolTyID: C = ConstantBool::get(AV.BoolVal); break;
189 case Type::SByteTyID: C = ConstantSInt::get(ArgTy, AV.SByteVal); break;
190 case Type::UByteTyID: C = ConstantUInt::get(ArgTy, AV.UByteVal); break;
191 case Type::ShortTyID: C = ConstantSInt::get(ArgTy, AV.ShortVal); break;
192 case Type::UShortTyID: C = ConstantUInt::get(ArgTy, AV.UShortVal); break;
193 case Type::IntTyID: C = ConstantSInt::get(ArgTy, AV.IntVal); break;
194 case Type::UIntTyID: C = ConstantUInt::get(ArgTy, AV.UIntVal); break;
195 case Type::LongTyID: C = ConstantSInt::get(ArgTy, AV.LongVal); break;
196 case Type::ULongTyID: C = ConstantUInt::get(ArgTy, AV.ULongVal); break;
197 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
198 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
199 case Type::PointerTyID:
200 void *ArgPtr = GVTOP(AV);
201 if (sizeof(void*) == 4) {
202 C = ConstantSInt::get(Type::IntTy, (int)(intptr_t)ArgPtr);
203 } else {
204 C = ConstantSInt::get(Type::LongTy, (intptr_t)ArgPtr);
205 }
206 C = ConstantExpr::getCast(C, ArgTy); // Cast the integer to pointer
207 break;
208 }
209 Args.push_back(C);
210 }
211
Chris Lattnera471e042005-05-06 06:48:54 +0000212 CallInst *TheCall = new CallInst(F, Args, "", StubBB);
213 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000214 if (TheCall->getType() != Type::VoidTy)
215 new ReturnInst(TheCall, StubBB); // Return result of the call.
216 else
217 new ReturnInst(StubBB); // Just return void.
218
219 // Finally, return the value returned by our nullary stub function.
220 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000221}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000222
223/// runJITOnFunction - Run the FunctionPassManager full of
224/// just-in-time compilation passes on F, hopefully filling in
225/// GlobalAddress[F] with the address of F's machine code.
226///
227void JIT::runJITOnFunction(Function *F) {
228 static bool isAlreadyCodeGenerating = false;
229 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Jeff Cohen00b168892005-07-27 06:12:32 +0000230
Reid Spenceree448632005-07-12 15:51:55 +0000231 MutexGuard locked(lock);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000232
233 // JIT the function
234 isAlreadyCodeGenerating = true;
Reid Spenceree448632005-07-12 15:51:55 +0000235 state.getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000236 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000237
238 // If the function referred to a global variable that had not yet been
239 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
240 // all of these globals now.
Reid Spenceree448632005-07-12 15:51:55 +0000241 while (!state.getPendingGlobals(locked).empty()) {
242 const GlobalVariable *GV = state.getPendingGlobals(locked).back();
243 state.getPendingGlobals(locked).pop_back();
Chris Lattnerc07ed132003-12-20 03:36:47 +0000244 EmitGlobalVariable(GV);
245 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000246}
247
248/// getPointerToFunction - This method is used to get the address of the
249/// specified function, compiling it if neccesary.
250///
251void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000252 MutexGuard locked(lock);
253
Chris Lattnerc07ed132003-12-20 03:36:47 +0000254 if (void *Addr = getPointerToGlobalIfAvailable(F))
255 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000256
257 // Make sure we read in the function if it exists in this Module
Misha Brukmanf976c852005-04-21 22:55:34 +0000258 if (F->hasNotBeenReadFromBytecode())
Chris Lattner0050ef82004-11-15 23:18:09 +0000259 try {
260 MP->materializeFunction(F);
261 } catch ( std::string& errmsg ) {
262 std::cerr << "Error reading function '" << F->getName()
263 << "' from bytecode file: " << errmsg << "\n";
264 abort();
265 } catch (...) {
266 std::cerr << "Error reading function '" << F->getName()
267 << "from bytecode file!\n";
268 abort();
269 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000270
Chris Lattnerc07ed132003-12-20 03:36:47 +0000271 if (F->isExternal()) {
272 void *Addr = getPointerToNamedFunction(F->getName());
273 addGlobalMapping(F, Addr);
274 return Addr;
275 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000276
277 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000278
279 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000280 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
281 return Addr;
282}
283
Chris Lattnerc07ed132003-12-20 03:36:47 +0000284/// getOrEmitGlobalVariable - Return the address of the specified global
285/// variable, possibly emitting it to memory if needed. This is used by the
286/// Emitter.
287void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000288 MutexGuard locked(lock);
289
Chris Lattnerc07ed132003-12-20 03:36:47 +0000290 void *Ptr = getPointerToGlobalIfAvailable(GV);
291 if (Ptr) return Ptr;
292
293 // If the global is external, just remember the address.
294 if (GV->isExternal()) {
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000295 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000296 if (Ptr == 0) {
297 std::cerr << "Could not resolve external global address: "
298 << GV->getName() << "\n";
299 abort();
300 }
301 } else {
302 // If the global hasn't been emitted to memory yet, allocate space. We will
303 // actually initialize the global after current function has finished
304 // compilation.
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000305 const Type *GlobalType = GV->getType()->getElementType();
Owen Andersona69571c2006-05-03 01:29:57 +0000306 size_t S = getTargetData()->getTypeSize(GlobalType);
307 size_t A = getTargetData()->getTypeAlignment(GlobalType);
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000308 if (A <= 8) {
309 Ptr = malloc(S);
310 } else {
311 // Allocate S+A bytes of memory, then use an aligned pointer within that
312 // space.
313 Ptr = malloc(S+A);
314 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
315 unsigned Offset = MisAligned ? (A-MisAligned) : 0;
316
317 // Trim the tail off the memory block.
318 realloc(Ptr, S+Offset);
319 Ptr = (char*)Ptr + Offset;
320 }
Reid Spenceree448632005-07-12 15:51:55 +0000321 state.getPendingGlobals(locked).push_back(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000322 }
323 addGlobalMapping(GV, Ptr);
324 return Ptr;
325}
326
327
Chris Lattner4d326fa2003-12-20 01:46:27 +0000328/// recompileAndRelinkFunction - This method is used to force a function
329/// which has already been compiled, to be compiled again, possibly
330/// after it has been modified. Then the entry to the old copy is overwritten
331/// with a branch to the new copy. If there was no old copy, this acts
332/// just like JIT::getPointerToFunction().
333///
334void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000335 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000336
Chris Lattnerc07ed132003-12-20 03:36:47 +0000337 // If it's not already compiled there is no reason to patch it up.
338 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000339
Chris Lattnerc07ed132003-12-20 03:36:47 +0000340 // Delete the old function mapping.
341 addGlobalMapping(F, 0);
342
Chris Lattnerc07ed132003-12-20 03:36:47 +0000343 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000344 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000345
346 // Update state, forward the old function to the new function.
347 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000348 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
349 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
350 return Addr;
351}
Misha Brukman895eddf2004-11-07 23:58:46 +0000352