blob: af8fd8fb7c0e7fb917b3fc38b3ae840e3c87688e [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Gabor Greifa99be512007-07-05 17:07:56 +000011// execution of LLVM bitcode 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"
Brian Gaeke97222942003-09-05 19:39:22 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000024#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
Owen Anderson07000c62006-05-12 06:33:49 +000026#include "llvm/Target/TargetData.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"
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000029
30#include "llvm/Config/config.h"
31
Chris Lattnerc19aade2003-12-08 08:06:28 +000032using namespace llvm;
Misha Brukmanabb027c2003-05-27 21:40:39 +000033
Nate Begemanb76ea742006-07-22 16:59:38 +000034#ifdef __APPLE__
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000035// Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
36// of atexit). It passes the address of linker generated symbol __dso_handle
37// to the function.
38// This configuration change happened at version 5330.
39# include <AvailabilityMacros.h>
40# if defined(MAC_OS_X_VERSION_10_4) && \
41 ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
42 (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
43 __APPLE_CC__ >= 5330))
44# ifndef HAVE___DSO_HANDLE
45# define HAVE___DSO_HANDLE 1
46# endif
47# endif
Evan Cheng5f42c552006-07-21 23:06:20 +000048#endif
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000049
50#if HAVE___DSO_HANDLE
51extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
Nate Begemanb76ea742006-07-22 16:59:38 +000052#endif
Evan Cheng5f42c552006-07-21 23:06:20 +000053
Dan Gohman844731a2008-05-13 00:00:25 +000054namespace {
55
Chris Lattner2fe4bb02006-03-22 06:07:50 +000056static struct RegisterJIT {
57 RegisterJIT() { JIT::Register(); }
58} JITRegistrator;
59
Dan Gohman844731a2008-05-13 00:00:25 +000060}
61
Jeff Cohen2f519142006-03-24 02:53:49 +000062namespace llvm {
63 void LinkInJIT() {
64 }
65}
66
Anton Korobeynikov299d9d72008-03-22 08:53:09 +000067#if defined (__GNUC__)
68extern "C" void __register_frame(void*);
69#endif
70
Chris Lattner34c94332007-12-06 01:34:04 +000071/// createJIT - This is the factory method for creating a JIT for the current
72/// machine, it does not fall back to the interpreter. This takes ownership
73/// of the module provider.
74ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
75 std::string *ErrorStr,
Evan Cheng502f20b2008-08-08 08:11:34 +000076 JITMemoryManager *JMM,
77 bool Fast) {
78 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
Chris Lattner34c94332007-12-06 01:34:04 +000079 if (!EE) return 0;
80
Anton Korobeynikov299d9d72008-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 Lattner34c94332007-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,
Evan Cheng502f20b2008-08-08 08:11:34 +000093 JITMemoryManager *JMM, bool Fast)
Nate Begemanf049e072008-05-21 16:34:48 +000094 : ExecutionEngine(MP), TM(tm), TJI(tji) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +000095 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +000096
Nate Begemanf049e072008-05-21 16:34:48 +000097 jitstate = new JITState(MP);
98
Misha Brukmanabb027c2003-05-27 21:40:39 +000099 // Initialize MCE
Chris Lattner34c94332007-12-06 01:34:04 +0000100 MCE = createEmitter(*this, JMM);
Misha Brukmanf976c852005-04-21 22:55:34 +0000101
Brian Gaeke50872d52004-04-14 17:45:52 +0000102 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +0000103 MutexGuard locked(lock);
Nate Begemanf049e072008-05-21 16:34:48 +0000104 FunctionPassManager &PM = jitstate->getPM(locked);
Chris Lattnerb93b0342006-05-04 21:18:40 +0000105 PM.add(new TargetData(*TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +0000106
Chris Lattner4d326fa2003-12-20 01:46:27 +0000107 // Turn the machine code intermediate representation into bytes in memory that
108 // may be executed.
Evan Cheng502f20b2008-08-08 08:11:34 +0000109 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
Bill Wendling832171c2006-12-07 20:04:42 +0000110 cerr << "Target does not support machine code emission!\n";
Chris Lattner4d326fa2003-12-20 01:46:27 +0000111 abort();
112 }
Chris Lattner1911fd42006-09-04 04:14:57 +0000113
114 // Initialize passes.
115 PM.doInitialization();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000116}
117
Chris Lattner4d326fa2003-12-20 01:46:27 +0000118JIT::~JIT() {
Nate Begemanf049e072008-05-21 16:34:48 +0000119 delete jitstate;
Chris Lattner4d326fa2003-12-20 01:46:27 +0000120 delete MCE;
121 delete &TM;
122}
123
Nate Begemanf049e072008-05-21 16:34:48 +0000124/// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
125/// removed the last ModuleProvider, we need re-initialize jitstate with a valid
126/// ModuleProvider.
127void JIT::addModuleProvider(ModuleProvider *MP) {
128 MutexGuard locked(lock);
129
130 if (Modules.empty()) {
131 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
132
133 jitstate = new JITState(MP);
134
135 FunctionPassManager &PM = jitstate->getPM(locked);
136 PM.add(new TargetData(*TM.getTargetData()));
137
138 // Turn the machine code intermediate representation into bytes in memory
139 // that may be executed.
140 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
141 cerr << "Target does not support machine code emission!\n";
142 abort();
143 }
144
145 // Initialize passes.
146 PM.doInitialization();
147 }
148
149 ExecutionEngine::addModuleProvider(MP);
150}
151
152/// removeModuleProvider - If we are removing the last ModuleProvider,
153/// invalidate the jitstate since the PassManager it contains references a
154/// released ModuleProvider.
155Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
156 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
157
158 MutexGuard locked(lock);
159 if (Modules.empty()) {
160 delete jitstate;
161 jitstate = 0;
162 }
163
164 return result;
165}
166
Brian Gaeke70975ee2003-09-05 18:42:01 +0000167/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +0000168///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000169GenericValue JIT::runFunction(Function *F,
170 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +0000171 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +0000172
173 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +0000174 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000175 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +0000176 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000177
Chris Lattnere5eab142004-08-15 23:53:06 +0000178 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
179 "Too many arguments passed into function!");
180 assert(FTy->getNumParams() == ArgValues.size() &&
181 "This doesn't support passing arguments through varargs (yet)!");
182
Misha Brukmanec843022004-10-22 23:35:57 +0000183 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +0000184 // prototypes.
Chris Lattner79e038a2007-08-08 16:19:57 +0000185 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000186 switch (ArgValues.size()) {
187 case 3:
Chris Lattner79e038a2007-08-08 16:19:57 +0000188 if (FTy->getParamType(0) == Type::Int32Ty &&
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000189 isa<PointerType>(FTy->getParamType(1)) &&
190 isa<PointerType>(FTy->getParamType(2))) {
191 int (*PF)(int, char **, const char **) =
Chris Lattner870286a2006-06-01 17:29:22 +0000192 (int(*)(int, char **, const char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000193
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000194 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +0000195 GenericValue rv;
Reid Spencer38f6a152007-03-06 03:11:31 +0000196 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
197 (char **)GVTOP(ArgValues[1]),
198 (const char **)GVTOP(ArgValues[2])));
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000199 return rv;
200 }
201 break;
Chris Lattner174f2262004-08-16 01:07:04 +0000202 case 2:
Chris Lattner79e038a2007-08-08 16:19:57 +0000203 if (FTy->getParamType(0) == Type::Int32Ty &&
Chris Lattner174f2262004-08-16 01:07:04 +0000204 isa<PointerType>(FTy->getParamType(1))) {
Chris Lattner870286a2006-06-01 17:29:22 +0000205 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000206
Chris Lattner174f2262004-08-16 01:07:04 +0000207 // Call the function.
208 GenericValue rv;
Reid Spencer38f6a152007-03-06 03:11:31 +0000209 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
210 (char **)GVTOP(ArgValues[1])));
Chris Lattner174f2262004-08-16 01:07:04 +0000211 return rv;
212 }
213 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000214 case 1:
215 if (FTy->getNumParams() == 1 &&
Chris Lattner79e038a2007-08-08 16:19:57 +0000216 FTy->getParamType(0) == Type::Int32Ty) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000217 GenericValue rv;
Chris Lattner870286a2006-06-01 17:29:22 +0000218 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
Reid Spencer38f6a152007-03-06 03:11:31 +0000219 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000220 return rv;
221 }
222 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000223 }
224 }
225
226 // Handle cases where no arguments are passed first.
227 if (ArgValues.empty()) {
228 GenericValue rv;
229 switch (RetTy->getTypeID()) {
230 default: assert(0 && "Unknown return type for function call!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000231 case Type::IntegerTyID: {
232 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
233 if (BitWidth == 1)
Reid Spencer38f6a152007-03-06 03:11:31 +0000234 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000235 else if (BitWidth <= 8)
Reid Spencer38f6a152007-03-06 03:11:31 +0000236 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000237 else if (BitWidth <= 16)
Reid Spencer38f6a152007-03-06 03:11:31 +0000238 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000239 else if (BitWidth <= 32)
Reid Spencer38f6a152007-03-06 03:11:31 +0000240 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000241 else if (BitWidth <= 64)
Reid Spencer38f6a152007-03-06 03:11:31 +0000242 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000243 else
244 assert(0 && "Integer types > 64 bits not supported");
Chris Lattnerd297aea2004-08-15 23:34:48 +0000245 return rv;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000246 }
Chris Lattnere5eab142004-08-15 23:53:06 +0000247 case Type::VoidTyID:
Reid Spencer38f6a152007-03-06 03:11:31 +0000248 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
Chris Lattnere5eab142004-08-15 23:53:06 +0000249 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000250 case Type::FloatTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000251 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000252 return rv;
253 case Type::DoubleTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000254 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000255 return rv;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000256 case Type::X86_FP80TyID:
257 case Type::FP128TyID:
258 case Type::PPC_FP128TyID:
259 assert(0 && "long double not supported yet");
260 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000261 case Type::PointerTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000262 return PTOGV(((void*(*)())(intptr_t)FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000263 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000264 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000265
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000266 // Okay, this is not one of our quick and easy cases. Because we don't have a
267 // full FFI, we have to codegen a nullary stub function that just calls the
268 // function we are interested in, passing in constants for all of the
269 // arguments. Make this function and return.
270
271 // First, create the function.
272 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greif051a9502008-04-06 20:25:17 +0000273 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
274 F->getParent());
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000275
276 // Insert a basic block.
Gabor Greif051a9502008-04-06 20:25:17 +0000277 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000278
279 // Convert all of the GenericValue arguments over to constants. Note that we
280 // currently don't support varargs.
Chris Lattner990b8492007-02-13 06:01:22 +0000281 SmallVector<Value*, 8> Args;
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000282 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
283 Constant *C = 0;
284 const Type *ArgTy = FTy->getParamType(i);
285 const GenericValue &AV = ArgValues[i];
286 switch (ArgTy->getTypeID()) {
287 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner02a260a2008-04-20 00:41:09 +0000288 case Type::IntegerTyID:
289 C = ConstantInt::get(AV.IntVal);
290 break;
291 case Type::FloatTyID:
292 C = ConstantFP::get(APFloat(AV.FloatVal));
293 break;
294 case Type::DoubleTyID:
295 C = ConstantFP::get(APFloat(AV.DoubleVal));
296 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000297 case Type::PPC_FP128TyID:
298 case Type::X86_FP80TyID:
Chris Lattner02a260a2008-04-20 00:41:09 +0000299 case Type::FP128TyID:
300 C = ConstantFP::get(APFloat(AV.IntVal));
301 break;
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000302 case Type::PointerTyID:
303 void *ArgPtr = GVTOP(AV);
Chris Lattner02a260a2008-04-20 00:41:09 +0000304 if (sizeof(void*) == 4)
Reid Spencere49661b2006-12-31 05:51:36 +0000305 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner02a260a2008-04-20 00:41:09 +0000306 else
Reid Spencere49661b2006-12-31 05:51:36 +0000307 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Reid Spencer15f46d62006-12-12 01:17:41 +0000308 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000309 break;
310 }
311 Args.push_back(C);
312 }
313
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000314 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
315 "", StubBB);
Chris Lattnera471e042005-05-06 06:48:54 +0000316 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000317 if (TheCall->getType() != Type::VoidTy)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000318 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000319 else
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000320 ReturnInst::Create(StubBB); // Just return void.
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000321
322 // Finally, return the value returned by our nullary stub function.
323 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000324}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000325
326/// runJITOnFunction - Run the FunctionPassManager full of
327/// just-in-time compilation passes on F, hopefully filling in
328/// GlobalAddress[F] with the address of F's machine code.
329///
330void JIT::runJITOnFunction(Function *F) {
331 static bool isAlreadyCodeGenerating = false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000332
Reid Spenceree448632005-07-12 15:51:55 +0000333 MutexGuard locked(lock);
Chris Lattner17f218e2007-08-13 20:08:16 +0000334 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Chris Lattner4d326fa2003-12-20 01:46:27 +0000335
336 // JIT the function
337 isAlreadyCodeGenerating = true;
Nate Begemanf049e072008-05-21 16:34:48 +0000338 jitstate->getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000339 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000340
341 // If the function referred to a global variable that had not yet been
342 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
343 // all of these globals now.
Nate Begemanf049e072008-05-21 16:34:48 +0000344 while (!jitstate->getPendingGlobals(locked).empty()) {
345 const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
346 jitstate->getPendingGlobals(locked).pop_back();
Chris Lattnerc07ed132003-12-20 03:36:47 +0000347 EmitGlobalVariable(GV);
348 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000349}
350
351/// getPointerToFunction - This method is used to get the address of the
352/// specified function, compiling it if neccesary.
353///
354void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000355
Chris Lattnerc07ed132003-12-20 03:36:47 +0000356 if (void *Addr = getPointerToGlobalIfAvailable(F))
357 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000358
Chris Lattnerfe854032006-08-16 01:24:12 +0000359 // Make sure we read in the function if it exists in this Module.
Gabor Greifa99be512007-07-05 17:07:56 +0000360 if (F->hasNotBeenReadFromBitcode()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000361 // Determine the module provider this function is provided by.
362 Module *M = F->getParent();
363 ModuleProvider *MP = 0;
364 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
365 if (Modules[i]->getModule() == M) {
366 MP = Modules[i];
367 break;
368 }
369 }
370 assert(MP && "Function isn't in a module we know about!");
371
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000372 std::string ErrorMsg;
373 if (MP->materializeFunction(F, &ErrorMsg)) {
Bill Wendling832171c2006-12-07 20:04:42 +0000374 cerr << "Error reading function '" << F->getName()
Gabor Greifa99be512007-07-05 17:07:56 +0000375 << "' from bitcode file: " << ErrorMsg << "\n";
Chris Lattner0050ef82004-11-15 23:18:09 +0000376 abort();
377 }
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000378 }
Nicolas Geoffrayfd7d9912008-04-20 08:33:02 +0000379
380 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
381 return Addr;
382 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000383
Nicolas Geoffrayfd7d9912008-04-20 08:33:02 +0000384 MutexGuard locked(lock);
385
Reid Spencer5cbf9852007-01-30 20:08:39 +0000386 if (F->isDeclaration()) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000387 void *Addr = getPointerToNamedFunction(F->getName());
388 addGlobalMapping(F, Addr);
389 return Addr;
390 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000391
392 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000393
394 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000395 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
396 return Addr;
397}
398
Chris Lattnerc07ed132003-12-20 03:36:47 +0000399/// getOrEmitGlobalVariable - Return the address of the specified global
400/// variable, possibly emitting it to memory if needed. This is used by the
401/// Emitter.
402void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000403 MutexGuard locked(lock);
404
Chris Lattnerc07ed132003-12-20 03:36:47 +0000405 void *Ptr = getPointerToGlobalIfAvailable(GV);
406 if (Ptr) return Ptr;
407
408 // If the global is external, just remember the address.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000409 if (GV->isDeclaration()) {
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +0000410#if HAVE___DSO_HANDLE
Evan Cheng5f42c552006-07-21 23:06:20 +0000411 if (GV->getName() == "__dso_handle")
412 return (void*)&__dso_handle;
Evan Chengb82ab942006-07-22 00:42:03 +0000413#endif
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000414 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Chris Lattnerc07ed132003-12-20 03:36:47 +0000415 if (Ptr == 0) {
Bill Wendling832171c2006-12-07 20:04:42 +0000416 cerr << "Could not resolve external global address: "
417 << GV->getName() << "\n";
Chris Lattnerc07ed132003-12-20 03:36:47 +0000418 abort();
Dale Johannesendd947ea2008-08-07 01:30:15 +0000419 addGlobalMapping(GV, Ptr);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000420 }
421 } else {
Dale Johannesendd947ea2008-08-07 01:30:15 +0000422 // If the global hasn't been emitted to memory yet, allocate space and
423 // emit it into memory. It goes in the same array as the generated
424 // code, jump tables, etc.
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000425 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000426 size_t S = getTargetData()->getABITypeSize(GlobalType);
Duncan Sandsd1025932008-01-29 06:23:44 +0000427 size_t A = getTargetData()->getPreferredAlignment(GV);
Dale Johannesendd947ea2008-08-07 01:30:15 +0000428 Ptr = MCE->allocateSpace(S, A);
429 addGlobalMapping(GV, Ptr);
430 EmitGlobalVariable(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000431 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000432 return Ptr;
433}
434
Chris Lattner4d326fa2003-12-20 01:46:27 +0000435/// recompileAndRelinkFunction - This method is used to force a function
436/// which has already been compiled, to be compiled again, possibly
437/// after it has been modified. Then the entry to the old copy is overwritten
438/// with a branch to the new copy. If there was no old copy, this acts
439/// just like JIT::getPointerToFunction().
440///
441void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000442 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000443
Chris Lattnerc07ed132003-12-20 03:36:47 +0000444 // If it's not already compiled there is no reason to patch it up.
445 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000446
Chris Lattnerc07ed132003-12-20 03:36:47 +0000447 // Delete the old function mapping.
448 addGlobalMapping(F, 0);
449
Chris Lattnerc07ed132003-12-20 03:36:47 +0000450 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000451 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000452
453 // Update state, forward the old function to the new function.
454 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000455 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
456 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
457 return Addr;
458}
Misha Brukman895eddf2004-11-07 23:58:46 +0000459