blob: e95c8a0996cabff0df844c6d11eb8c6248c65835 [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//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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
Dan Gohman089efff2008-05-13 00:00:25 +000055namespace {
56
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057static struct RegisterJIT {
58 RegisterJIT() { JIT::Register(); }
59} JITRegistrator;
60
Dan Gohman089efff2008-05-13 00:00:25 +000061}
62
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063namespace llvm {
64 void LinkInJIT() {
65 }
66}
67
Anton Korobeynikov6556e9e2008-03-22 08:53:09 +000068#if defined (__GNUC__)
69extern "C" void __register_frame(void*);
70#endif
71
Chris Lattner4db98aa2007-12-06 01:34:04 +000072/// createJIT - This is the factory method for creating a JIT for the current
73/// machine, it does not fall back to the interpreter. This takes ownership
74/// of the module provider.
75ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
76 std::string *ErrorStr,
77 JITMemoryManager *JMM) {
78 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM);
79 if (!EE) return 0;
80
Anton Korobeynikov6556e9e2008-03-22 08:53:09 +000081 // Register routine for informing unwinding runtime about new EH frames
82#if defined(__GNUC__)
83 EE->InstallExceptionTableRegister(__register_frame);
84#endif
85
Chris Lattner4db98aa2007-12-06 01:34:04 +000086 // Make sure we can resolve symbols in the program as well. The zero arg
87 // to the function tells DynamicLibrary to load the program, not a library.
88 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
89 return EE;
90}
91
92JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
93 JITMemoryManager *JMM)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 : ExecutionEngine(MP), TM(tm), TJI(tji), jitstate(MP) {
95 setTargetData(TM.getTargetData());
96
97 // Initialize MCE
Chris Lattner4db98aa2007-12-06 01:34:04 +000098 MCE = createEmitter(*this, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099
100 // Add target data
101 MutexGuard locked(lock);
102 FunctionPassManager &PM = jitstate.getPM(locked);
103 PM.add(new TargetData(*TM.getTargetData()));
104
105 // Turn the machine code intermediate representation into bytes in memory that
106 // may be executed.
107 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
108 cerr << "Target does not support machine code emission!\n";
109 abort();
110 }
111
112 // Initialize passes.
113 PM.doInitialization();
114}
115
116JIT::~JIT() {
117 delete MCE;
118 delete &TM;
119}
120
121/// run - Start execution with the specified function and arguments.
122///
123GenericValue JIT::runFunction(Function *F,
124 const std::vector<GenericValue> &ArgValues) {
125 assert(F && "Function *F was null at entry to run()");
126
127 void *FPtr = getPointerToFunction(F);
128 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
129 const FunctionType *FTy = F->getFunctionType();
130 const Type *RetTy = FTy->getReturnType();
131
132 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
133 "Too many arguments passed into function!");
134 assert(FTy->getNumParams() == ArgValues.size() &&
135 "This doesn't support passing arguments through varargs (yet)!");
136
137 // Handle some common cases first. These cases correspond to common `main'
138 // prototypes.
Chris Lattnerbbf22702007-08-08 16:19:57 +0000139 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 switch (ArgValues.size()) {
141 case 3:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000142 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143 isa<PointerType>(FTy->getParamType(1)) &&
144 isa<PointerType>(FTy->getParamType(2))) {
145 int (*PF)(int, char **, const char **) =
146 (int(*)(int, char **, const char **))(intptr_t)FPtr;
147
148 // Call the function.
149 GenericValue rv;
150 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
151 (char **)GVTOP(ArgValues[1]),
152 (const char **)GVTOP(ArgValues[2])));
153 return rv;
154 }
155 break;
156 case 2:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000157 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 isa<PointerType>(FTy->getParamType(1))) {
159 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
160
161 // Call the function.
162 GenericValue rv;
163 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
164 (char **)GVTOP(ArgValues[1])));
165 return rv;
166 }
167 break;
168 case 1:
169 if (FTy->getNumParams() == 1 &&
Chris Lattnerbbf22702007-08-08 16:19:57 +0000170 FTy->getParamType(0) == Type::Int32Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 GenericValue rv;
172 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
173 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
174 return rv;
175 }
176 break;
177 }
178 }
179
180 // Handle cases where no arguments are passed first.
181 if (ArgValues.empty()) {
182 GenericValue rv;
183 switch (RetTy->getTypeID()) {
184 default: assert(0 && "Unknown return type for function call!");
185 case Type::IntegerTyID: {
186 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
187 if (BitWidth == 1)
188 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
189 else if (BitWidth <= 8)
190 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
191 else if (BitWidth <= 16)
192 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
193 else if (BitWidth <= 32)
194 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
195 else if (BitWidth <= 64)
196 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
197 else
198 assert(0 && "Integer types > 64 bits not supported");
199 return rv;
200 }
201 case Type::VoidTyID:
202 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
203 return rv;
204 case Type::FloatTyID:
205 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
206 return rv;
207 case Type::DoubleTyID:
208 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
209 return rv;
Dale Johannesenc560da62007-09-17 18:44:13 +0000210 case Type::X86_FP80TyID:
211 case Type::FP128TyID:
212 case Type::PPC_FP128TyID:
213 assert(0 && "long double not supported yet");
214 return rv;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 case Type::PointerTyID:
216 return PTOGV(((void*(*)())(intptr_t)FPtr)());
217 }
218 }
219
220 // Okay, this is not one of our quick and easy cases. Because we don't have a
221 // full FFI, we have to codegen a nullary stub function that just calls the
222 // function we are interested in, passing in constants for all of the
223 // arguments. Make this function and return.
224
225 // First, create the function.
226 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000227 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
228 F->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229
230 // Insert a basic block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000231 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232
233 // Convert all of the GenericValue arguments over to constants. Note that we
234 // currently don't support varargs.
235 SmallVector<Value*, 8> Args;
236 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
237 Constant *C = 0;
238 const Type *ArgTy = FTy->getParamType(i);
239 const GenericValue &AV = ArgValues[i];
240 switch (ArgTy->getTypeID()) {
241 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner5e0610f2008-04-20 00:41:09 +0000242 case Type::IntegerTyID:
243 C = ConstantInt::get(AV.IntVal);
244 break;
245 case Type::FloatTyID:
246 C = ConstantFP::get(APFloat(AV.FloatVal));
247 break;
248 case Type::DoubleTyID:
249 C = ConstantFP::get(APFloat(AV.DoubleVal));
250 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000251 case Type::PPC_FP128TyID:
252 case Type::X86_FP80TyID:
Chris Lattner5e0610f2008-04-20 00:41:09 +0000253 case Type::FP128TyID:
254 C = ConstantFP::get(APFloat(AV.IntVal));
255 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 case Type::PointerTyID:
257 void *ArgPtr = GVTOP(AV);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000258 if (sizeof(void*) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000260 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
263 break;
264 }
265 Args.push_back(C);
266 }
267
Gabor Greifd6da1d02008-04-06 20:25:17 +0000268 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(), "", StubBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 TheCall->setTailCall();
270 if (TheCall->getType() != Type::VoidTy)
Gabor Greifd6da1d02008-04-06 20:25:17 +0000271 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 else
Gabor Greifd6da1d02008-04-06 20:25:17 +0000273 ReturnInst::Create(StubBB); // Just return void.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274
275 // Finally, return the value returned by our nullary stub function.
276 return runFunction(Stub, std::vector<GenericValue>());
277}
278
279/// runJITOnFunction - Run the FunctionPassManager full of
280/// just-in-time compilation passes on F, hopefully filling in
281/// GlobalAddress[F] with the address of F's machine code.
282///
283void JIT::runJITOnFunction(Function *F) {
284 static bool isAlreadyCodeGenerating = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285
286 MutexGuard locked(lock);
Chris Lattner700fb1d2007-08-13 20:08:16 +0000287 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288
289 // JIT the function
290 isAlreadyCodeGenerating = true;
291 jitstate.getPM(locked).run(*F);
292 isAlreadyCodeGenerating = false;
293
294 // If the function referred to a global variable that had not yet been
295 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
296 // all of these globals now.
297 while (!jitstate.getPendingGlobals(locked).empty()) {
298 const GlobalVariable *GV = jitstate.getPendingGlobals(locked).back();
299 jitstate.getPendingGlobals(locked).pop_back();
300 EmitGlobalVariable(GV);
301 }
302}
303
304/// getPointerToFunction - This method is used to get the address of the
305/// specified function, compiling it if neccesary.
306///
307void *JIT::getPointerToFunction(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308
309 if (void *Addr = getPointerToGlobalIfAvailable(F))
310 return Addr; // Check if function already code gen'd
311
312 // Make sure we read in the function if it exists in this Module.
313 if (F->hasNotBeenReadFromBitcode()) {
314 // Determine the module provider this function is provided by.
315 Module *M = F->getParent();
316 ModuleProvider *MP = 0;
317 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
318 if (Modules[i]->getModule() == M) {
319 MP = Modules[i];
320 break;
321 }
322 }
323 assert(MP && "Function isn't in a module we know about!");
324
325 std::string ErrorMsg;
326 if (MP->materializeFunction(F, &ErrorMsg)) {
327 cerr << "Error reading function '" << F->getName()
328 << "' from bitcode file: " << ErrorMsg << "\n";
329 abort();
330 }
331 }
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000332
333 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
334 return Addr;
335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000337 MutexGuard locked(lock);
338
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 if (F->isDeclaration()) {
340 void *Addr = getPointerToNamedFunction(F->getName());
341 addGlobalMapping(F, Addr);
342 return Addr;
343 }
344
345 runJITOnFunction(F);
346
347 void *Addr = getPointerToGlobalIfAvailable(F);
348 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
349 return Addr;
350}
351
352/// getOrEmitGlobalVariable - Return the address of the specified global
353/// variable, possibly emitting it to memory if needed. This is used by the
354/// Emitter.
355void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
356 MutexGuard locked(lock);
357
358 void *Ptr = getPointerToGlobalIfAvailable(GV);
359 if (Ptr) return Ptr;
360
361 // If the global is external, just remember the address.
362 if (GV->isDeclaration()) {
Anton Korobeynikov52f44db2007-07-30 20:02:02 +0000363#if HAVE___DSO_HANDLE
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 if (GV->getName() == "__dso_handle")
365 return (void*)&__dso_handle;
366#endif
367 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
368 if (Ptr == 0) {
369 cerr << "Could not resolve external global address: "
370 << GV->getName() << "\n";
371 abort();
372 }
373 } else {
374 // If the global hasn't been emitted to memory yet, allocate space. We will
375 // actually initialize the global after current function has finished
376 // compilation.
377 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000378 size_t S = getTargetData()->getABITypeSize(GlobalType);
Duncan Sands935686e2008-01-29 06:23:44 +0000379 size_t A = getTargetData()->getPreferredAlignment(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 if (A <= 8) {
381 Ptr = malloc(S);
382 } else {
383 // Allocate S+A bytes of memory, then use an aligned pointer within that
384 // space.
385 Ptr = malloc(S+A);
386 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
387 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
388 }
389 jitstate.getPendingGlobals(locked).push_back(GV);
390 }
391 addGlobalMapping(GV, Ptr);
392 return Ptr;
393}
394
395
396/// recompileAndRelinkFunction - This method is used to force a function
397/// which has already been compiled, to be compiled again, possibly
398/// after it has been modified. Then the entry to the old copy is overwritten
399/// with a branch to the new copy. If there was no old copy, this acts
400/// just like JIT::getPointerToFunction().
401///
402void *JIT::recompileAndRelinkFunction(Function *F) {
403 void *OldAddr = getPointerToGlobalIfAvailable(F);
404
405 // If it's not already compiled there is no reason to patch it up.
406 if (OldAddr == 0) { return getPointerToFunction(F); }
407
408 // Delete the old function mapping.
409 addGlobalMapping(F, 0);
410
411 // Recodegen the function
412 runJITOnFunction(F);
413
414 // Update state, forward the old function to the new function.
415 void *Addr = getPointerToGlobalIfAvailable(F);
416 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
417 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
418 return Addr;
419}
420