LLVM API Documentation

JIT.cpp
Go to the documentation of this file.
00001 //===-- JIT.cpp - LLVM Just in Time Compiler ------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This tool implements a just-in-time compiler for LLVM, allowing direct
00011 // execution of LLVM bitcode in an efficient manner.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "JIT.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/CodeGen/JITCodeEmitter.h"
00018 #include "llvm/CodeGen/MachineCodeInfo.h"
00019 #include "llvm/Config/config.h"
00020 #include "llvm/ExecutionEngine/GenericValue.h"
00021 #include "llvm/ExecutionEngine/JITEventListener.h"
00022 #include "llvm/ExecutionEngine/JITMemoryManager.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/Function.h"
00027 #include "llvm/IR/GlobalVariable.h"
00028 #include "llvm/IR/Instructions.h"
00029 #include "llvm/Support/Dwarf.h"
00030 #include "llvm/Support/DynamicLibrary.h"
00031 #include "llvm/Support/ErrorHandling.h"
00032 #include "llvm/Support/ManagedStatic.h"
00033 #include "llvm/Support/MutexGuard.h"
00034 #include "llvm/Target/TargetJITInfo.h"
00035 #include "llvm/Target/TargetMachine.h"
00036 
00037 using namespace llvm;
00038 
00039 #ifdef __APPLE__
00040 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
00041 // of atexit). It passes the address of linker generated symbol __dso_handle
00042 // to the function.
00043 // This configuration change happened at version 5330.
00044 # include <AvailabilityMacros.h>
00045 # if defined(MAC_OS_X_VERSION_10_4) && \
00046      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
00047       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
00048        __APPLE_CC__ >= 5330))
00049 #  ifndef HAVE___DSO_HANDLE
00050 #   define HAVE___DSO_HANDLE 1
00051 #  endif
00052 # endif
00053 #endif
00054 
00055 #if HAVE___DSO_HANDLE
00056 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
00057 #endif
00058 
00059 namespace {
00060 
00061 static struct RegisterJIT {
00062   RegisterJIT() { JIT::Register(); }
00063 } JITRegistrator;
00064 
00065 }
00066 
00067 extern "C" void LLVMLinkInJIT() {
00068 }
00069 
00070 // Determine whether we can register EH tables.
00071 #if (defined(__GNUC__) && !defined(__ARM_EABI__) && \
00072      !defined(__USING_SJLJ_EXCEPTIONS__))
00073 #define HAVE_EHTABLE_SUPPORT 1
00074 #else
00075 #define HAVE_EHTABLE_SUPPORT 0
00076 #endif
00077 
00078 #if HAVE_EHTABLE_SUPPORT
00079 
00080 // libgcc defines the __register_frame function to dynamically register new
00081 // dwarf frames for exception handling. This functionality is not portable
00082 // across compilers and is only provided by GCC. We use the __register_frame
00083 // function here so that code generated by the JIT cooperates with the unwinding
00084 // runtime of libgcc. When JITting with exception handling enable, LLVM
00085 // generates dwarf frames and registers it to libgcc with __register_frame.
00086 //
00087 // The __register_frame function works with Linux.
00088 //
00089 // Unfortunately, this functionality seems to be in libgcc after the unwinding
00090 // library of libgcc for darwin was written. The code for darwin overwrites the
00091 // value updated by __register_frame with a value fetched with "keymgr".
00092 // "keymgr" is an obsolete functionality, which should be rewritten some day.
00093 // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
00094 // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
00095 // values of an opaque key, used by libgcc to find dwarf tables.
00096 
00097 extern "C" void __register_frame(void*);
00098 extern "C" void __deregister_frame(void*);
00099 
00100 #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED <= 1050
00101 # define USE_KEYMGR 1
00102 #else
00103 # define USE_KEYMGR 0
00104 #endif
00105 
00106 #if USE_KEYMGR
00107 
00108 namespace {
00109 
00110 // LibgccObject - This is the structure defined in libgcc. There is no #include
00111 // provided for this structure, so we also define it here. libgcc calls it
00112 // "struct object". The structure is undocumented in libgcc.
00113 struct LibgccObject {
00114   void *unused1;
00115   void *unused2;
00116   void *unused3;
00117 
00118   /// frame - Pointer to the exception table.
00119   void *frame;
00120 
00121   /// encoding -  The encoding of the object?
00122   union {
00123     struct {
00124       unsigned long sorted : 1;
00125       unsigned long from_array : 1;
00126       unsigned long mixed_encoding : 1;
00127       unsigned long encoding : 8;
00128       unsigned long count : 21;
00129     } b;
00130     size_t i;
00131   } encoding;
00132 
00133   /// fde_end - libgcc defines this field only if some macro is defined. We
00134   /// include this field even if it may not there, to make libgcc happy.
00135   char *fde_end;
00136 
00137   /// next - At least we know it's a chained list!
00138   struct LibgccObject *next;
00139 };
00140 
00141 // "kemgr" stuff. Apparently, all frame tables are stored there.
00142 extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
00143 extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
00144 #define KEYMGR_GCC3_DW2_OBJ_LIST        302     /* Dwarf2 object list  */
00145 
00146 /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
00147 /// probably contains all dwarf tables that are loaded.
00148 struct LibgccObjectInfo {
00149 
00150   /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
00151   ///
00152   struct LibgccObject* seenObjects;
00153 
00154   /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
00155   ///
00156   struct LibgccObject* unseenObjects;
00157 
00158   unsigned unused[2];
00159 };
00160 
00161 /// darwin_register_frame - Since __register_frame does not work with darwin's
00162 /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
00163 /// "Dwarf2 object list" key.
00164 void DarwinRegisterFrame(void* FrameBegin) {
00165   // Get the key.
00166   LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
00167     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
00168   assert(LOI && "This should be preallocated by the runtime");
00169 
00170   // Allocate a new LibgccObject to represent this frame. Deallocation of this
00171   // object may be impossible: since darwin code in libgcc was written after
00172   // the ability to dynamically register frames, things may crash if we
00173   // deallocate it.
00174   struct LibgccObject* ob = (struct LibgccObject*)
00175     malloc(sizeof(struct LibgccObject));
00176 
00177   // Do like libgcc for the values of the field.
00178   ob->unused1 = (void *)-1;
00179   ob->unused2 = 0;
00180   ob->unused3 = 0;
00181   ob->frame = FrameBegin;
00182   ob->encoding.i = 0;
00183   ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
00184 
00185   // Put the info on both places, as libgcc uses the first or the second
00186   // field. Note that we rely on having two pointers here. If fde_end was a
00187   // char, things would get complicated.
00188   ob->fde_end = (char*)LOI->unseenObjects;
00189   ob->next = LOI->unseenObjects;
00190 
00191   // Update the key's unseenObjects list.
00192   LOI->unseenObjects = ob;
00193 
00194   // Finally update the "key". Apparently, libgcc requires it.
00195   _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
00196                                          LOI);
00197 
00198 }
00199 
00200 }
00201 #endif // __APPLE__
00202 #endif // HAVE_EHTABLE_SUPPORT
00203 
00204 /// createJIT - This is the factory method for creating a JIT for the current
00205 /// machine, it does not fall back to the interpreter.  This takes ownership
00206 /// of the module.
00207 ExecutionEngine *JIT::createJIT(Module *M,
00208                                 std::string *ErrorStr,
00209                                 JITMemoryManager *JMM,
00210                                 bool GVsWithCode,
00211                                 TargetMachine *TM) {
00212   // Try to register the program as a source of symbols to resolve against.
00213   //
00214   // FIXME: Don't do this here.
00215   sys::DynamicLibrary::LoadLibraryPermanently(0, NULL);
00216 
00217   // If the target supports JIT code generation, create the JIT.
00218   if (TargetJITInfo *TJ = TM->getJITInfo()) {
00219     return new JIT(M, *TM, *TJ, JMM, GVsWithCode);
00220   } else {
00221     if (ErrorStr)
00222       *ErrorStr = "target does not support JIT code generation";
00223     return 0;
00224   }
00225 }
00226 
00227 namespace {
00228 /// This class supports the global getPointerToNamedFunction(), which allows
00229 /// bugpoint or gdb users to search for a function by name without any context.
00230 class JitPool {
00231   SmallPtrSet<JIT*, 1> JITs;  // Optimize for process containing just 1 JIT.
00232   mutable sys::Mutex Lock;
00233 public:
00234   void Add(JIT *jit) {
00235     MutexGuard guard(Lock);
00236     JITs.insert(jit);
00237   }
00238   void Remove(JIT *jit) {
00239     MutexGuard guard(Lock);
00240     JITs.erase(jit);
00241   }
00242   void *getPointerToNamedFunction(const char *Name) const {
00243     MutexGuard guard(Lock);
00244     assert(JITs.size() != 0 && "No Jit registered");
00245     //search function in every instance of JIT
00246     for (SmallPtrSet<JIT*, 1>::const_iterator Jit = JITs.begin(),
00247            end = JITs.end();
00248          Jit != end; ++Jit) {
00249       if (Function *F = (*Jit)->FindFunctionNamed(Name))
00250         return (*Jit)->getPointerToFunction(F);
00251     }
00252     // The function is not available : fallback on the first created (will
00253     // search in symbol of the current program/library)
00254     return (*JITs.begin())->getPointerToNamedFunction(Name);
00255   }
00256 };
00257 ManagedStatic<JitPool> AllJits;
00258 }
00259 extern "C" {
00260   // getPointerToNamedFunction - This function is used as a global wrapper to
00261   // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
00262   // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
00263   // need to resolve function(s) that are being mis-codegenerated, so we need to
00264   // resolve their addresses at runtime, and this is the way to do it.
00265   void *getPointerToNamedFunction(const char *Name) {
00266     return AllJits->getPointerToNamedFunction(Name);
00267   }
00268 }
00269 
00270 JIT::JIT(Module *M, TargetMachine &tm, TargetJITInfo &tji,
00271          JITMemoryManager *jmm, bool GVsWithCode)
00272   : ExecutionEngine(M), TM(tm), TJI(tji),
00273     JMM(jmm ? jmm : JITMemoryManager::CreateDefaultMemManager()),
00274     AllocateGVsWithCode(GVsWithCode), isAlreadyCodeGenerating(false) {
00275   setDataLayout(TM.getDataLayout());
00276 
00277   jitstate = new JITState(M);
00278 
00279   // Initialize JCE
00280   JCE = createEmitter(*this, JMM, TM);
00281 
00282   // Register in global list of all JITs.
00283   AllJits->Add(this);
00284 
00285   // Add target data
00286   MutexGuard locked(lock);
00287   FunctionPassManager &PM = jitstate->getPM(locked);
00288   PM.add(new DataLayout(*TM.getDataLayout()));
00289 
00290   // Turn the machine code intermediate representation into bytes in memory that
00291   // may be executed.
00292   if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
00293     report_fatal_error("Target does not support machine code emission!");
00294   }
00295 
00296   // Register routine for informing unwinding runtime about new EH frames
00297 #if HAVE_EHTABLE_SUPPORT
00298 #if USE_KEYMGR
00299   struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
00300     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
00301 
00302   // The key is created on demand, and libgcc creates it the first time an
00303   // exception occurs. Since we need the key to register frames, we create
00304   // it now.
00305   if (!LOI)
00306     LOI = (LibgccObjectInfo*)calloc(sizeof(struct LibgccObjectInfo), 1);
00307   _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST, LOI);
00308   InstallExceptionTableRegister(DarwinRegisterFrame);
00309   // Not sure about how to deregister on Darwin.
00310 #else
00311   InstallExceptionTableRegister(__register_frame);
00312   InstallExceptionTableDeregister(__deregister_frame);
00313 #endif // __APPLE__
00314 #endif // HAVE_EHTABLE_SUPPORT
00315 
00316   // Initialize passes.
00317   PM.doInitialization();
00318 }
00319 
00320 JIT::~JIT() {
00321   // Unregister all exception tables registered by this JIT.
00322   DeregisterAllTables();
00323   // Cleanup.
00324   AllJits->Remove(this);
00325   delete jitstate;
00326   delete JCE;
00327   // JMM is a ownership of JCE, so we no need delete JMM here.
00328   delete &TM;
00329 }
00330 
00331 /// addModule - Add a new Module to the JIT.  If we previously removed the last
00332 /// Module, we need re-initialize jitstate with a valid Module.
00333 void JIT::addModule(Module *M) {
00334   MutexGuard locked(lock);
00335 
00336   if (Modules.empty()) {
00337     assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
00338 
00339     jitstate = new JITState(M);
00340 
00341     FunctionPassManager &PM = jitstate->getPM(locked);
00342     PM.add(new DataLayout(*TM.getDataLayout()));
00343 
00344     // Turn the machine code intermediate representation into bytes in memory
00345     // that may be executed.
00346     if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
00347       report_fatal_error("Target does not support machine code emission!");
00348     }
00349 
00350     // Initialize passes.
00351     PM.doInitialization();
00352   }
00353 
00354   ExecutionEngine::addModule(M);
00355 }
00356 
00357 /// removeModule - If we are removing the last Module, invalidate the jitstate
00358 /// since the PassManager it contains references a released Module.
00359 bool JIT::removeModule(Module *M) {
00360   bool result = ExecutionEngine::removeModule(M);
00361 
00362   MutexGuard locked(lock);
00363 
00364   if (jitstate && jitstate->getModule() == M) {
00365     delete jitstate;
00366     jitstate = 0;
00367   }
00368 
00369   if (!jitstate && !Modules.empty()) {
00370     jitstate = new JITState(Modules[0]);
00371 
00372     FunctionPassManager &PM = jitstate->getPM(locked);
00373     PM.add(new DataLayout(*TM.getDataLayout()));
00374 
00375     // Turn the machine code intermediate representation into bytes in memory
00376     // that may be executed.
00377     if (TM.addPassesToEmitMachineCode(PM, *JCE)) {
00378       report_fatal_error("Target does not support machine code emission!");
00379     }
00380 
00381     // Initialize passes.
00382     PM.doInitialization();
00383   }
00384   return result;
00385 }
00386 
00387 /// run - Start execution with the specified function and arguments.
00388 ///
00389 GenericValue JIT::runFunction(Function *F,
00390                               const std::vector<GenericValue> &ArgValues) {
00391   assert(F && "Function *F was null at entry to run()");
00392 
00393   void *FPtr = getPointerToFunction(F);
00394   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
00395   FunctionType *FTy = F->getFunctionType();
00396   Type *RetTy = FTy->getReturnType();
00397 
00398   assert((FTy->getNumParams() == ArgValues.size() ||
00399           (FTy->isVarArg() && FTy->getNumParams() <= ArgValues.size())) &&
00400          "Wrong number of arguments passed into function!");
00401   assert(FTy->getNumParams() == ArgValues.size() &&
00402          "This doesn't support passing arguments through varargs (yet)!");
00403 
00404   // Handle some common cases first.  These cases correspond to common `main'
00405   // prototypes.
00406   if (RetTy->isIntegerTy(32) || RetTy->isVoidTy()) {
00407     switch (ArgValues.size()) {
00408     case 3:
00409       if (FTy->getParamType(0)->isIntegerTy(32) &&
00410           FTy->getParamType(1)->isPointerTy() &&
00411           FTy->getParamType(2)->isPointerTy()) {
00412         int (*PF)(int, char **, const char **) =
00413           (int(*)(int, char **, const char **))(intptr_t)FPtr;
00414 
00415         // Call the function.
00416         GenericValue rv;
00417         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00418                                  (char **)GVTOP(ArgValues[1]),
00419                                  (const char **)GVTOP(ArgValues[2])));
00420         return rv;
00421       }
00422       break;
00423     case 2:
00424       if (FTy->getParamType(0)->isIntegerTy(32) &&
00425           FTy->getParamType(1)->isPointerTy()) {
00426         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
00427 
00428         // Call the function.
00429         GenericValue rv;
00430         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(),
00431                                  (char **)GVTOP(ArgValues[1])));
00432         return rv;
00433       }
00434       break;
00435     case 1:
00436       if (FTy->getParamType(0)->isIntegerTy(32)) {
00437         GenericValue rv;
00438         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
00439         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
00440         return rv;
00441       }
00442       if (FTy->getParamType(0)->isPointerTy()) {
00443         GenericValue rv;
00444         int (*PF)(char *) = (int(*)(char *))(intptr_t)FPtr;
00445         rv.IntVal = APInt(32, PF((char*)GVTOP(ArgValues[0])));
00446         return rv;
00447       }
00448       break;
00449     }
00450   }
00451 
00452   // Handle cases where no arguments are passed first.
00453   if (ArgValues.empty()) {
00454     GenericValue rv;
00455     switch (RetTy->getTypeID()) {
00456     default: llvm_unreachable("Unknown return type for function call!");
00457     case Type::IntegerTyID: {
00458       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
00459       if (BitWidth == 1)
00460         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
00461       else if (BitWidth <= 8)
00462         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
00463       else if (BitWidth <= 16)
00464         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
00465       else if (BitWidth <= 32)
00466         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
00467       else if (BitWidth <= 64)
00468         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
00469       else
00470         llvm_unreachable("Integer types > 64 bits not supported");
00471       return rv;
00472     }
00473     case Type::VoidTyID:
00474       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
00475       return rv;
00476     case Type::FloatTyID:
00477       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
00478       return rv;
00479     case Type::DoubleTyID:
00480       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
00481       return rv;
00482     case Type::X86_FP80TyID:
00483     case Type::FP128TyID:
00484     case Type::PPC_FP128TyID:
00485       llvm_unreachable("long double not supported yet");
00486     case Type::PointerTyID:
00487       return PTOGV(((void*(*)())(intptr_t)FPtr)());
00488     }
00489   }
00490 
00491   // Okay, this is not one of our quick and easy cases.  Because we don't have a
00492   // full FFI, we have to codegen a nullary stub function that just calls the
00493   // function we are interested in, passing in constants for all of the
00494   // arguments.  Make this function and return.
00495 
00496   // First, create the function.
00497   FunctionType *STy=FunctionType::get(RetTy, false);
00498   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
00499                                     F->getParent());
00500 
00501   // Insert a basic block.
00502   BasicBlock *StubBB = BasicBlock::Create(F->getContext(), "", Stub);
00503 
00504   // Convert all of the GenericValue arguments over to constants.  Note that we
00505   // currently don't support varargs.
00506   SmallVector<Value*, 8> Args;
00507   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
00508     Constant *C = 0;
00509     Type *ArgTy = FTy->getParamType(i);
00510     const GenericValue &AV = ArgValues[i];
00511     switch (ArgTy->getTypeID()) {
00512     default: llvm_unreachable("Unknown argument type for function call!");
00513     case Type::IntegerTyID:
00514         C = ConstantInt::get(F->getContext(), AV.IntVal);
00515         break;
00516     case Type::FloatTyID:
00517         C = ConstantFP::get(F->getContext(), APFloat(AV.FloatVal));
00518         break;
00519     case Type::DoubleTyID:
00520         C = ConstantFP::get(F->getContext(), APFloat(AV.DoubleVal));
00521         break;
00522     case Type::PPC_FP128TyID:
00523     case Type::X86_FP80TyID:
00524     case Type::FP128TyID:
00525         C = ConstantFP::get(F->getContext(), APFloat(ArgTy->getFltSemantics(),
00526                                                      AV.IntVal));
00527         break;
00528     case Type::PointerTyID:
00529       void *ArgPtr = GVTOP(AV);
00530       if (sizeof(void*) == 4)
00531         C = ConstantInt::get(Type::getInt32Ty(F->getContext()),
00532                              (int)(intptr_t)ArgPtr);
00533       else
00534         C = ConstantInt::get(Type::getInt64Ty(F->getContext()),
00535                              (intptr_t)ArgPtr);
00536       // Cast the integer to pointer
00537       C = ConstantExpr::getIntToPtr(C, ArgTy);
00538       break;
00539     }
00540     Args.push_back(C);
00541   }
00542 
00543   CallInst *TheCall = CallInst::Create(F, Args, "", StubBB);
00544   TheCall->setCallingConv(F->getCallingConv());
00545   TheCall->setTailCall();
00546   if (!TheCall->getType()->isVoidTy())
00547     // Return result of the call.
00548     ReturnInst::Create(F->getContext(), TheCall, StubBB);
00549   else
00550     ReturnInst::Create(F->getContext(), StubBB);           // Just return void.
00551 
00552   // Finally, call our nullary stub function.
00553   GenericValue Result = runFunction(Stub, std::vector<GenericValue>());
00554   // Erase it, since no other function can have a reference to it.
00555   Stub->eraseFromParent();
00556   // And return the result.
00557   return Result;
00558 }
00559 
00560 void JIT::RegisterJITEventListener(JITEventListener *L) {
00561   if (L == NULL)
00562     return;
00563   MutexGuard locked(lock);
00564   EventListeners.push_back(L);
00565 }
00566 void JIT::UnregisterJITEventListener(JITEventListener *L) {
00567   if (L == NULL)
00568     return;
00569   MutexGuard locked(lock);
00570   std::vector<JITEventListener*>::reverse_iterator I=
00571       std::find(EventListeners.rbegin(), EventListeners.rend(), L);
00572   if (I != EventListeners.rend()) {
00573     std::swap(*I, EventListeners.back());
00574     EventListeners.pop_back();
00575   }
00576 }
00577 void JIT::NotifyFunctionEmitted(
00578     const Function &F,
00579     void *Code, size_t Size,
00580     const JITEvent_EmittedFunctionDetails &Details) {
00581   MutexGuard locked(lock);
00582   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
00583     EventListeners[I]->NotifyFunctionEmitted(F, Code, Size, Details);
00584   }
00585 }
00586 
00587 void JIT::NotifyFreeingMachineCode(void *OldPtr) {
00588   MutexGuard locked(lock);
00589   for (unsigned I = 0, S = EventListeners.size(); I < S; ++I) {
00590     EventListeners[I]->NotifyFreeingMachineCode(OldPtr);
00591   }
00592 }
00593 
00594 /// runJITOnFunction - Run the FunctionPassManager full of
00595 /// just-in-time compilation passes on F, hopefully filling in
00596 /// GlobalAddress[F] with the address of F's machine code.
00597 ///
00598 void JIT::runJITOnFunction(Function *F, MachineCodeInfo *MCI) {
00599   MutexGuard locked(lock);
00600 
00601   class MCIListener : public JITEventListener {
00602     MachineCodeInfo *const MCI;
00603    public:
00604     MCIListener(MachineCodeInfo *mci) : MCI(mci) {}
00605     virtual void NotifyFunctionEmitted(const Function &,
00606                                        void *Code, size_t Size,
00607                                        const EmittedFunctionDetails &) {
00608       MCI->setAddress(Code);
00609       MCI->setSize(Size);
00610     }
00611   };
00612   MCIListener MCIL(MCI);
00613   if (MCI)
00614     RegisterJITEventListener(&MCIL);
00615 
00616   runJITOnFunctionUnlocked(F, locked);
00617 
00618   if (MCI)
00619     UnregisterJITEventListener(&MCIL);
00620 }
00621 
00622 void JIT::runJITOnFunctionUnlocked(Function *F, const MutexGuard &locked) {
00623   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
00624 
00625   jitTheFunction(F, locked);
00626 
00627   // If the function referred to another function that had not yet been
00628   // read from bitcode, and we are jitting non-lazily, emit it now.
00629   while (!jitstate->getPendingFunctions(locked).empty()) {
00630     Function *PF = jitstate->getPendingFunctions(locked).back();
00631     jitstate->getPendingFunctions(locked).pop_back();
00632 
00633     assert(!PF->hasAvailableExternallyLinkage() &&
00634            "Externally-defined function should not be in pending list.");
00635 
00636     jitTheFunction(PF, locked);
00637 
00638     // Now that the function has been jitted, ask the JITEmitter to rewrite
00639     // the stub with real address of the function.
00640     updateFunctionStub(PF);
00641   }
00642 }
00643 
00644 void JIT::jitTheFunction(Function *F, const MutexGuard &locked) {
00645   isAlreadyCodeGenerating = true;
00646   jitstate->getPM(locked).run(*F);
00647   isAlreadyCodeGenerating = false;
00648 
00649   // clear basic block addresses after this function is done
00650   getBasicBlockAddressMap(locked).clear();
00651 }
00652 
00653 /// getPointerToFunction - This method is used to get the address of the
00654 /// specified function, compiling it if necessary.
00655 ///
00656 void *JIT::getPointerToFunction(Function *F) {
00657 
00658   if (void *Addr = getPointerToGlobalIfAvailable(F))
00659     return Addr;   // Check if function already code gen'd
00660 
00661   MutexGuard locked(lock);
00662 
00663   // Now that this thread owns the lock, make sure we read in the function if it
00664   // exists in this Module.
00665   std::string ErrorMsg;
00666   if (F->Materialize(&ErrorMsg)) {
00667     report_fatal_error("Error reading function '" + F->getName()+
00668                       "' from bitcode file: " + ErrorMsg);
00669   }
00670 
00671   // ... and check if another thread has already code gen'd the function.
00672   if (void *Addr = getPointerToGlobalIfAvailable(F))
00673     return Addr;
00674 
00675   if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) {
00676     bool AbortOnFailure = !F->hasExternalWeakLinkage();
00677     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
00678     addGlobalMapping(F, Addr);
00679     return Addr;
00680   }
00681 
00682   runJITOnFunctionUnlocked(F, locked);
00683 
00684   void *Addr = getPointerToGlobalIfAvailable(F);
00685   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
00686   return Addr;
00687 }
00688 
00689 void JIT::addPointerToBasicBlock(const BasicBlock *BB, void *Addr) {
00690   MutexGuard locked(lock);
00691 
00692   BasicBlockAddressMapTy::iterator I =
00693     getBasicBlockAddressMap(locked).find(BB);
00694   if (I == getBasicBlockAddressMap(locked).end()) {
00695     getBasicBlockAddressMap(locked)[BB] = Addr;
00696   } else {
00697     // ignore repeats: some BBs can be split into few MBBs?
00698   }
00699 }
00700 
00701 void JIT::clearPointerToBasicBlock(const BasicBlock *BB) {
00702   MutexGuard locked(lock);
00703   getBasicBlockAddressMap(locked).erase(BB);
00704 }
00705 
00706 void *JIT::getPointerToBasicBlock(BasicBlock *BB) {
00707   // make sure it's function is compiled by JIT
00708   (void)getPointerToFunction(BB->getParent());
00709 
00710   // resolve basic block address
00711   MutexGuard locked(lock);
00712 
00713   BasicBlockAddressMapTy::iterator I =
00714     getBasicBlockAddressMap(locked).find(BB);
00715   if (I != getBasicBlockAddressMap(locked).end()) {
00716     return I->second;
00717   } else {
00718     llvm_unreachable("JIT does not have BB address for address-of-label, was"
00719                      " it eliminated by optimizer?");
00720   }
00721 }
00722 
00723 void *JIT::getPointerToNamedFunction(const std::string &Name,
00724                                      bool AbortOnFailure){
00725   if (!isSymbolSearchingDisabled()) {
00726     void *ptr = JMM->getPointerToNamedFunction(Name, false);
00727     if (ptr)
00728       return ptr;
00729   }
00730 
00731   /// If a LazyFunctionCreator is installed, use it to get/create the function.
00732   if (LazyFunctionCreator)
00733     if (void *RP = LazyFunctionCreator(Name))
00734       return RP;
00735 
00736   if (AbortOnFailure) {
00737     report_fatal_error("Program used external function '"+Name+
00738                       "' which could not be resolved!");
00739   }
00740   return 0;
00741 }
00742 
00743 
00744 /// getOrEmitGlobalVariable - Return the address of the specified global
00745 /// variable, possibly emitting it to memory if needed.  This is used by the
00746 /// Emitter.
00747 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
00748   MutexGuard locked(lock);
00749 
00750   void *Ptr = getPointerToGlobalIfAvailable(GV);
00751   if (Ptr) return Ptr;
00752 
00753   // If the global is external, just remember the address.
00754   if (GV->isDeclaration() || GV->hasAvailableExternallyLinkage()) {
00755 #if HAVE___DSO_HANDLE
00756     if (GV->getName() == "__dso_handle")
00757       return (void*)&__dso_handle;
00758 #endif
00759     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName());
00760     if (Ptr == 0) {
00761       report_fatal_error("Could not resolve external global address: "
00762                         +GV->getName());
00763     }
00764     addGlobalMapping(GV, Ptr);
00765   } else {
00766     // If the global hasn't been emitted to memory yet, allocate space and
00767     // emit it into memory.
00768     Ptr = getMemoryForGV(GV);
00769     addGlobalMapping(GV, Ptr);
00770     EmitGlobalVariable(GV);  // Initialize the variable.
00771   }
00772   return Ptr;
00773 }
00774 
00775 /// recompileAndRelinkFunction - This method is used to force a function
00776 /// which has already been compiled, to be compiled again, possibly
00777 /// after it has been modified. Then the entry to the old copy is overwritten
00778 /// with a branch to the new copy. If there was no old copy, this acts
00779 /// just like JIT::getPointerToFunction().
00780 ///
00781 void *JIT::recompileAndRelinkFunction(Function *F) {
00782   void *OldAddr = getPointerToGlobalIfAvailable(F);
00783 
00784   // If it's not already compiled there is no reason to patch it up.
00785   if (OldAddr == 0) { return getPointerToFunction(F); }
00786 
00787   // Delete the old function mapping.
00788   addGlobalMapping(F, 0);
00789 
00790   // Recodegen the function
00791   runJITOnFunction(F);
00792 
00793   // Update state, forward the old function to the new function.
00794   void *Addr = getPointerToGlobalIfAvailable(F);
00795   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
00796   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
00797   return Addr;
00798 }
00799 
00800 /// getMemoryForGV - This method abstracts memory allocation of global
00801 /// variable so that the JIT can allocate thread local variables depending
00802 /// on the target.
00803 ///
00804 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
00805   char *Ptr;
00806 
00807   // GlobalVariable's which are not "constant" will cause trouble in a server
00808   // situation. It's returned in the same block of memory as code which may
00809   // not be writable.
00810   if (isGVCompilationDisabled() && !GV->isConstant()) {
00811     report_fatal_error("Compilation of non-internal GlobalValue is disabled!");
00812   }
00813 
00814   // Some applications require globals and code to live together, so they may
00815   // be allocated into the same buffer, but in general globals are allocated
00816   // through the memory manager which puts them near the code but not in the
00817   // same buffer.
00818   Type *GlobalType = GV->getType()->getElementType();
00819   size_t S = getDataLayout()->getTypeAllocSize(GlobalType);
00820   size_t A = getDataLayout()->getPreferredAlignment(GV);
00821   if (GV->isThreadLocal()) {
00822     MutexGuard locked(lock);
00823     Ptr = TJI.allocateThreadLocalMemory(S);
00824   } else if (TJI.allocateSeparateGVMemory()) {
00825     if (A <= 8) {
00826       Ptr = (char*)malloc(S);
00827     } else {
00828       // Allocate S+A bytes of memory, then use an aligned pointer within that
00829       // space.
00830       Ptr = (char*)malloc(S+A);
00831       unsigned MisAligned = ((intptr_t)Ptr & (A-1));
00832       Ptr = Ptr + (MisAligned ? (A-MisAligned) : 0);
00833     }
00834   } else if (AllocateGVsWithCode) {
00835     Ptr = (char*)JCE->allocateSpace(S, A);
00836   } else {
00837     Ptr = (char*)JCE->allocateGlobal(S, A);
00838   }
00839   return Ptr;
00840 }
00841 
00842 void JIT::addPendingFunction(Function *F) {
00843   MutexGuard locked(lock);
00844   jitstate->getPendingFunctions(locked).push_back(F);
00845 }
00846 
00847 
00848 JITEventListener::~JITEventListener() {}