1 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tool implements a just-in-time compiler for LLVM, allowing direct
11 // execution of LLVM bitcode in an efficient manner.
13 //===----------------------------------------------------------------------===//
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/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"
30 #include "llvm/Config/config.h"
35 // 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
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
51 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
56 static struct RegisterJIT {
57 RegisterJIT() { JIT::Register(); }
68 #if defined (__GNUC__)
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.
77 // The __register_frame function works with Linux.
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.
87 extern "C" void __register_frame(void*);
89 #if defined (__APPLE__)
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.
101 /// frame - Pointer to the exception table.
104 /// encoding - The encoding of the object?
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;
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.
120 /// next - At least we know it's a chained list!
121 struct LibgccObject *next;
124 // "kemgr" stuff. Apparently, all frame tables are stored there.
125 extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
126 extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
127 #define KEYMGR_GCC3_DW2_OBJ_LIST 302 /* Dwarf2 object list */
129 /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
130 /// probably contains all dwarf tables that are loaded.
131 struct LibgccObjectInfo {
133 /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
135 struct LibgccObject* seenObjects;
137 /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
139 struct LibgccObject* unseenObjects;
145 #include "llvm/Support/Dwarf.h"
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.
150 void DarwinRegisterFrame(void* FrameBegin) {
152 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
153 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
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
159 struct LibgccObject* ob = (struct LibgccObject*)
160 malloc(sizeof(struct LibgccObject));
162 // Do like libgcc for the values of the field.
163 ob->unused1 = (void *)-1;
166 ob->frame = FrameBegin;
168 ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
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;
176 // Update the key's unseenObjects list.
177 LOI->unseenObjects = ob;
179 // Finally update the "key". Apparently, libgcc requires it.
180 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
189 /// 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.
192 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
193 std::string *ErrorStr,
194 JITMemoryManager *JMM,
196 ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
199 // 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);
205 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
206 JITMemoryManager *JMM, bool Fast)
207 : ExecutionEngine(MP), TM(tm), TJI(tji) {
208 setTargetData(TM.getTargetData());
210 jitstate = new JITState(MP);
213 MCE = createEmitter(*this, JMM);
216 MutexGuard locked(lock);
217 FunctionPassManager &PM = jitstate->getPM(locked);
218 PM.add(new TargetData(*TM.getTargetData()));
220 // Turn the machine code intermediate representation into bytes in memory that
222 if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
223 cerr << "Target does not support machine code emission!\n";
227 // Register routine for informing unwinding runtime about new EH frames
228 #if defined(__GNUC__)
229 #if defined(__APPLE__)
230 struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
231 _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
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
237 LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo));
238 _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
241 InstallExceptionTableRegister(DarwinRegisterFrame);
243 InstallExceptionTableRegister(__register_frame);
247 // Initialize passes.
248 PM.doInitialization();
257 /// addModuleProvider - Add a new ModuleProvider to the JIT. If we previously
258 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
260 void JIT::addModuleProvider(ModuleProvider *MP) {
261 MutexGuard locked(lock);
263 if (Modules.empty()) {
264 assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
266 jitstate = new JITState(MP);
268 FunctionPassManager &PM = jitstate->getPM(locked);
269 PM.add(new TargetData(*TM.getTargetData()));
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";
278 // Initialize passes.
279 PM.doInitialization();
282 ExecutionEngine::addModuleProvider(MP);
285 /// removeModuleProvider - If we are removing the last ModuleProvider,
286 /// invalidate the jitstate since the PassManager it contains references a
287 /// released ModuleProvider.
288 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
289 Module *result = ExecutionEngine::removeModuleProvider(MP, E);
291 MutexGuard locked(lock);
292 if (Modules.empty()) {
300 /// run - Start execution with the specified function and arguments.
302 GenericValue JIT::runFunction(Function *F,
303 const std::vector<GenericValue> &ArgValues) {
304 assert(F && "Function *F was null at entry to run()");
306 void *FPtr = getPointerToFunction(F);
307 assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
308 const FunctionType *FTy = F->getFunctionType();
309 const Type *RetTy = FTy->getReturnType();
311 assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
312 "Too many arguments passed into function!");
313 assert(FTy->getNumParams() == ArgValues.size() &&
314 "This doesn't support passing arguments through varargs (yet)!");
316 // Handle some common cases first. These cases correspond to common `main'
318 if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
319 switch (ArgValues.size()) {
321 if (FTy->getParamType(0) == Type::Int32Ty &&
322 isa<PointerType>(FTy->getParamType(1)) &&
323 isa<PointerType>(FTy->getParamType(2))) {
324 int (*PF)(int, char **, const char **) =
325 (int(*)(int, char **, const char **))(intptr_t)FPtr;
327 // Call the function.
329 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
330 (char **)GVTOP(ArgValues[1]),
331 (const char **)GVTOP(ArgValues[2])));
336 if (FTy->getParamType(0) == Type::Int32Ty &&
337 isa<PointerType>(FTy->getParamType(1))) {
338 int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
340 // Call the function.
342 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
343 (char **)GVTOP(ArgValues[1])));
348 if (FTy->getNumParams() == 1 &&
349 FTy->getParamType(0) == Type::Int32Ty) {
351 int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
352 rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
359 // Handle cases where no arguments are passed first.
360 if (ArgValues.empty()) {
362 switch (RetTy->getTypeID()) {
363 default: assert(0 && "Unknown return type for function call!");
364 case Type::IntegerTyID: {
365 unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
367 rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
368 else if (BitWidth <= 8)
369 rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
370 else if (BitWidth <= 16)
371 rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
372 else if (BitWidth <= 32)
373 rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
374 else if (BitWidth <= 64)
375 rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
377 assert(0 && "Integer types > 64 bits not supported");
381 rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
383 case Type::FloatTyID:
384 rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
386 case Type::DoubleTyID:
387 rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
389 case Type::X86_FP80TyID:
390 case Type::FP128TyID:
391 case Type::PPC_FP128TyID:
392 assert(0 && "long double not supported yet");
394 case Type::PointerTyID:
395 return PTOGV(((void*(*)())(intptr_t)FPtr)());
399 // Okay, this is not one of our quick and easy cases. Because we don't have a
400 // full FFI, we have to codegen a nullary stub function that just calls the
401 // function we are interested in, passing in constants for all of the
402 // arguments. Make this function and return.
404 // First, create the function.
405 FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
406 Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
409 // Insert a basic block.
410 BasicBlock *StubBB = BasicBlock::Create("", Stub);
412 // Convert all of the GenericValue arguments over to constants. Note that we
413 // currently don't support varargs.
414 SmallVector<Value*, 8> Args;
415 for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
417 const Type *ArgTy = FTy->getParamType(i);
418 const GenericValue &AV = ArgValues[i];
419 switch (ArgTy->getTypeID()) {
420 default: assert(0 && "Unknown argument type for function call!");
421 case Type::IntegerTyID:
422 C = ConstantInt::get(AV.IntVal);
424 case Type::FloatTyID:
425 C = ConstantFP::get(APFloat(AV.FloatVal));
427 case Type::DoubleTyID:
428 C = ConstantFP::get(APFloat(AV.DoubleVal));
430 case Type::PPC_FP128TyID:
431 case Type::X86_FP80TyID:
432 case Type::FP128TyID:
433 C = ConstantFP::get(APFloat(AV.IntVal));
435 case Type::PointerTyID:
436 void *ArgPtr = GVTOP(AV);
437 if (sizeof(void*) == 4)
438 C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
440 C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
441 C = ConstantExpr::getIntToPtr(C, ArgTy); // Cast the integer to pointer
447 CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
449 TheCall->setTailCall();
450 if (TheCall->getType() != Type::VoidTy)
451 ReturnInst::Create(TheCall, StubBB); // Return result of the call.
453 ReturnInst::Create(StubBB); // Just return void.
455 // Finally, return the value returned by our nullary stub function.
456 return runFunction(Stub, std::vector<GenericValue>());
459 /// runJITOnFunction - Run the FunctionPassManager full of
460 /// just-in-time compilation passes on F, hopefully filling in
461 /// GlobalAddress[F] with the address of F's machine code.
463 void JIT::runJITOnFunction(Function *F) {
464 static bool isAlreadyCodeGenerating = false;
466 MutexGuard locked(lock);
467 assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
470 isAlreadyCodeGenerating = true;
471 jitstate->getPM(locked).run(*F);
472 isAlreadyCodeGenerating = false;
474 // If the function referred to a global variable that had not yet been
475 // emitted, it allocates memory for the global, but doesn't emit it yet. Emit
476 // all of these globals now.
477 while (!jitstate->getPendingGlobals(locked).empty()) {
478 const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
479 jitstate->getPendingGlobals(locked).pop_back();
480 EmitGlobalVariable(GV);
484 /// getPointerToFunction - This method is used to get the address of the
485 /// specified function, compiling it if neccesary.
487 void *JIT::getPointerToFunction(Function *F) {
489 if (void *Addr = getPointerToGlobalIfAvailable(F))
490 return Addr; // Check if function already code gen'd
492 // Make sure we read in the function if it exists in this Module.
493 if (F->hasNotBeenReadFromBitcode()) {
494 // Determine the module provider this function is provided by.
495 Module *M = F->getParent();
496 ModuleProvider *MP = 0;
497 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
498 if (Modules[i]->getModule() == M) {
503 assert(MP && "Function isn't in a module we know about!");
505 std::string ErrorMsg;
506 if (MP->materializeFunction(F, &ErrorMsg)) {
507 cerr << "Error reading function '" << F->getName()
508 << "' from bitcode file: " << ErrorMsg << "\n";
513 if (void *Addr = getPointerToGlobalIfAvailable(F)) {
517 MutexGuard locked(lock);
519 if (F->isDeclaration()) {
520 void *Addr = getPointerToNamedFunction(F->getName());
521 addGlobalMapping(F, Addr);
527 void *Addr = getPointerToGlobalIfAvailable(F);
528 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
532 /// getOrEmitGlobalVariable - Return the address of the specified global
533 /// variable, possibly emitting it to memory if needed. This is used by the
535 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
536 MutexGuard locked(lock);
538 void *Ptr = getPointerToGlobalIfAvailable(GV);
541 // If the global is external, just remember the address.
542 if (GV->isDeclaration()) {
543 #if HAVE___DSO_HANDLE
544 if (GV->getName() == "__dso_handle")
545 return (void*)&__dso_handle;
547 Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
549 cerr << "Could not resolve external global address: "
550 << GV->getName() << "\n";
552 addGlobalMapping(GV, Ptr);
555 if (isGVCompilationDisabled()) {
556 cerr << "Compilation of GlobalVariable is disabled!\n";
559 // If the global hasn't been emitted to memory yet, allocate space and
560 // emit it into memory. It goes in the same array as the generated
561 // code, jump tables, etc.
562 const Type *GlobalType = GV->getType()->getElementType();
563 size_t S = getTargetData()->getABITypeSize(GlobalType);
564 size_t A = getTargetData()->getPreferredAlignment(GV);
565 if (GV->isThreadLocal()) {
566 MutexGuard locked(lock);
567 Ptr = TJI.allocateThreadLocalMemory(S);
568 } else if (TJI.allocateSeparateGVMemory()) {
572 // Allocate S+A bytes of memory, then use an aligned pointer within that
575 unsigned MisAligned = ((intptr_t)Ptr & (A-1));
576 Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
579 Ptr = MCE->allocateSpace(S, A);
581 addGlobalMapping(GV, Ptr);
582 EmitGlobalVariable(GV);
587 /// recompileAndRelinkFunction - This method is used to force a function
588 /// which has already been compiled, to be compiled again, possibly
589 /// after it has been modified. Then the entry to the old copy is overwritten
590 /// with a branch to the new copy. If there was no old copy, this acts
591 /// just like JIT::getPointerToFunction().
593 void *JIT::recompileAndRelinkFunction(Function *F) {
594 void *OldAddr = getPointerToGlobalIfAvailable(F);
596 // If it's not already compiled there is no reason to patch it up.
597 if (OldAddr == 0) { return getPointerToFunction(F); }
599 // Delete the old function mapping.
600 addGlobalMapping(F, 0);
602 // Recodegen the function
605 // Update state, forward the old function to the new function.
606 void *Addr = getPointerToGlobalIfAvailable(F);
607 assert(Addr && "Code generation didn't add function to GlobalAddress table!");
608 TJI.replaceMachineCodeForFunction(OldAddr, Addr);
612 /// getMemoryForGV - This method abstracts memory allocation of global
613 /// variable so that the JIT can allocate thread local variables depending
616 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
617 const Type *ElTy = GV->getType()->getElementType();
618 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
619 if (GV->isThreadLocal()) {
620 MutexGuard locked(lock);
621 return TJI.allocateThreadLocalMemory(GVSize);
623 return new char[GVSize];