blob: 57201493e07fda96687fffca5d1e7c639d8f139b [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"
Owen Anderson07000c62006-05-12 06:33:49 +000024#include "llvm/Target/TargetData.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000025#include "llvm/Target/TargetMachine.h"
Chris Lattner4d326fa2003-12-20 01:46:27 +000026#include "llvm/Target/TargetJITInfo.h"
Chris Lattner44e3dd12009-03-03 20:10:23 +000027#include "llvm/Support/Dwarf.h"
28#include "llvm/Support/MutexGuard.h"
29#include "llvm/System/DynamicLibrary.h"
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +000030#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
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000067
Evan Cheng2d5424d2009-02-01 06:42:27 +000068#if defined(__GNUC__) && !defined(__ARM__EABI__)
Nicolas Geoffrayd046fc62008-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 Korobeynikov299d9d72008-03-22 08:53:09 +000087extern "C" void __register_frame(void*);
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000088
Evan Cheng00f16282009-04-14 22:31:59 +000089#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
90# define USE_KEYMGR 1
91#else
92# define USE_KEYMGR 0
93#endif
94
95#if USE_KEYMGR
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +000096
97namespace {
98
99// LibgccObject - This is the structure defined in libgcc. There is no #include
100// provided for this structure, so we also define it here. libgcc calls it
101// "struct object". The structure is undocumented in libgcc.
102struct LibgccObject {
103 void *unused1;
104 void *unused2;
105 void *unused3;
106
107 /// frame - Pointer to the exception table.
108 void *frame;
109
110 /// encoding - The encoding of the object?
111 union {
112 struct {
113 unsigned long sorted : 1;
114 unsigned long from_array : 1;
115 unsigned long mixed_encoding : 1;
116 unsigned long encoding : 8;
117 unsigned long count : 21;
118 } b;
119 size_t i;
120 } encoding;
121
122 /// fde_end - libgcc defines this field only if some macro is defined. We
123 /// include this field even if it may not there, to make libgcc happy.
124 char *fde_end;
125
126 /// next - At least we know it's a chained list!
127 struct LibgccObject *next;
128};
129
130// "kemgr" stuff. Apparently, all frame tables are stored there.
131extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
132extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
133#define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
134
135/// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
136/// probably contains all dwarf tables that are loaded.
137struct LibgccObjectInfo {
138
139 /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
140 ///
141 struct LibgccObject* seenObjects;
142
143 /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
144 ///
145 struct LibgccObject* unseenObjects;
146
147 unsigned unused[2];
148};
149
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000150/// darwin_register_frame - Since __register_frame does not work with darwin's
151/// libgcc,we provide our own function, which "tricks" libgcc by modifying the
152/// "Dwarf2 object list" key.
153void DarwinRegisterFrame(void* FrameBegin) {
154 // Get the key.
Chris Lattner44e3dd12009-03-03 20:10:23 +0000155 LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000156 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
Chris Lattner44e3dd12009-03-03 20:10:23 +0000157 assert(LOI && "This should be preallocated by the runtime");
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000158
159 // Allocate a new LibgccObject to represent this frame. Deallocation of this
160 // object may be impossible: since darwin code in libgcc was written after
161 // the ability to dynamically register frames, things may crash if we
162 // deallocate it.
163 struct LibgccObject* ob = (struct LibgccObject*)
164 malloc(sizeof(struct LibgccObject));
165
166 // Do like libgcc for the values of the field.
167 ob->unused1 = (void *)-1;
168 ob->unused2 = 0;
169 ob->unused3 = 0;
170 ob->frame = FrameBegin;
171 ob->encoding.i = 0;
172 ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
173
174 // Put the info on both places, as libgcc uses the first or the the second
175 // field. Note that we rely on having two pointers here. If fde_end was a
176 // char, things would get complicated.
177 ob->fde_end = (char*)LOI->unseenObjects;
178 ob->next = LOI->unseenObjects;
179
180 // Update the key's unseenObjects list.
181 LOI->unseenObjects = ob;
182
183 // Finally update the "key". Apparently, libgcc requires it.
184 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
185 LOI);
186
187}
188
189}
190#endif // __APPLE__
191#endif // __GNUC__
Anton Korobeynikov299d9d72008-03-22 08:53:09 +0000192
Chris Lattner34c94332007-12-06 01:34:04 +0000193/// createJIT - This is the factory method for creating a JIT for the current
194/// machine, it does not fall back to the interpreter. This takes ownership
195/// of the module provider.
196ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
197 std::string *ErrorStr,
Evan Cheng502f20b2008-08-08 08:11:34 +0000198 JITMemoryManager *JMM,
199 bool Fast) {
200 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
Chris Lattner34c94332007-12-06 01:34:04 +0000201 if (!EE) return 0;
202
Chris Lattner34c94332007-12-06 01:34:04 +0000203 // Make sure we can resolve symbols in the program as well. The zero arg
204 // to the function tells DynamicLibrary to load the program, not a library.
205 sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
206 return EE;
207}
208
209JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
Evan Cheng502f20b2008-08-08 08:11:34 +0000210 JITMemoryManager *JMM, bool Fast)
Nate Begemanf049e072008-05-21 16:34:48 +0000211 : ExecutionEngine(MP), TM(tm), TJI(tji) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000212 setTargetData(TM.getTargetData());
Misha Brukmanabb027c2003-05-27 21:40:39 +0000213
Nate Begemanf049e072008-05-21 16:34:48 +0000214 jitstate = new JITState(MP);
215
Misha Brukmanabb027c2003-05-27 21:40:39 +0000216 // Initialize MCE
Chris Lattner34c94332007-12-06 01:34:04 +0000217 MCE = createEmitter(*this, JMM);
Misha Brukmanf976c852005-04-21 22:55:34 +0000218
Brian Gaeke50872d52004-04-14 17:45:52 +0000219 // Add target data
Reid Spenceree448632005-07-12 15:51:55 +0000220 MutexGuard locked(lock);
Nate Begemanf049e072008-05-21 16:34:48 +0000221 FunctionPassManager &PM = jitstate->getPM(locked);
Chris Lattnerb93b0342006-05-04 21:18:40 +0000222 PM.add(new TargetData(*TM.getTargetData()));
Brian Gaeke50872d52004-04-14 17:45:52 +0000223
Chris Lattner4d326fa2003-12-20 01:46:27 +0000224 // Turn the machine code intermediate representation into bytes in memory that
225 // may be executed.
Evan Cheng502f20b2008-08-08 08:11:34 +0000226 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
Bill Wendling832171c2006-12-07 20:04:42 +0000227 cerr << "Target does not support machine code emission!\n";
Chris Lattner4d326fa2003-12-20 01:46:27 +0000228 abort();
229 }
Chris Lattner1911fd42006-09-04 04:14:57 +0000230
Nicolas Geoffraya7ec87c2008-08-18 14:53:56 +0000231 // Register routine for informing unwinding runtime about new EH frames
Evan Cheng2d5424d2009-02-01 06:42:27 +0000232#if defined(__GNUC__) && !defined(__ARM_EABI__)
Evan Cheng00f16282009-04-14 22:31:59 +0000233#if USE_KEYMGR
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000234 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
235 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
236
237 // The key is created on demand, and libgcc creates it the first time an
238 // exception occurs. Since we need the key to register frames, we create
239 // it now.
240 if (!LOI) {
241 LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo));
242 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
243 LOI);
244 }
245 InstallExceptionTableRegister(DarwinRegisterFrame);
246#else
Nicolas Geoffraya7ec87c2008-08-18 14:53:56 +0000247 InstallExceptionTableRegister(__register_frame);
Nicolas Geoffrayd046fc62008-08-28 22:34:49 +0000248#endif // __APPLE__
249#endif // __GNUC__
Nicolas Geoffraya7ec87c2008-08-18 14:53:56 +0000250
Chris Lattner1911fd42006-09-04 04:14:57 +0000251 // Initialize passes.
252 PM.doInitialization();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000253}
254
Chris Lattner4d326fa2003-12-20 01:46:27 +0000255JIT::~JIT() {
Nate Begemanf049e072008-05-21 16:34:48 +0000256 delete jitstate;
Chris Lattner4d326fa2003-12-20 01:46:27 +0000257 delete MCE;
258 delete &TM;
259}
260
Nate Begemanf049e072008-05-21 16:34:48 +0000261/// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
262/// removed the last ModuleProvider, we need re-initialize jitstate with a valid
263/// ModuleProvider.
264void JIT::addModuleProvider(ModuleProvider *MP) {
265 MutexGuard locked(lock);
266
267 if (Modules.empty()) {
268 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
269
270 jitstate = new JITState(MP);
271
272 FunctionPassManager &PM = jitstate->getPM(locked);
273 PM.add(new TargetData(*TM.getTargetData()));
274
275 // Turn the machine code intermediate representation into bytes in memory
276 // that may be executed.
277 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
278 cerr << "Target does not support machine code emission!\n";
279 abort();
280 }
281
282 // Initialize passes.
283 PM.doInitialization();
284 }
285
286 ExecutionEngine::addModuleProvider(MP);
287}
288
289/// removeModuleProvider - If we are removing the last ModuleProvider,
290/// invalidate the jitstate since the PassManager it contains references a
291/// released ModuleProvider.
292Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
293 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
294
295 MutexGuard locked(lock);
Nate Begemand6b7a242009-02-18 08:31:02 +0000296
297 if (jitstate->getMP() == MP) {
Nate Begemanf049e072008-05-21 16:34:48 +0000298 delete jitstate;
299 jitstate = 0;
300 }
301
Nate Begemand6b7a242009-02-18 08:31:02 +0000302 if (!jitstate && !Modules.empty()) {
303 jitstate = new JITState(Modules[0]);
304
305 FunctionPassManager &PM = jitstate->getPM(locked);
306 PM.add(new TargetData(*TM.getTargetData()));
307
308 // Turn the machine code intermediate representation into bytes in memory
309 // that may be executed.
310 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
311 cerr << "Target does not support machine code emission!\n";
312 abort();
313 }
314
315 // Initialize passes.
316 PM.doInitialization();
317 }
Nate Begemanf049e072008-05-21 16:34:48 +0000318 return result;
319}
320
Nate Begeman60789e42009-01-23 19:27:28 +0000321/// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
322/// and deletes the ModuleProvider and owned Module. Avoids materializing
323/// the underlying module.
324void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
325 ExecutionEngine::deleteModuleProvider(MP, E);
326
327 MutexGuard locked(lock);
Nate Begemand6b7a242009-02-18 08:31:02 +0000328
329 if (jitstate->getMP() == MP) {
Nate Begeman60789e42009-01-23 19:27:28 +0000330 delete jitstate;
331 jitstate = 0;
332 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000333
334 if (!jitstate && !Modules.empty()) {
335 jitstate = new JITState(Modules[0]);
336
337 FunctionPassManager &PM = jitstate->getPM(locked);
338 PM.add(new TargetData(*TM.getTargetData()));
339
340 // Turn the machine code intermediate representation into bytes in memory
341 // that may be executed.
342 if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
343 cerr << "Target does not support machine code emission!\n";
344 abort();
345 }
346
347 // Initialize passes.
348 PM.doInitialization();
349 }
Nate Begeman60789e42009-01-23 19:27:28 +0000350}
351
Brian Gaeke70975ee2003-09-05 18:42:01 +0000352/// run - Start execution with the specified function and arguments.
Chris Lattner05a1a302003-08-21 21:32:12 +0000353///
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000354GenericValue JIT::runFunction(Function *F,
355 const std::vector<GenericValue> &ArgValues) {
Chris Lattnerb47130c2004-08-15 23:29:50 +0000356 assert(F && "Function *F was null at entry to run()");
Chris Lattnerb47130c2004-08-15 23:29:50 +0000357
358 void *FPtr = getPointerToFunction(F);
Chris Lattner7c45d782004-08-15 23:31:43 +0000359 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000360 const FunctionType *FTy = F->getFunctionType();
Chris Lattnere5eab142004-08-15 23:53:06 +0000361 const Type *RetTy = FTy->getReturnType();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000362
Dan Gohman07ab52b2009-02-19 02:55:18 +0000363 assert((FTy->getNumParams() == ArgValues.size() ||
364 (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
365 "Wrong number of arguments passed into function!");
Chris Lattnere5eab142004-08-15 23:53:06 +0000366 assert(FTy->getNumParams() == ArgValues.size() &&
367 "This doesn't support passing arguments through varargs (yet)!");
368
Misha Brukmanec843022004-10-22 23:35:57 +0000369 // Handle some common cases first. These cases correspond to common `main'
Chris Lattnere5eab142004-08-15 23:53:06 +0000370 // prototypes.
Chris Lattner79e038a2007-08-08 16:19:57 +0000371 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000372 switch (ArgValues.size()) {
373 case 3:
Chris Lattner79e038a2007-08-08 16:19:57 +0000374 if (FTy->getParamType(0) == Type::Int32Ty &&
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000375 isa<PointerType>(FTy->getParamType(1)) &&
376 isa<PointerType>(FTy->getParamType(2))) {
377 int (*PF)(int, char **, const char **) =
Chris Lattner870286a2006-06-01 17:29:22 +0000378 (int(*)(int, char **, const char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000379
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000380 // Call the function.
Chris Lattnere5eab142004-08-15 23:53:06 +0000381 GenericValue rv;
Reid Spencer38f6a152007-03-06 03:11:31 +0000382 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
383 (char **)GVTOP(ArgValues[1]),
384 (const char **)GVTOP(ArgValues[2])));
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000385 return rv;
386 }
387 break;
Chris Lattner174f2262004-08-16 01:07:04 +0000388 case 2:
Chris Lattner79e038a2007-08-08 16:19:57 +0000389 if (FTy->getParamType(0) == Type::Int32Ty &&
Chris Lattner174f2262004-08-16 01:07:04 +0000390 isa<PointerType>(FTy->getParamType(1))) {
Chris Lattner870286a2006-06-01 17:29:22 +0000391 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
Misha Brukmanec843022004-10-22 23:35:57 +0000392
Chris Lattner174f2262004-08-16 01:07:04 +0000393 // Call the function.
394 GenericValue rv;
Reid Spencer38f6a152007-03-06 03:11:31 +0000395 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
396 (char **)GVTOP(ArgValues[1])));
Chris Lattner174f2262004-08-16 01:07:04 +0000397 return rv;
398 }
399 break;
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000400 case 1:
401 if (FTy->getNumParams() == 1 &&
Chris Lattner79e038a2007-08-08 16:19:57 +0000402 FTy->getParamType(0) == Type::Int32Ty) {
Chris Lattnere5eab142004-08-15 23:53:06 +0000403 GenericValue rv;
Chris Lattner870286a2006-06-01 17:29:22 +0000404 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
Reid Spencer38f6a152007-03-06 03:11:31 +0000405 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
Chris Lattnerf7bedf42004-08-15 23:39:59 +0000406 return rv;
407 }
408 break;
Chris Lattnere5eab142004-08-15 23:53:06 +0000409 }
410 }
411
412 // Handle cases where no arguments are passed first.
413 if (ArgValues.empty()) {
414 GenericValue rv;
415 switch (RetTy->getTypeID()) {
416 default: assert(0 && "Unknown return type for function call!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000417 case Type::IntegerTyID: {
418 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
419 if (BitWidth == 1)
Reid Spencer38f6a152007-03-06 03:11:31 +0000420 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000421 else if (BitWidth <= 8)
Reid Spencer38f6a152007-03-06 03:11:31 +0000422 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000423 else if (BitWidth <= 16)
Reid Spencer38f6a152007-03-06 03:11:31 +0000424 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000425 else if (BitWidth <= 32)
Reid Spencer38f6a152007-03-06 03:11:31 +0000426 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000427 else if (BitWidth <= 64)
Reid Spencer38f6a152007-03-06 03:11:31 +0000428 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
Reid Spencera54b7cb2007-01-12 07:05:14 +0000429 else
430 assert(0 && "Integer types > 64 bits not supported");
Chris Lattnerd297aea2004-08-15 23:34:48 +0000431 return rv;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 }
Chris Lattnere5eab142004-08-15 23:53:06 +0000433 case Type::VoidTyID:
Reid Spencer38f6a152007-03-06 03:11:31 +0000434 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
Chris Lattnere5eab142004-08-15 23:53:06 +0000435 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000436 case Type::FloatTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000437 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000438 return rv;
439 case Type::DoubleTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000440 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
Chris Lattnere5eab142004-08-15 23:53:06 +0000441 return rv;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000442 case Type::X86_FP80TyID:
443 case Type::FP128TyID:
444 case Type::PPC_FP128TyID:
445 assert(0 && "long double not supported yet");
446 return rv;
Chris Lattnere5eab142004-08-15 23:53:06 +0000447 case Type::PointerTyID:
Chris Lattner870286a2006-06-01 17:29:22 +0000448 return PTOGV(((void*(*)())(intptr_t)FPtr)());
Chris Lattnerd297aea2004-08-15 23:34:48 +0000449 }
Chris Lattnerff0f1bb2003-12-26 06:13:47 +0000450 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000451
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000452 // Okay, this is not one of our quick and easy cases. Because we don't have a
453 // full FFI, we have to codegen a nullary stub function that just calls the
454 // function we are interested in, passing in constants for all of the
455 // arguments. Make this function and return.
456
457 // First, create the function.
458 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
Gabor Greif051a9502008-04-06 20:25:17 +0000459 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
460 F->getParent());
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000461
462 // Insert a basic block.
Gabor Greif051a9502008-04-06 20:25:17 +0000463 BasicBlock *StubBB = BasicBlock::Create("", Stub);
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000464
465 // Convert all of the GenericValue arguments over to constants. Note that we
466 // currently don't support varargs.
Chris Lattner990b8492007-02-13 06:01:22 +0000467 SmallVector<Value*, 8> Args;
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000468 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
469 Constant *C = 0;
470 const Type *ArgTy = FTy->getParamType(i);
471 const GenericValue &AV = ArgValues[i];
472 switch (ArgTy->getTypeID()) {
473 default: assert(0 && "Unknown argument type for function call!");
Chris Lattner02a260a2008-04-20 00:41:09 +0000474 case Type::IntegerTyID:
475 C = ConstantInt::get(AV.IntVal);
476 break;
477 case Type::FloatTyID:
478 C = ConstantFP::get(APFloat(AV.FloatVal));
479 break;
480 case Type::DoubleTyID:
481 C = ConstantFP::get(APFloat(AV.DoubleVal));
482 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000483 case Type::PPC_FP128TyID:
484 case Type::X86_FP80TyID:
Chris Lattner02a260a2008-04-20 00:41:09 +0000485 case Type::FP128TyID:
486 C = ConstantFP::get(APFloat(AV.IntVal));
487 break;
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000488 case Type::PointerTyID:
489 void *ArgPtr = GVTOP(AV);
Chris Lattner02a260a2008-04-20 00:41:09 +0000490 if (sizeof(void*) == 4)
Reid Spencere49661b2006-12-31 05:51:36 +0000491 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
Chris Lattner02a260a2008-04-20 00:41:09 +0000492 else
Reid Spencere49661b2006-12-31 05:51:36 +0000493 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
Reid Spencer15f46d62006-12-12 01:17:41 +0000494 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000495 break;
496 }
497 Args.push_back(C);
498 }
499
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000500 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
501 "", StubBB);
Chris Lattnercdfc51f2008-11-23 08:00:11 +0000502 TheCall->setCallingConv(F->getCallingConv());
Chris Lattnera471e042005-05-06 06:48:54 +0000503 TheCall->setTailCall();
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000504 if (TheCall->getType() != Type::VoidTy)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000505 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000506 else
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000507 ReturnInst::Create(StubBB); // Just return void.
Chris Lattnercc22e9f2004-08-16 00:14:18 +0000508
509 // Finally, return the value returned by our nullary stub function.
510 return runFunction(Stub, std::vector<GenericValue>());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000511}
Chris Lattner4d326fa2003-12-20 01:46:27 +0000512
513/// runJITOnFunction - Run the FunctionPassManager full of
514/// just-in-time compilation passes on F, hopefully filling in
515/// GlobalAddress[F] with the address of F's machine code.
516///
517void JIT::runJITOnFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000518 MutexGuard locked(lock);
Dan Gohman21afcda2009-02-06 21:25:08 +0000519 runJITOnFunctionUnlocked(F, locked);
520}
521
522void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
523 static bool isAlreadyCodeGenerating = false;
Chris Lattner17f218e2007-08-13 20:08:16 +0000524 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
Chris Lattner4d326fa2003-12-20 01:46:27 +0000525
526 // JIT the function
527 isAlreadyCodeGenerating = true;
Nate Begemanf049e072008-05-21 16:34:48 +0000528 jitstate->getPM(locked).run(*F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000529 isAlreadyCodeGenerating = false;
Chris Lattnerc07ed132003-12-20 03:36:47 +0000530
Nate Begemand6b7a242009-02-18 08:31:02 +0000531 // If the function referred to another function that had not yet been
532 // read from bitcode, but we are jitting non-lazily, emit it now.
533 while (!jitstate->getPendingFunctions(locked).empty()) {
534 Function *PF = jitstate->getPendingFunctions(locked).back();
535 jitstate->getPendingFunctions(locked).pop_back();
536
537 // JIT the function
538 isAlreadyCodeGenerating = true;
539 jitstate->getPM(locked).run(*PF);
540 isAlreadyCodeGenerating = false;
541
542 // Now that the function has been jitted, ask the JITEmitter to rewrite
543 // the stub with real address of the function.
544 updateFunctionStub(PF);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000545 }
Nate Begemand6b7a242009-02-18 08:31:02 +0000546
547 // If the JIT is configured to emit info so that dlsym can be used to
548 // rewrite stubs to external globals, do so now.
549 if (areDlsymStubsEnabled() && isLazyCompilationDisabled())
550 updateDlsymStubTable();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000551}
552
553/// getPointerToFunction - This method is used to get the address of the
554/// specified function, compiling it if neccesary.
555///
556void *JIT::getPointerToFunction(Function *F) {
Reid Spenceree448632005-07-12 15:51:55 +0000557
Chris Lattnerc07ed132003-12-20 03:36:47 +0000558 if (void *Addr = getPointerToGlobalIfAvailable(F))
559 return Addr; // Check if function already code gen'd
Chris Lattner4d326fa2003-12-20 01:46:27 +0000560
Dan Gohmana3ac0c12009-02-19 02:40:15 +0000561 MutexGuard locked(lock);
562
Chris Lattnerfe854032006-08-16 01:24:12 +0000563 // Make sure we read in the function if it exists in this Module.
Gabor Greifa99be512007-07-05 17:07:56 +0000564 if (F->hasNotBeenReadFromBitcode()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000565 // Determine the module provider this function is provided by.
566 Module *M = F->getParent();
567 ModuleProvider *MP = 0;
568 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
569 if (Modules[i]->getModule() == M) {
570 MP = Modules[i];
571 break;
572 }
573 }
574 assert(MP && "Function isn't in a module we know about!");
575
Chris Lattner5c72a3a2006-07-07 17:18:09 +0000576 std::string ErrorMsg;
577 if (MP->materializeFunction(F, &ErrorMsg)) {
Bill Wendling832171c2006-12-07 20:04:42 +0000578 cerr << "Error reading function '" << F->getName()
Gabor Greifa99be512007-07-05 17:07:56 +0000579 << "' from bitcode file: " << ErrorMsg << "\n";
Chris Lattner0050ef82004-11-15 23:18:09 +0000580 abort();
581 }
Mon P Wang1c341c82008-10-10 01:47:42 +0000582
Dan Gohman69f93782009-01-05 05:32:42 +0000583 // Now retry to get the address.
584 if (void *Addr = getPointerToGlobalIfAvailable(F))
585 return Addr;
Nicolas Geoffrayfd7d9912008-04-20 08:33:02 +0000586 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000587
Reid Spencer5cbf9852007-01-30 20:08:39 +0000588 if (F->isDeclaration()) {
Duncan Sands667d4b82009-03-07 15:45:40 +0000589 bool AbortOnFailure =
590 !areDlsymStubsEnabled() && !F->hasExternalWeakLinkage();
Dan Gohman69f93782009-01-05 05:32:42 +0000591 void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000592 addGlobalMapping(F, Addr);
593 return Addr;
594 }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000595
Dan Gohman21afcda2009-02-06 21:25:08 +0000596 runJITOnFunctionUnlocked(F, locked);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000597
598 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000599 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
600 return Addr;
601}
602
Chris Lattnerc07ed132003-12-20 03:36:47 +0000603/// getOrEmitGlobalVariable - Return the address of the specified global
604/// variable, possibly emitting it to memory if needed. This is used by the
605/// Emitter.
606void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
Reid Spenceree448632005-07-12 15:51:55 +0000607 MutexGuard locked(lock);
608
Chris Lattnerc07ed132003-12-20 03:36:47 +0000609 void *Ptr = getPointerToGlobalIfAvailable(GV);
610 if (Ptr) return Ptr;
611
612 // If the global is external, just remember the address.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000613 if (GV->isDeclaration()) {
Anton Korobeynikov3b30a6e2007-07-30 20:02:02 +0000614#if HAVE___DSO_HANDLE
Evan Cheng5f42c552006-07-21 23:06:20 +0000615 if (GV->getName() == "__dso_handle")
616 return (void*)&__dso_handle;
Evan Chengb82ab942006-07-22 00:42:03 +0000617#endif
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000618 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
Nate Begeman66941982009-03-04 19:10:38 +0000619 if (Ptr == 0 && !areDlsymStubsEnabled()) {
Bill Wendling832171c2006-12-07 20:04:42 +0000620 cerr << "Could not resolve external global address: "
621 << GV->getName() << "\n";
Chris Lattnerc07ed132003-12-20 03:36:47 +0000622 abort();
623 }
Nate Begeman66941982009-03-04 19:10:38 +0000624 addGlobalMapping(GV, Ptr);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000625 } else {
Evan Cheng4d544a22009-01-16 19:14:49 +0000626 // GlobalVariable's which are not "constant" will cause trouble in a server
627 // situation. It's returned in the same block of memory as code which may
628 // not be writable.
629 if (isGVCompilationDisabled() && !GV->isConstant()) {
Evan Cheng77f86ad2008-12-09 07:31:49 +0000630 cerr << "Compilation of non-internal GlobalValue is disabled!\n";
Evan Cheng446531e2008-09-24 16:25:55 +0000631 abort();
632 }
Dale Johannesendd947ea2008-08-07 01:30:15 +0000633 // If the global hasn't been emitted to memory yet, allocate space and
634 // emit it into memory. It goes in the same array as the generated
635 // code, jump tables, etc.
Chris Lattnerf5d438c2006-05-02 21:57:51 +0000636 const Type *GlobalType = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000637 size_t S = getTargetData()->getTypePaddedSize(GlobalType);
Duncan Sandsd1025932008-01-29 06:23:44 +0000638 size_t A = getTargetData()->getPreferredAlignment(GV);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000639 if (GV->isThreadLocal()) {
640 MutexGuard locked(lock);
641 Ptr = TJI.allocateThreadLocalMemory(S);
Evan Chengb0b53492008-11-04 09:30:48 +0000642 } else if (TJI.allocateSeparateGVMemory()) {
643 if (A <= 8) {
644 Ptr = malloc(S);
645 } else {
646 // Allocate S+A bytes of memory, then use an aligned pointer within that
647 // space.
648 Ptr = malloc(S+A);
649 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
650 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
651 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000652 } else {
653 Ptr = MCE->allocateSpace(S, A);
654 }
Dale Johannesendd947ea2008-08-07 01:30:15 +0000655 addGlobalMapping(GV, Ptr);
656 EmitGlobalVariable(GV);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000657 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000658 return Ptr;
659}
660
Chris Lattner4d326fa2003-12-20 01:46:27 +0000661/// recompileAndRelinkFunction - This method is used to force a function
662/// which has already been compiled, to be compiled again, possibly
663/// after it has been modified. Then the entry to the old copy is overwritten
664/// with a branch to the new copy. If there was no old copy, this acts
665/// just like JIT::getPointerToFunction().
666///
667void *JIT::recompileAndRelinkFunction(Function *F) {
Chris Lattnerc07ed132003-12-20 03:36:47 +0000668 void *OldAddr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000669
Chris Lattnerc07ed132003-12-20 03:36:47 +0000670 // If it's not already compiled there is no reason to patch it up.
671 if (OldAddr == 0) { return getPointerToFunction(F); }
Chris Lattner4d326fa2003-12-20 01:46:27 +0000672
Chris Lattnerc07ed132003-12-20 03:36:47 +0000673 // Delete the old function mapping.
674 addGlobalMapping(F, 0);
675
Chris Lattnerc07ed132003-12-20 03:36:47 +0000676 // Recodegen the function
Chris Lattner4d326fa2003-12-20 01:46:27 +0000677 runJITOnFunction(F);
Chris Lattnerc07ed132003-12-20 03:36:47 +0000678
679 // Update state, forward the old function to the new function.
680 void *Addr = getPointerToGlobalIfAvailable(F);
Chris Lattner4d326fa2003-12-20 01:46:27 +0000681 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
682 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
683 return Addr;
684}
Misha Brukman895eddf2004-11-07 23:58:46 +0000685
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000686/// getMemoryForGV - This method abstracts memory allocation of global
687/// variable so that the JIT can allocate thread local variables depending
688/// on the target.
689///
690char* JIT::getMemoryForGV(const GlobalVariable* GV) {
691 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000692 size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000693 if (GV->isThreadLocal()) {
694 MutexGuard locked(lock);
695 return TJI.allocateThreadLocalMemory(GVSize);
696 } else {
697 return new char[GVSize];
698 }
699}
Nate Begemand6b7a242009-02-18 08:31:02 +0000700
701void JIT::addPendingFunction(Function *F) {
702 MutexGuard locked(lock);
703 jitstate->getPendingFunctions(locked).push_back(F);
704}