blob: d6b080e1a57fe01153bebacc36efbb1cf09d05a1 [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.
110 if (RetTy == Type::Int32Ty || RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
111 switch (ArgValues.size()) {
112 case 3:
113 if ((FTy->getParamType(0) == Type::Int32Ty ||
114 FTy->getParamType(0) == Type::Int32Ty) &&
115 isa<PointerType>(FTy->getParamType(1)) &&
116 isa<PointerType>(FTy->getParamType(2))) {
117 int (*PF)(int, char **, const char **) =
118 (int(*)(int, char **, const char **))(intptr_t)FPtr;
119
120 // Call the function.
121 GenericValue rv;
122 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
123 (char **)GVTOP(ArgValues[1]),
124 (const char **)GVTOP(ArgValues[2])));
125 return rv;
126 }
127 break;
128 case 2:
129 if ((FTy->getParamType(0) == Type::Int32Ty ||
130 FTy->getParamType(0) == Type::Int32Ty) &&
131 isa<PointerType>(FTy->getParamType(1))) {
132 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
133
134 // Call the function.
135 GenericValue rv;
136 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
137 (char **)GVTOP(ArgValues[1])));
138 return rv;
139 }
140 break;
141 case 1:
142 if (FTy->getNumParams() == 1 &&
143 (FTy->getParamType(0) == Type::Int32Ty ||
144 FTy->getParamType(0) == Type::Int32Ty)) {
145 GenericValue rv;
146 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
147 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
148 return rv;
149 }
150 break;
151 }
152 }
153
154 // Handle cases where no arguments are passed first.
155 if (ArgValues.empty()) {
156 GenericValue rv;
157 switch (RetTy->getTypeID()) {
158 default: assert(0 && "Unknown return type for function call!");
159 case Type::IntegerTyID: {
160 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
161 if (BitWidth == 1)
162 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
163 else if (BitWidth <= 8)
164 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
165 else if (BitWidth <= 16)
166 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
167 else if (BitWidth <= 32)
168 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
169 else if (BitWidth <= 64)
170 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
171 else
172 assert(0 && "Integer types > 64 bits not supported");
173 return rv;
174 }
175 case Type::VoidTyID:
176 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
177 return rv;
178 case Type::FloatTyID:
179 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
180 return rv;
181 case Type::DoubleTyID:
182 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
183 return rv;
184 case Type::PointerTyID:
185 return PTOGV(((void*(*)())(intptr_t)FPtr)());
186 }
187 }
188
189 // Okay, this is not one of our quick and easy cases. Because we don't have a
190 // full FFI, we have to codegen a nullary stub function that just calls the
191 // function we are interested in, passing in constants for all of the
192 // arguments. Make this function and return.
193
194 // First, create the function.
195 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
196 Function *Stub = new Function(STy, Function::InternalLinkage, "",
197 F->getParent());
198
199 // Insert a basic block.
200 BasicBlock *StubBB = new BasicBlock("", Stub);
201
202 // Convert all of the GenericValue arguments over to constants. Note that we
203 // currently don't support varargs.
204 SmallVector<Value*, 8> Args;
205 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
206 Constant *C = 0;
207 const Type *ArgTy = FTy->getParamType(i);
208 const GenericValue &AV = ArgValues[i];
209 switch (ArgTy->getTypeID()) {
210 default: assert(0 && "Unknown argument type for function call!");
211 case Type::IntegerTyID: C = ConstantInt::get(AV.IntVal); break;
212 case Type::FloatTyID: C = ConstantFP ::get(ArgTy, AV.FloatVal); break;
213 case Type::DoubleTyID: C = ConstantFP ::get(ArgTy, AV.DoubleVal); break;
214 case Type::PointerTyID:
215 void *ArgPtr = GVTOP(AV);
216 if (sizeof(void*) == 4) {
217 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
218 } else {
219 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
220 }
221 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
222 break;
223 }
224 Args.push_back(C);
225 }
226
David Greeneb1c4a7b2007-08-01 03:43:44 +0000227 CallInst *TheCall = new CallInst(F, Args.begin(), Args.end(), "", StubBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 TheCall->setTailCall();
229 if (TheCall->getType() != Type::VoidTy)
230 new ReturnInst(TheCall, StubBB); // Return result of the call.
231 else
232 new ReturnInst(StubBB); // Just return void.
233
234 // Finally, return the value returned by our nullary stub function.
235 return runFunction(Stub, std::vector<GenericValue>());
236}
237
238/// runJITOnFunction - Run the FunctionPassManager full of
239/// just-in-time compilation passes on F, hopefully filling in
240/// GlobalAddress[F] with the address of F's machine code.
241///
242void JIT::runJITOnFunction(Function *F) {
243 static bool isAlreadyCodeGenerating = false;
244 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
245
246 MutexGuard locked(lock);
247
248 // JIT the function
249 isAlreadyCodeGenerating = true;
250 jitstate.getPM(locked).run(*F);
251 isAlreadyCodeGenerating = false;
252
253 // If the function referred to a global variable that had not yet been
254 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
255 // all of these globals now.
256 while (!jitstate.getPendingGlobals(locked).empty()) {
257 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
258 jitstate.getPendingGlobals(locked).pop_back();
259 EmitGlobalVariable(GV);
260 }
261}
262
263/// getPointerToFunction - This method is used to get the address of the
264/// specified function, compiling it if neccesary.
265///
266void *JIT::getPointerToFunction(Function *F) {
267 MutexGuard locked(lock);
268
269 if (void *Addr = getPointerToGlobalIfAvailable(F))
270 return Addr; // Check if function already code gen'd
271
272 // Make sure we read in the function if it exists in this Module.
273 if (F->hasNotBeenReadFromBitcode()) {
274 // Determine the module provider this function is provided by.
275 Module *M = F->getParent();
276 ModuleProvider *MP = 0;
277 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
278 if (Modules[i]->getModule() == M) {
279 MP = Modules[i];
280 break;
281 }
282 }
283 assert(MP && "Function isn't in a module we know about!");
284
285 std::string ErrorMsg;
286 if (MP->materializeFunction(F, &ErrorMsg)) {
287 cerr << "Error reading function '" << F->getName()
288 << "' from bitcode file: " << ErrorMsg << "\n";
289 abort();
290 }
291 }
292
293 if (F->isDeclaration()) {
294 void *Addr = getPointerToNamedFunction(F->getName());
295 addGlobalMapping(F, Addr);
296 return Addr;
297 }
298
299 runJITOnFunction(F);
300
301 void *Addr = getPointerToGlobalIfAvailable(F);
302 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
303 return Addr;
304}
305
306/// getOrEmitGlobalVariable - Return the address of the specified global
307/// variable, possibly emitting it to memory if needed. This is used by the
308/// Emitter.
309void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
310 MutexGuard locked(lock);
311
312 void *Ptr = getPointerToGlobalIfAvailable(GV);
313 if (Ptr) return Ptr;
314
315 // If the global is external, just remember the address.
316 if (GV->isDeclaration()) {
Anton Korobeynikov52f44db2007-07-30 20:02:02 +0000317#if HAVE___DSO_HANDLE
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 if (GV->getName() == "__dso_handle")
319 return (void*)&__dso_handle;
320#endif
321 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
322 if (Ptr == 0) {
323 cerr << "Could not resolve external global address: "
324 << GV->getName() << "\n";
325 abort();
326 }
327 } else {
328 // If the global hasn't been emitted to memory yet, allocate space. We will
329 // actually initialize the global after current function has finished
330 // compilation.
331 const Type *GlobalType = GV->getType()->getElementType();
332 size_t S = getTargetData()->getTypeSize(GlobalType);
333 size_t A = getTargetData()->getPrefTypeAlignment(GlobalType);
334 if (A <= 8) {
335 Ptr = malloc(S);
336 } else {
337 // Allocate S+A bytes of memory, then use an aligned pointer within that
338 // space.
339 Ptr = malloc(S+A);
340 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
341 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
342 }
343 jitstate.getPendingGlobals(locked).push_back(GV);
344 }
345 addGlobalMapping(GV, Ptr);
346 return Ptr;
347}
348
349
350/// recompileAndRelinkFunction - This method is used to force a function
351/// which has already been compiled, to be compiled again, possibly
352/// after it has been modified. Then the entry to the old copy is overwritten
353/// with a branch to the new copy. If there was no old copy, this acts
354/// just like JIT::getPointerToFunction().
355///
356void *JIT::recompileAndRelinkFunction(Function *F) {
357 void *OldAddr = getPointerToGlobalIfAvailable(F);
358
359 // If it's not already compiled there is no reason to patch it up.
360 if (OldAddr == 0) { return getPointerToFunction(F); }
361
362 // Delete the old function mapping.
363 addGlobalMapping(F, 0);
364
365 // Recodegen the function
366 runJITOnFunction(F);
367
368 // Update state, forward the old function to the new function.
369 void *Addr = getPointerToGlobalIfAvailable(F);
370 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
371 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
372 return Addr;
373}
374