blob: 766d62ce194b478be7180208c516a29d793b4144 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
2//
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//===----------------------------------------------------------------------===//
9//
10// This tool implements a just-in-time compiler for LLVM, allowing direct
11// execution of LLVM bitcode in an efficient manner.
12//
13//===----------------------------------------------------------------------===//
14
15#include "JIT.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Function.h"
19#include "llvm/GlobalVariable.h"
20#include "llvm/Instructions.h"
21#include "llvm/ModuleProvider.h"
22#include "llvm/CodeGen/MachineCodeEmitter.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/ExecutionEngine/GenericValue.h"
25#include "llvm/Support/MutexGuard.h"
26#include "llvm/System/DynamicLibrary.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetJITInfo.h"
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000030
31#include "llvm/Config/config.h"
32
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033using namespace llvm;
34
35#ifdef __APPLE__
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000036// Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
37// of atexit). It passes the address of linker generated symbol __dso_handle
38// to the function.
39// This configuration change happened at version 5330.
40# include <AvailabilityMacros.h>
41# if defined(MAC_OS_X_VERSION_10_4) && \
42 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
43 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
44 __APPLE_CC__ >= 5330))
45# ifndef HAVE___DSO_HANDLE
46# define HAVE___DSO_HANDLE 1
47# endif
48# endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#endif
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000050
51#if HAVE___DSO_HANDLE
52extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#endif
54
55static struct RegisterJIT {
56 RegisterJIT() { JIT::Register(); }
57} JITRegistrator;
58
59namespace llvm {
60 void LinkInJIT() {
61 }
62}
63
64JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji)
65 : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
66 setTargetData(TM.getTargetData());
67
68 // Initialize MCE
69 MCE = createEmitter(*this);
70
71 // Add target data
72 MutexGuard locked(lock);
73 FunctionPassManager &PM = jitstate.getPM(locked);
74 PM.add(new TargetData(*TM.getTargetData()));
75
76 // Turn the machine code intermediate representation into bytes in memory that
77 // may be executed.
78 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
79 cerr << "Target does not support machine code emission!\n";
80 abort();
81 }
82
83 // Initialize passes.
84 PM.doInitialization();
85}
86
87JIT::~JIT() {
88 delete MCE;
89 delete &TM;
90}
91
92/// run - Start execution with the specified function and arguments.
93///
94GenericValue JIT::runFunction(Function *F,
95 const std::vector<GenericValue> &ArgValues) {
96 assert(F && "Function *F was null at entry to run()");
97
98 void *FPtr = getPointerToFunction(F);
99 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
100 const FunctionType *FTy = F->getFunctionType();
101 const Type *RetTy = FTy->getReturnType();
102
103 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
104 "Too many arguments passed into function!");
105 assert(FTy->getNumParams() == ArgValues.size() &&
106 "This doesn't support passing arguments through varargs (yet)!");
107
108 // Handle some common cases first. These cases correspond to common `main'
109 // prototypes.
Chris Lattnerbbf22702007-08-08 16:19:57 +0000110 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000111 switch (ArgValues.size()) {
112 case 3:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000113 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 isa<PointerType>(FTy->getParamType(1)) &&
115 isa<PointerType>(FTy->getParamType(2))) {
116 int (*PF)(int, char **, const char **) =
117 (int(*)(int, char **, const char **))(intptr_t)FPtr;
118
119 // Call the function.
120 GenericValue rv;
121 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
122 (char **)GVTOP(ArgValues[1]),
123 (const char **)GVTOP(ArgValues[2])));
124 return rv;
125 }
126 break;
127 case 2:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000128 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000129 isa<PointerType>(FTy->getParamType(1))) {
130 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
131
132 // Call the function.
133 GenericValue rv;
134 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
135 (char **)GVTOP(ArgValues[1])));
136 return rv;
137 }
138 break;
139 case 1:
140 if (FTy->getNumParams() == 1 &&
Chris Lattnerbbf22702007-08-08 16:19:57 +0000141 FTy->getParamType(0) == Type::Int32Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 GenericValue rv;
143 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
144 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
145 return rv;
146 }
147 break;
148 }
149 }
150
151 // Handle cases where no arguments are passed first.
152 if (ArgValues.empty()) {
153 GenericValue rv;
154 switch (RetTy->getTypeID()) {
155 default: assert(0 && "Unknown return type for function call!");
156 case Type::IntegerTyID: {
157 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
158 if (BitWidth == 1)
159 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
160 else if (BitWidth <= 8)
161 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
162 else if (BitWidth <= 16)
163 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
164 else if (BitWidth <= 32)
165 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
166 else if (BitWidth <= 64)
167 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
168 else
169 assert(0 && "Integer types > 64 bits not supported");
170 return rv;
171 }
172 case Type::VoidTyID:
173 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
174 return rv;
175 case Type::FloatTyID:
176 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
177 return rv;
178 case Type::DoubleTyID:
179 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
180 return rv;
181 case Type::PointerTyID:
182 return PTOGV(((void*(*)())(intptr_t)FPtr)());
183 }
184 }
185
186 // Okay, this is not one of our quick and easy cases. Because we don't have a
187 // full FFI, we have to codegen a nullary stub function that just calls the
188 // function we are interested in, passing in constants for all of the
189 // arguments. Make this function and return.
190
191 // First, create the function.
192 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
193 Function *Stub = new Function(STy, Function::InternalLinkage, "",
194 F->getParent());
195
196 // Insert a basic block.
197 BasicBlock *StubBB = new BasicBlock("", Stub);
198
199 // Convert all of the GenericValue arguments over to constants. Note that we
200 // currently don't support varargs.
201 SmallVector<Value*, 8> Args;
202 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
203 Constant *C = 0;
204 const Type *ArgTy = FTy->getParamType(i);
205 const GenericValue &AV = ArgValues[i];
206 switch (ArgTy->getTypeID()) {
207 default: assert(0 && "Unknown argument type for function call!");
208 case Type::IntegerTyID: C = ConstantInt::get(AV.IntVal); break;
209 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
210 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
211 case Type::PointerTyID:
212 void *ArgPtr = GVTOP(AV);
213 if (sizeof(void*) == 4) {
214 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
215 } else {
216 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
217 }
218 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
219 break;
220 }
221 Args.push_back(C);
222 }
223
David Greeneb1c4a7b2007-08-01 03:43:44 +0000224 CallInst *TheCall = new CallInst(F, Args.begin(), Args.end(), "", StubBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 TheCall->setTailCall();
226 if (TheCall->getType() != Type::VoidTy)
227 new ReturnInst(TheCall, StubBB); // Return result of the call.
228 else
229 new ReturnInst(StubBB); // Just return void.
230
231 // Finally, return the value returned by our nullary stub function.
232 return runFunction(Stub, std::vector<GenericValue>());
233}
234
235/// runJITOnFunction - Run the FunctionPassManager full of
236/// just-in-time compilation passes on F, hopefully filling in
237/// GlobalAddress[F] with the address of F's machine code.
238///
239void JIT::runJITOnFunction(Function *F) {
240 static bool isAlreadyCodeGenerating = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241
242 MutexGuard locked(lock);
Chris Lattner700fb1d2007-08-13 20:08:16 +0000243 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244
245 // JIT the function
246 isAlreadyCodeGenerating = true;
247 jitstate.getPM(locked).run(*F);
248 isAlreadyCodeGenerating = false;
249
250 // If the function referred to a global variable that had not yet been
251 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
252 // all of these globals now.
253 while (!jitstate.getPendingGlobals(locked).empty()) {
254 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
255 jitstate.getPendingGlobals(locked).pop_back();
256 EmitGlobalVariable(GV);
257 }
258}
259
260/// getPointerToFunction - This method is used to get the address of the
261/// specified function, compiling it if neccesary.
262///
263void *JIT::getPointerToFunction(Function *F) {
264 MutexGuard locked(lock);
265
266 if (void *Addr = getPointerToGlobalIfAvailable(F))
267 return Addr; // Check if function already code gen'd
268
269 // Make sure we read in the function if it exists in this Module.
270 if (F->hasNotBeenReadFromBitcode()) {
271 // Determine the module provider this function is provided by.
272 Module *M = F->getParent();
273 ModuleProvider *MP = 0;
274 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
275 if (Modules[i]->getModule() == M) {
276 MP = Modules[i];
277 break;
278 }
279 }
280 assert(MP && "Function isn't in a module we know about!");
281
282 std::string ErrorMsg;
283 if (MP->materializeFunction(F, &ErrorMsg)) {
284 cerr << "Error reading function '" << F->getName()
285 << "' from bitcode file: " << ErrorMsg << "\n";
286 abort();
287 }
288 }
289
290 if (F->isDeclaration()) {
291 void *Addr = getPointerToNamedFunction(F->getName());
292 addGlobalMapping(F, Addr);
293 return Addr;
294 }
295
296 runJITOnFunction(F);
297
298 void *Addr = getPointerToGlobalIfAvailable(F);
299 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
300 return Addr;
301}
302
303/// getOrEmitGlobalVariable - Return the address of the specified global
304/// variable, possibly emitting it to memory if needed. This is used by the
305/// Emitter.
306void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
307 MutexGuard locked(lock);
308
309 void *Ptr = getPointerToGlobalIfAvailable(GV);
310 if (Ptr) return Ptr;
311
312 // If the global is external, just remember the address.
313 if (GV->isDeclaration()) {
Anton Korobeynikov52f44db2007-07-30 20:02:02 +0000314#if HAVE___DSO_HANDLE
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 if (GV->getName() == "__dso_handle")
316 return (void*)&__dso_handle;
317#endif
318 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
319 if (Ptr == 0) {
320 cerr << "Could not resolve external global address: "
321 << GV->getName() << "\n";
322 abort();
323 }
324 } else {
325 // If the global hasn't been emitted to memory yet, allocate space. We will
326 // actually initialize the global after current function has finished
327 // compilation.
328 const Type *GlobalType = GV->getType()->getElementType();
329 size_t S = getTargetData()->getTypeSize(GlobalType);
330 size_t A = getTargetData()->getPrefTypeAlignment(GlobalType);
331 if (A <= 8) {
332 Ptr = malloc(S);
333 } else {
334 // Allocate S+A bytes of memory, then use an aligned pointer within that
335 // space.
336 Ptr = malloc(S+A);
337 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
338 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
339 }
340 jitstate.getPendingGlobals(locked).push_back(GV);
341 }
342 addGlobalMapping(GV, Ptr);
343 return Ptr;
344}
345
346
347/// recompileAndRelinkFunction - This method is used to force a function
348/// which has already been compiled, to be compiled again, possibly
349/// after it has been modified. Then the entry to the old copy is overwritten
350/// with a branch to the new copy. If there was no old copy, this acts
351/// just like JIT::getPointerToFunction().
352///
353void *JIT::recompileAndRelinkFunction(Function *F) {
354 void *OldAddr = getPointerToGlobalIfAvailable(F);
355
356 // If it's not already compiled there is no reason to patch it up.
357 if (OldAddr == 0) { return getPointerToFunction(F); }
358
359 // Delete the old function mapping.
360 addGlobalMapping(F, 0);
361
362 // Recodegen the function
363 runJITOnFunction(F);
364
365 // Update state, forward the old function to the new function.
366 void *Addr = getPointerToGlobalIfAvailable(F);
367 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
368 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
369 return Addr;
370}
371