blob: 6940d85d757f8739886b71870f152feb23227f13 [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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/ExecutionEngine/GenericValue.h"
24#include "llvm/Support/MutexGuard.h"
25#include "llvm/System/DynamicLibrary.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetJITInfo.h"
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000029
30#include "llvm/Config/config.h"
31
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032using namespace llvm;
33
34#ifdef __APPLE__
Anton Korobeynikov52f44db2007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#endif
Anton Korobeynikov52f44db2007-07-30 20:02:02 +000049
50#if HAVE___DSO_HANDLE
51extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052#endif
53
Dan Gohman089efff2008-05-13 00:00:25 +000054namespace {
55
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056static struct RegisterJIT {
57 RegisterJIT() { JIT::Register(); }
58} JITRegistrator;
59
Dan Gohman089efff2008-05-13 00:00:25 +000060}
61
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062namespace llvm {
63 void LinkInJIT() {
64 }
65}
66
Nicolas Geoffray72dfb8e2008-08-28 22:34:49 +000067
Evan Chengaf8dce02009-02-01 06:42:27 +000068#if defined(__GNUC__) && !defined(__ARM__EABI__)
Nicolas Geoffray72dfb8e2008-08-28 22:34:49 +000069
70// libgcc defines the __register_frame function to dynamically register new
71// dwarf frames for exception handling. This functionality is not portable
72// across compilers and is only provided by GCC. We use the __register_frame
73// function here so that code generated by the JIT cooperates with the unwinding
74// runtime of libgcc. When JITting with exception handling enable, LLVM
75// generates dwarf frames and registers it to libgcc with __register_frame.
76//
77// The __register_frame function works with Linux.
78//
79// Unfortunately, this functionality seems to be in libgcc after the unwinding
80// library of libgcc for darwin was written. The code for darwin overwrites the
81// value updated by __register_frame with a value fetched with "keymgr".
82// "keymgr" is an obsolete functionality, which should be rewritten some day.
83// In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
84// need a workaround in LLVM which uses the "keymgr" to dynamically modify the
85// values of an opaque key, used by libgcc to find dwarf tables.
86
Anton Korobeynikov6556e9e2008-03-22 08:53:09 +000087extern "C" void __register_frame(void*);
Nicolas Geoffray72dfb8e2008-08-28 22:34:49 +000088
Evan Chengaf8dce02009-02-01 06:42:27 +000089#if defined(__APPLE__)
Nicolas Geoffray72dfb8e2008-08-28 22:34:49 +000090
91namespace {
92
93// LibgccObject - This is the structure defined in libgcc. There is no #include
94// provided for this structure, so we also define it here. libgcc calls it
95// "struct object". The structure is undocumented in libgcc.
96struct LibgccObject {
97 void *unused1;
98 void *unused2;
99 void *unused3;
100
101 /// frame - Pointer to the exception table.
102 void *frame;
103
104 /// encoding - The encoding of the object?
105 union {
106 struct {
107 unsigned long sorted : 1;
108 unsigned long from_array : 1;
109 unsigned long mixed_encoding : 1;
110 unsigned long encoding : 8;
111 unsigned long count : 21;
112 } b;
113 size_t i;
114 } encoding;
115
116 /// fde_end - libgcc defines this field only if some macro is defined. We
117 /// include this field even if it may not there, to make libgcc happy.
118 char *fde_end;
119
120 /// next - At least we know it's a chained list!
121 struct LibgccObject *next;
122};
123
124// "kemgr" stuff. Apparently, all frame tables are stored there.
125extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
126extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
127#define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
128
129/// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
130/// probably contains all dwarf tables that are loaded.
131struct LibgccObjectInfo {
132
133 /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
134 ///
135 struct LibgccObject* seenObjects;
136
137 /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
138 ///
139 struct LibgccObject* unseenObjects;
140
141 unsigned unused[2];
142};
143
144// for DW_EH_PE_omit
145#include "llvm/Support/Dwarf.h"
146
147/// darwin_register_frame - Since __register_frame does not work with darwin's
148/// libgcc,we provide our own function, which "tricks" libgcc by modifying the
149/// "Dwarf2 object list" key.
150void DarwinRegisterFrame(void* FrameBegin) {
151 // Get the key.
152 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
153 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
154
155 // Allocate a new LibgccObject to represent this frame. Deallocation of this
156 // object may be impossible: since darwin code in libgcc was written after
157 // the ability to dynamically register frames, things may crash if we
158 // deallocate it.
159 struct LibgccObject* ob = (struct LibgccObject*)
160 malloc(sizeof(struct LibgccObject));
161
162 // Do like libgcc for the values of the field.
163 ob->unused1 = (void *)-1;
164 ob->unused2 = 0;
165 ob->unused3 = 0;
166 ob->frame = FrameBegin;
167 ob->encoding.i = 0;
168 ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
169
170 // Put the info on both places, as libgcc uses the first or the the second
171 // field. Note that we rely on having two pointers here. If fde_end was a
172 // char, things would get complicated.
173 ob->fde_end = (char*)LOI->unseenObjects;
174 ob->next = LOI->unseenObjects;
175
176 // Update the key's unseenObjects list.
177 LOI->unseenObjects = ob;
178
179 // Finally update the "key". Apparently, libgcc requires it.
180 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
181 LOI);
182
183}
184
185}
186#endif // __APPLE__
187#endif // __GNUC__
Anton Korobeynikov6556e9e2008-03-22 08:53:09 +0000188
Chris Lattner4db98aa2007-12-06 01:34:04 +0000189/// createJIT - This is the factory method for creating a JIT for the current
190/// machine, it does not fall back to the interpreter. This takes ownership
191/// of the module provider.
192ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
193 std::string *ErrorStr,
Evan Chenga6394fc2008-08-08 08:11:34 +0000194 JITMemoryManager *JMM,
195 bool Fast) {
196 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
Chris Lattner4db98aa2007-12-06 01:34:04 +0000197 if (!EE) return 0;
198
Chris Lattner4db98aa2007-12-06 01:34:04 +0000199 // Make sure we can resolve symbols in the program as well. The zero arg
200 // to the function tells DynamicLibrary to load the program, not a library.
201 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
202 return EE;
203}
204
205JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
Evan Chenga6394fc2008-08-08 08:11:34 +0000206 JITMemoryManager *JMM, bool Fast)
Nate Begemanf7113d92008-05-21 16:34:48 +0000207 : ExecutionEngine(MP), TM(tm), TJI(tji) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 setTargetData(TM.getTargetData());
209
Nate Begemanf7113d92008-05-21 16:34:48 +0000210 jitstate = new JITState(MP);
211
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 // Initialize MCE
Chris Lattner4db98aa2007-12-06 01:34:04 +0000213 MCE = createEmitter(*this, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214
215 // Add target data
216 MutexGuard locked(lock);
Nate Begemanf7113d92008-05-21 16:34:48 +0000217 FunctionPassManager &PM = jitstate->getPM(locked);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 PM.add(new TargetData(*TM.getTargetData()));
219
220 // Turn the machine code intermediate representation into bytes in memory that
221 // may be executed.
Evan Chenga6394fc2008-08-08 08:11:34 +0000222 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 cerr << "Target does not support machine code emission!\n";
224 abort();
225 }
226
Nicolas Geoffraybed46f82008-08-18 14:53:56 +0000227 // Register routine for informing unwinding runtime about new EH frames
Evan Chengaf8dce02009-02-01 06:42:27 +0000228#if defined(__GNUC__) && !defined(__ARM_EABI__)
Nicolas Geoffray72dfb8e2008-08-28 22:34:49 +0000229#if defined(__APPLE__)
230 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
231 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
232
233 // The key is created on demand, and libgcc creates it the first time an
234 // exception occurs. Since we need the key to register frames, we create
235 // it now.
236 if (!LOI) {
237 LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo));
238 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
239 LOI);
240 }
241 InstallExceptionTableRegister(DarwinRegisterFrame);
242#else
Nicolas Geoffraybed46f82008-08-18 14:53:56 +0000243 InstallExceptionTableRegister(__register_frame);
Nicolas Geoffray72dfb8e2008-08-28 22:34:49 +0000244#endif // __APPLE__
245#endif // __GNUC__
Nicolas Geoffraybed46f82008-08-18 14:53:56 +0000246
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 // Initialize passes.
248 PM.doInitialization();
249}
250
251JIT::~JIT() {
Nate Begemanf7113d92008-05-21 16:34:48 +0000252 delete jitstate;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 delete MCE;
254 delete &TM;
255}
256
Nate Begemanf7113d92008-05-21 16:34:48 +0000257/// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
258/// removed the last ModuleProvider, we need re-initialize jitstate with a valid
259/// ModuleProvider.
260void JIT::addModuleProvider(ModuleProvider *MP) {
261 MutexGuard locked(lock);
262
263 if (Modules.empty()) {
264 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
265
266 jitstate = new JITState(MP);
267
268 FunctionPassManager &PM = jitstate->getPM(locked);
269 PM.add(new TargetData(*TM.getTargetData()));
270
271 // Turn the machine code intermediate representation into bytes in memory
272 // that may be executed.
273 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
274 cerr << "Target does not support machine code emission!\n";
275 abort();
276 }
277
278 // Initialize passes.
279 PM.doInitialization();
280 }
281
282 ExecutionEngine::addModuleProvider(MP);
283}
284
285/// removeModuleProvider - If we are removing the last ModuleProvider,
286/// invalidate the jitstate since the PassManager it contains references a
287/// released ModuleProvider.
288Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
289 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
290
291 MutexGuard locked(lock);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000292
293 if (jitstate->getMP() == MP) {
Nate Begemanf7113d92008-05-21 16:34:48 +0000294 delete jitstate;
295 jitstate = 0;
296 }
297
Nate Begeman7b1a8472009-02-18 08:31:02 +0000298 if (!jitstate && !Modules.empty()) {
299 jitstate = new JITState(Modules[0]);
300
301 FunctionPassManager &PM = jitstate->getPM(locked);
302 PM.add(new TargetData(*TM.getTargetData()));
303
304 // Turn the machine code intermediate representation into bytes in memory
305 // that may be executed.
306 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
307 cerr << "Target does not support machine code emission!\n";
308 abort();
309 }
310
311 // Initialize passes.
312 PM.doInitialization();
313 }
Nate Begemanf7113d92008-05-21 16:34:48 +0000314 return result;
315}
316
Nate Begemanb34045e2009-01-23 19:27:28 +0000317/// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
318/// and deletes the ModuleProvider and owned Module. Avoids materializing
319/// the underlying module.
320void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
321 ExecutionEngine::deleteModuleProvider(MP, E);
322
323 MutexGuard locked(lock);
Nate Begeman7b1a8472009-02-18 08:31:02 +0000324
325 if (jitstate->getMP() == MP) {
Nate Begemanb34045e2009-01-23 19:27:28 +0000326 delete jitstate;
327 jitstate = 0;
328 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000329
330 if (!jitstate && !Modules.empty()) {
331 jitstate = new JITState(Modules[0]);
332
333 FunctionPassManager &PM = jitstate->getPM(locked);
334 PM.add(new TargetData(*TM.getTargetData()));
335
336 // Turn the machine code intermediate representation into bytes in memory
337 // that may be executed.
338 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
339 cerr << "Target does not support machine code emission!\n";
340 abort();
341 }
342
343 // Initialize passes.
344 PM.doInitialization();
345 }
Nate Begemanb34045e2009-01-23 19:27:28 +0000346}
347
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348/// run - Start execution with the specified function and arguments.
349///
350GenericValue JIT::runFunction(Function *F,
351 const std::vector<GenericValue> &ArgValues) {
352 assert(F && "Function *F was null at entry to run()");
353
354 void *FPtr = getPointerToFunction(F);
355 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
356 const FunctionType *FTy = F->getFunctionType();
357 const Type *RetTy = FTy->getReturnType();
358
359 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
360 "Too many arguments passed into function!");
361 assert(FTy->getNumParams() == ArgValues.size() &&
362 "This doesn't support passing arguments through varargs (yet)!");
363
364 // Handle some common cases first. These cases correspond to common `main'
365 // prototypes.
Chris Lattnerbbf22702007-08-08 16:19:57 +0000366 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 switch (ArgValues.size()) {
368 case 3:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000369 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 isa<PointerType>(FTy->getParamType(1)) &&
371 isa<PointerType>(FTy->getParamType(2))) {
372 int (*PF)(int, char **, const char **) =
373 (int(*)(int, char **, const char **))(intptr_t)FPtr;
374
375 // Call the function.
376 GenericValue rv;
377 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
378 (char **)GVTOP(ArgValues[1]),
379 (const char **)GVTOP(ArgValues[2])));
380 return rv;
381 }
382 break;
383 case 2:
Chris Lattnerbbf22702007-08-08 16:19:57 +0000384 if (FTy->getParamType(0) == Type::Int32Ty &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 isa<PointerType>(FTy->getParamType(1))) {
386 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
387
388 // Call the function.
389 GenericValue rv;
390 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
391 (char **)GVTOP(ArgValues[1])));
392 return rv;
393 }
394 break;
395 case 1:
396 if (FTy->getNumParams() == 1 &&
Chris Lattnerbbf22702007-08-08 16:19:57 +0000397 FTy->getParamType(0) == Type::Int32Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 GenericValue rv;
399 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
400 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
401 return rv;
402 }
403 break;
404 }
405 }
406
407 // Handle cases where no arguments are passed first.
408 if (ArgValues.empty()) {
409 GenericValue rv;
410 switch (RetTy->getTypeID()) {
411 default: assert(0 && "Unknown return type for function call!");
412 case Type::IntegerTyID: {
413 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
414 if (BitWidth == 1)
415 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
416 else if (BitWidth <= 8)
417 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
418 else if (BitWidth <= 16)
419 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
420 else if (BitWidth <= 32)
421 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
422 else if (BitWidth <= 64)
423 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
424 else
425 assert(0 && "Integer types > 64 bits not supported");
426 return rv;
427 }
428 case Type::VoidTyID:
429 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
430 return rv;
431 case Type::FloatTyID:
432 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
433 return rv;
434 case Type::DoubleTyID:
435 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
436 return rv;
Dale Johannesenc560da62007-09-17 18:44:13 +0000437 case Type::X86_FP80TyID:
438 case Type::FP128TyID:
439 case Type::PPC_FP128TyID:
440 assert(0 && "long double not supported yet");
441 return rv;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 case Type::PointerTyID:
443 return PTOGV(((void*(*)())(intptr_t)FPtr)());
444 }
445 }
446
447 // Okay, this is not one of our quick and easy cases. Because we don't have a
448 // full FFI, we have to codegen a nullary stub function that just calls the
449 // function we are interested in, passing in constants for all of the
450 // arguments. Make this function and return.
451
452 // First, create the function.
453 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000454 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
455 F->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456
457 // Insert a basic block.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000458 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459
460 // Convert all of the GenericValue arguments over to constants. Note that we
461 // currently don't support varargs.
462 SmallVector<Value*, 8> Args;
463 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
464 Constant *C = 0;
465 const Type *ArgTy = FTy->getParamType(i);
466 const GenericValue &AV = ArgValues[i];
467 switch (ArgTy->getTypeID()) {
468 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner5e0610f2008-04-20 00:41:09 +0000469 case Type::IntegerTyID:
470 C = ConstantInt::get(AV.IntVal);
471 break;
472 case Type::FloatTyID:
473 C = ConstantFP::get(APFloat(AV.FloatVal));
474 break;
475 case Type::DoubleTyID:
476 C = ConstantFP::get(APFloat(AV.DoubleVal));
477 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000478 case Type::PPC_FP128TyID:
479 case Type::X86_FP80TyID:
Chris Lattner5e0610f2008-04-20 00:41:09 +0000480 case Type::FP128TyID:
481 C = ConstantFP::get(APFloat(AV.IntVal));
482 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 case Type::PointerTyID:
484 void *ArgPtr = GVTOP(AV);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000485 if (sizeof(void*) == 4)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner5e0610f2008-04-20 00:41:09 +0000487 else
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000489 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
490 break;
491 }
492 Args.push_back(C);
493 }
494
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000495 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
496 "", StubBB);
Chris Lattner62ef4f12008-11-23 08:00:11 +0000497 TheCall->setCallingConv(F->getCallingConv());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498 TheCall->setTailCall();
499 if (TheCall->getType() != Type::VoidTy)
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000500 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 else
Gabor Greifb91ea9d2008-05-15 10:04:30 +0000502 ReturnInst::Create(StubBB); // Just return void.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503
504 // Finally, return the value returned by our nullary stub function.
505 return runFunction(Stub, std::vector<GenericValue>());
506}
507
508/// runJITOnFunction - Run the FunctionPassManager full of
509/// just-in-time compilation passes on F, hopefully filling in
510/// GlobalAddress[F] with the address of F's machine code.
511///
512void JIT::runJITOnFunction(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 MutexGuard locked(lock);
Dan Gohman2970af12009-02-06 21:25:08 +0000514 runJITOnFunctionUnlocked(F, locked);
515}
516
517void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
518 static bool isAlreadyCodeGenerating = false;
Chris Lattner700fb1d2007-08-13 20:08:16 +0000519 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520
521 // JIT the function
522 isAlreadyCodeGenerating = true;
Nate Begemanf7113d92008-05-21 16:34:48 +0000523 jitstate->getPM(locked).run(*F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 isAlreadyCodeGenerating = false;
525
Nate Begeman7b1a8472009-02-18 08:31:02 +0000526 // If the function referred to another function that had not yet been
527 // read from bitcode, but we are jitting non-lazily, emit it now.
528 while (!jitstate->getPendingFunctions(locked).empty()) {
529 Function *PF = jitstate->getPendingFunctions(locked).back();
530 jitstate->getPendingFunctions(locked).pop_back();
531
532 // JIT the function
533 isAlreadyCodeGenerating = true;
534 jitstate->getPM(locked).run(*PF);
535 isAlreadyCodeGenerating = false;
536
537 // Now that the function has been jitted, ask the JITEmitter to rewrite
538 // the stub with real address of the function.
539 updateFunctionStub(PF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 }
Nate Begeman7b1a8472009-02-18 08:31:02 +0000541
542 // If the JIT is configured to emit info so that dlsym can be used to
543 // rewrite stubs to external globals, do so now.
544 if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
545 updateDlsymStubTable();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546}
547
548/// getPointerToFunction - This method is used to get the address of the
549/// specified function, compiling it if neccesary.
550///
551void *JIT::getPointerToFunction(Function *F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552
553 if (void *Addr = getPointerToGlobalIfAvailable(F))
554 return Addr; // Check if function already code gen'd
555
556 // Make sure we read in the function if it exists in this Module.
557 if (F->hasNotBeenReadFromBitcode()) {
558 // Determine the module provider this function is provided by.
559 Module *M = F->getParent();
560 ModuleProvider *MP = 0;
561 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
562 if (Modules[i]->getModule() == M) {
563 MP = Modules[i];
564 break;
565 }
566 }
567 assert(MP && "Function isn't in a module we know about!");
568
569 std::string ErrorMsg;
570 if (MP->materializeFunction(F, &ErrorMsg)) {
571 cerr << "Error reading function '" << F->getName()
572 << "' from bitcode file: " << ErrorMsg << "\n";
573 abort();
574 }
Mon P Wanga21f8d42008-10-10 01:47:42 +0000575
Dan Gohman0ae39622009-01-05 05:32:42 +0000576 // Now retry to get the address.
577 if (void *Addr = getPointerToGlobalIfAvailable(F))
578 return Addr;
Nicolas Geoffray8ae32352008-04-20 08:33:02 +0000579 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580
Mon P Wang659eb722008-10-10 18:07:10 +0000581 MutexGuard locked(lock);
582
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 if (F->isDeclaration()) {
Dan Gohman0ae39622009-01-05 05:32:42 +0000584 bool AbortOnFailure = F->getLinkage() != GlobalValue::ExternalWeakLinkage;
585 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 addGlobalMapping(F, Addr);
587 return Addr;
588 }
589
Dan Gohman2970af12009-02-06 21:25:08 +0000590 runJITOnFunctionUnlocked(F, locked);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000591
592 void *Addr = getPointerToGlobalIfAvailable(F);
593 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
594 return Addr;
595}
596
597/// getOrEmitGlobalVariable - Return the address of the specified global
598/// variable, possibly emitting it to memory if needed. This is used by the
599/// Emitter.
600void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
601 MutexGuard locked(lock);
602
603 void *Ptr = getPointerToGlobalIfAvailable(GV);
604 if (Ptr) return Ptr;
605
606 // If the global is external, just remember the address.
607 if (GV->isDeclaration()) {
Anton Korobeynikov52f44db2007-07-30 20:02:02 +0000608#if HAVE___DSO_HANDLE
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609 if (GV->getName() == "__dso_handle")
610 return (void*)&__dso_handle;
611#endif
612 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
613 if (Ptr == 0) {
614 cerr << "Could not resolve external global address: "
615 << GV->getName() << "\n";
616 abort();
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000617 addGlobalMapping(GV, Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 }
619 } else {
Evan Cheng49777792009-01-16 19:14:49 +0000620 // GlobalVariable's which are not "constant" will cause trouble in a server
621 // situation. It's returned in the same block of memory as code which may
622 // not be writable.
623 if (isGVCompilationDisabled() && !GV->isConstant()) {
Evan Chenga134caf2008-12-09 07:31:49 +0000624 cerr << "Compilation of non-internal GlobalValue is disabled!\n";
Evan Cheng9b8bc832008-09-24 16:25:55 +0000625 abort();
626 }
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000627 // If the global hasn't been emitted to memory yet, allocate space and
628 // emit it into memory. It goes in the same array as the generated
629 // code, jump tables, etc.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000631 size_t S = getTargetData()->getTypePaddedSize(GlobalType);
Duncan Sands935686e2008-01-29 06:23:44 +0000632 size_t A = getTargetData()->getPreferredAlignment(GV);
Nicolas Geoffray46fa1532008-10-25 15:41:43 +0000633 if (GV->isThreadLocal()) {
634 MutexGuard locked(lock);
635 Ptr = TJI.allocateThreadLocalMemory(S);
Evan Cheng4a8e3b42008-11-04 09:30:48 +0000636 } else if (TJI.allocateSeparateGVMemory()) {
637 if (A <= 8) {
638 Ptr = malloc(S);
639 } else {
640 // Allocate S+A bytes of memory, then use an aligned pointer within that
641 // space.
642 Ptr = malloc(S+A);
643 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
644 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
645 }
Nicolas Geoffray46fa1532008-10-25 15:41:43 +0000646 } else {
647 Ptr = MCE->allocateSpace(S, A);
648 }
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000649 addGlobalMapping(GV, Ptr);
650 EmitGlobalVariable(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 return Ptr;
653}
654
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655/// recompileAndRelinkFunction - This method is used to force a function
656/// which has already been compiled, to be compiled again, possibly
657/// after it has been modified. Then the entry to the old copy is overwritten
658/// with a branch to the new copy. If there was no old copy, this acts
659/// just like JIT::getPointerToFunction().
660///
661void *JIT::recompileAndRelinkFunction(Function *F) {
662 void *OldAddr = getPointerToGlobalIfAvailable(F);
663
664 // If it's not already compiled there is no reason to patch it up.
665 if (OldAddr == 0) { return getPointerToFunction(F); }
666
667 // Delete the old function mapping.
668 addGlobalMapping(F, 0);
669
670 // Recodegen the function
671 runJITOnFunction(F);
672
673 // Update state, forward the old function to the new function.
674 void *Addr = getPointerToGlobalIfAvailable(F);
675 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
676 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
677 return Addr;
678}
679
Nicolas Geoffray46fa1532008-10-25 15:41:43 +0000680/// getMemoryForGV - This method abstracts memory allocation of global
681/// variable so that the JIT can allocate thread local variables depending
682/// on the target.
683///
684char* JIT::getMemoryForGV(const GlobalVariable* GV) {
685 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000686 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
Nicolas Geoffray46fa1532008-10-25 15:41:43 +0000687 if (GV->isThreadLocal()) {
688 MutexGuard locked(lock);
689 return TJI.allocateThreadLocalMemory(GVSize);
690 } else {
691 return new char[GVSize];
692 }
693}
Nate Begeman7b1a8472009-02-18 08:31:02 +0000694
695void JIT::addPendingFunction(Function *F) {
696 MutexGuard locked(lock);
697 jitstate->getPendingFunctions(locked).push_back(F);
698}