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/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Function.h"
00019 #include "llvm/GlobalVariable.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/ModuleProvider.h"
00022 #include "llvm/CodeGen/MachineCodeEmitter.h"
00023 #include "llvm/ExecutionEngine/GenericValue.h"
00024 #include "llvm/Support/MutexGuard.h"
00025 #include "llvm/System/DynamicLibrary.h"
00026 #include "llvm/Target/TargetData.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Target/TargetJITInfo.h"
00029 
00030 #include "llvm/Config/config.h"
00031 
00032 using namespace llvm;
00033 
00034 #ifdef __APPLE__ 
00035 // Apple gcc defaults to -fuse-cxa-atexit (i.e. calls __cxa_atexit instead
00036 // of atexit). It passes the address of linker generated symbol __dso_handle
00037 // to the function.
00038 // This configuration change happened at version 5330.
00039 # include <AvailabilityMacros.h>
00040 # if defined(MAC_OS_X_VERSION_10_4) && \
00041      ((MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4) || \
00042       (MAC_OS_X_VERSION_MIN_REQUIRED == MAC_OS_X_VERSION_10_4 && \
00043        __APPLE_CC__ >= 5330))
00044 #  ifndef HAVE___DSO_HANDLE
00045 #   define HAVE___DSO_HANDLE 1
00046 #  endif
00047 # endif
00048 #endif
00049 
00050 #if HAVE___DSO_HANDLE
00051 extern void *__dso_handle __attribute__ ((__visibility__ ("hidden")));
00052 #endif
00053 
00054 namespace {
00055 
00056 static struct RegisterJIT {
00057   RegisterJIT() { JIT::Register(); }
00058 } JITRegistrator;
00059 
00060 }
00061 
00062 namespace llvm {
00063   void LinkInJIT() {
00064   }
00065 }
00066 
00067 
00068 #if defined(__GNUC__) && !defined(__ARM__EABI__)
00069  
00070 // libgcc defines the __register_frame function to dynamically register new
00071 // dwarf frames for exception handling. This functionality is not portable
00072 // across compilers and is only provided by GCC. We use the __register_frame
00073 // function here so that code generated by the JIT cooperates with the unwinding
00074 // runtime of libgcc. When JITting with exception handling enable, LLVM
00075 // generates dwarf frames and registers it to libgcc with __register_frame.
00076 //
00077 // The __register_frame function works with Linux.
00078 //
00079 // Unfortunately, this functionality seems to be in libgcc after the unwinding
00080 // library of libgcc for darwin was written. The code for darwin overwrites the
00081 // value updated by __register_frame with a value fetched with "keymgr".
00082 // "keymgr" is an obsolete functionality, which should be rewritten some day.
00083 // In the meantime, since "keymgr" is on all libgccs shipped with apple-gcc, we
00084 // need a workaround in LLVM which uses the "keymgr" to dynamically modify the
00085 // values of an opaque key, used by libgcc to find dwarf tables.
00086 
00087 extern "C" void __register_frame(void*);
00088 
00089 #if defined(__APPLE__)
00090 
00091 namespace {
00092 
00093 // LibgccObject - This is the structure defined in libgcc. There is no #include
00094 // provided for this structure, so we also define it here. libgcc calls it
00095 // "struct object". The structure is undocumented in libgcc.
00096 struct LibgccObject {
00097   void *unused1;
00098   void *unused2;
00099   void *unused3;
00100   
00101   /// frame - Pointer to the exception table.
00102   void *frame;
00103   
00104   /// encoding -  The encoding of the object?
00105   union {
00106     struct {
00107       unsigned long sorted : 1;
00108       unsigned long from_array : 1;
00109       unsigned long mixed_encoding : 1;
00110       unsigned long encoding : 8;
00111       unsigned long count : 21; 
00112     } b;
00113     size_t i;
00114   } encoding;
00115   
00116   /// fde_end - libgcc defines this field only if some macro is defined. We
00117   /// include this field even if it may not there, to make libgcc happy.
00118   char *fde_end;
00119   
00120   /// next - At least we know it's a chained list!
00121   struct LibgccObject *next;
00122 };
00123 
00124 // "kemgr" stuff. Apparently, all frame tables are stored there.
00125 extern "C" void _keymgr_set_and_unlock_processwide_ptr(int, void *);
00126 extern "C" void *_keymgr_get_and_lock_processwide_ptr(int);
00127 #define KEYMGR_GCC3_DW2_OBJ_LIST        302     /* Dwarf2 object list  */
00128 
00129 /// LibgccObjectInfo - libgcc defines this struct as km_object_info. It
00130 /// probably contains all dwarf tables that are loaded.
00131 struct LibgccObjectInfo {
00132 
00133   /// seenObjects - LibgccObjects already parsed by the unwinding runtime.
00134   ///
00135   struct LibgccObject* seenObjects;
00136 
00137   /// unseenObjects - LibgccObjects not parsed yet by the unwinding runtime.
00138   ///
00139   struct LibgccObject* unseenObjects;
00140   
00141   unsigned unused[2];
00142 };
00143 
00144 // for DW_EH_PE_omit
00145 #include "llvm/Support/Dwarf.h"
00146 
00147 /// darwin_register_frame - Since __register_frame does not work with darwin's
00148 /// libgcc,we provide our own function, which "tricks" libgcc by modifying the
00149 /// "Dwarf2 object list" key.
00150 void DarwinRegisterFrame(void* FrameBegin) {
00151   // Get the key.
00152   struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
00153     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
00154   
00155   // Allocate a new LibgccObject to represent this frame. Deallocation of this
00156   // object may be impossible: since darwin code in libgcc was written after
00157   // the ability to dynamically register frames, things may crash if we
00158   // deallocate it.
00159   struct LibgccObject* ob = (struct LibgccObject*)
00160     malloc(sizeof(struct LibgccObject));
00161   
00162   // Do like libgcc for the values of the field.
00163   ob->unused1 = (void *)-1;
00164   ob->unused2 = 0;
00165   ob->unused3 = 0;
00166   ob->frame = FrameBegin;
00167   ob->encoding.i = 0; 
00168   ob->encoding.b.encoding = llvm::dwarf::DW_EH_PE_omit;
00169   
00170   // Put the info on both places, as libgcc uses the first or the the second
00171   // field. Note that we rely on having two pointers here. If fde_end was a
00172   // char, things would get complicated.
00173   ob->fde_end = (char*)LOI->unseenObjects;
00174   ob->next = LOI->unseenObjects;
00175   
00176   // Update the key's unseenObjects list.
00177   LOI->unseenObjects = ob;
00178   
00179   // Finally update the "key". Apparently, libgcc requires it. 
00180   _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
00181                                          LOI);
00182 
00183 }
00184 
00185 }
00186 #endif // __APPLE__
00187 #endif // __GNUC__
00188 
00189 /// createJIT - This is the factory method for creating a JIT for the current
00190 /// machine, it does not fall back to the interpreter.  This takes ownership
00191 /// of the module provider.
00192 ExecutionEngine *ExecutionEngine::createJIT(ModuleProvider *MP,
00193                                             std::string *ErrorStr,
00194                                             JITMemoryManager *JMM,
00195                                             bool Fast) {
00196   ExecutionEngine *EE = JIT::createJIT(MP, ErrorStr, JMM, Fast);
00197   if (!EE) return 0;
00198   
00199   // Make sure we can resolve symbols in the program as well. The zero arg
00200   // to the function tells DynamicLibrary to load the program, not a library.
00201   sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr);
00202   return EE;
00203 }
00204 
00205 JIT::JIT(ModuleProvider *MP, TargetMachine &tm, TargetJITInfo &tji,
00206          JITMemoryManager *JMM, bool Fast)
00207   : ExecutionEngine(MP), TM(tm), TJI(tji) {
00208   setTargetData(TM.getTargetData());
00209 
00210   jitstate = new JITState(MP);
00211 
00212   // Initialize MCE
00213   MCE = createEmitter(*this, JMM);
00214 
00215   // Add target data
00216   MutexGuard locked(lock);
00217   FunctionPassManager &PM = jitstate->getPM(locked);
00218   PM.add(new TargetData(*TM.getTargetData()));
00219 
00220   // Turn the machine code intermediate representation into bytes in memory that
00221   // may be executed.
00222   if (TM.addPassesToEmitMachineCode(PM, *MCE, Fast)) {
00223     cerr << "Target does not support machine code emission!\n";
00224     abort();
00225   }
00226   
00227   // Register routine for informing unwinding runtime about new EH frames
00228 #if defined(__GNUC__) && !defined(__ARM_EABI__)
00229 #if defined(__APPLE__)
00230   struct LibgccObjectInfo* LOI = (struct LibgccObjectInfo*)
00231     _keymgr_get_and_lock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST);
00232   
00233   // The key is created on demand, and libgcc creates it the first time an
00234   // exception occurs. Since we need the key to register frames, we create
00235   // it now.
00236   if (!LOI) {
00237     LOI = (LibgccObjectInfo*)malloc(sizeof(struct LibgccObjectInfo)); 
00238     _keymgr_set_and_unlock_processwide_ptr(KEYMGR_GCC3_DW2_OBJ_LIST,
00239                                            LOI);
00240   }
00241   InstallExceptionTableRegister(DarwinRegisterFrame);
00242 #else
00243   InstallExceptionTableRegister(__register_frame);
00244 #endif // __APPLE__
00245 #endif // __GNUC__
00246   
00247   // Initialize passes.
00248   PM.doInitialization();
00249 }
00250 
00251 JIT::~JIT() {
00252   delete jitstate;
00253   delete MCE;
00254   delete &TM;
00255 }
00256 
00257 /// addModuleProvider - Add a new ModuleProvider to the JIT.  If we previously
00258 /// removed the last ModuleProvider, we need re-initialize jitstate with a valid
00259 /// ModuleProvider.
00260 void JIT::addModuleProvider(ModuleProvider *MP) {
00261   MutexGuard locked(lock);
00262 
00263   if (Modules.empty()) {
00264     assert(!jitstate && "jitstate should be NULL if Modules vector is empty!");
00265 
00266     jitstate = new JITState(MP);
00267 
00268     FunctionPassManager &PM = jitstate->getPM(locked);
00269     PM.add(new TargetData(*TM.getTargetData()));
00270 
00271     // Turn the machine code intermediate representation into bytes in memory
00272     // that may be executed.
00273     if (TM.addPassesToEmitMachineCode(PM, *MCE, false /*fast*/)) {
00274       cerr << "Target does not support machine code emission!\n";
00275       abort();
00276     }
00277     
00278     // Initialize passes.
00279     PM.doInitialization();
00280   }
00281   
00282   ExecutionEngine::addModuleProvider(MP);
00283 }
00284 
00285 /// removeModuleProvider - If we are removing the last ModuleProvider, 
00286 /// invalidate the jitstate since the PassManager it contains references a
00287 /// released ModuleProvider.
00288 Module *JIT::removeModuleProvider(ModuleProvider *MP, std::string *E) {
00289   Module *result = ExecutionEngine::removeModuleProvider(MP, E);
00290   
00291   MutexGuard locked(lock);
00292   if (Modules.empty()) {
00293     delete jitstate;
00294     jitstate = 0;
00295   }
00296   
00297   return result;
00298 }
00299 
00300 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
00301 /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
00302 /// the underlying module.
00303 void JIT::deleteModuleProvider(ModuleProvider *MP, std::string *E) {
00304   ExecutionEngine::deleteModuleProvider(MP, E);
00305   
00306   MutexGuard locked(lock);
00307   if (Modules.empty()) {
00308     delete jitstate;
00309     jitstate = 0;
00310   }
00311 }
00312 
00313 /// run - Start execution with the specified function and arguments.
00314 ///
00315 GenericValue JIT::runFunction(Function *F,
00316                               const std::vector<GenericValue> &ArgValues) {
00317   assert(F && "Function *F was null at entry to run()");
00318 
00319   void *FPtr = getPointerToFunction(F);
00320   assert(FPtr && "Pointer to fn's code was null after getPointerToFunction");
00321   const FunctionType *FTy = F->getFunctionType();
00322   const Type *RetTy = FTy->getReturnType();
00323 
00324   assert((FTy->getNumParams() <= ArgValues.size() || FTy->isVarArg()) &&
00325          "Too many arguments passed into function!");
00326   assert(FTy->getNumParams() == ArgValues.size() &&
00327          "This doesn't support passing arguments through varargs (yet)!");
00328 
00329   // Handle some common cases first.  These cases correspond to common `main'
00330   // prototypes.
00331   if (RetTy == Type::Int32Ty || RetTy == Type::VoidTy) {
00332     switch (ArgValues.size()) {
00333     case 3:
00334       if (FTy->getParamType(0) == Type::Int32Ty &&
00335           isa<PointerType>(FTy->getParamType(1)) &&
00336           isa<PointerType>(FTy->getParamType(2))) {
00337         int (*PF)(int, char **, const char **) =
00338           (int(*)(int, char **, const char **))(intptr_t)FPtr;
00339 
00340         // Call the function.
00341         GenericValue rv;
00342         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), 
00343                                  (char **)GVTOP(ArgValues[1]),
00344                                  (const char **)GVTOP(ArgValues[2])));
00345         return rv;
00346       }
00347       break;
00348     case 2:
00349       if (FTy->getParamType(0) == Type::Int32Ty &&
00350           isa<PointerType>(FTy->getParamType(1))) {
00351         int (*PF)(int, char **) = (int(*)(int, char **))(intptr_t)FPtr;
00352 
00353         // Call the function.
00354         GenericValue rv;
00355         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue(), 
00356                                  (char **)GVTOP(ArgValues[1])));
00357         return rv;
00358       }
00359       break;
00360     case 1:
00361       if (FTy->getNumParams() == 1 &&
00362           FTy->getParamType(0) == Type::Int32Ty) {
00363         GenericValue rv;
00364         int (*PF)(int) = (int(*)(int))(intptr_t)FPtr;
00365         rv.IntVal = APInt(32, PF(ArgValues[0].IntVal.getZExtValue()));
00366         return rv;
00367       }
00368       break;
00369     }
00370   }
00371 
00372   // Handle cases where no arguments are passed first.
00373   if (ArgValues.empty()) {
00374     GenericValue rv;
00375     switch (RetTy->getTypeID()) {
00376     default: assert(0 && "Unknown return type for function call!");
00377     case Type::IntegerTyID: {
00378       unsigned BitWidth = cast<IntegerType>(RetTy)->getBitWidth();
00379       if (BitWidth == 1)
00380         rv.IntVal = APInt(BitWidth, ((bool(*)())(intptr_t)FPtr)());
00381       else if (BitWidth <= 8)
00382         rv.IntVal = APInt(BitWidth, ((char(*)())(intptr_t)FPtr)());
00383       else if (BitWidth <= 16)
00384         rv.IntVal = APInt(BitWidth, ((short(*)())(intptr_t)FPtr)());
00385       else if (BitWidth <= 32)
00386         rv.IntVal = APInt(BitWidth, ((int(*)())(intptr_t)FPtr)());
00387       else if (BitWidth <= 64)
00388         rv.IntVal = APInt(BitWidth, ((int64_t(*)())(intptr_t)FPtr)());
00389       else 
00390         assert(0 && "Integer types > 64 bits not supported");
00391       return rv;
00392     }
00393     case Type::VoidTyID:
00394       rv.IntVal = APInt(32, ((int(*)())(intptr_t)FPtr)());
00395       return rv;
00396     case Type::FloatTyID:
00397       rv.FloatVal = ((float(*)())(intptr_t)FPtr)();
00398       return rv;
00399     case Type::DoubleTyID:
00400       rv.DoubleVal = ((double(*)())(intptr_t)FPtr)();
00401       return rv;
00402     case Type::X86_FP80TyID:
00403     case Type::FP128TyID:
00404     case Type::PPC_FP128TyID:
00405       assert(0 && "long double not supported yet");
00406       return rv;
00407     case Type::PointerTyID:
00408       return PTOGV(((void*(*)())(intptr_t)FPtr)());
00409     }
00410   }
00411 
00412   // Okay, this is not one of our quick and easy cases.  Because we don't have a
00413   // full FFI, we have to codegen a nullary stub function that just calls the
00414   // function we are interested in, passing in constants for all of the
00415   // arguments.  Make this function and return.
00416 
00417   // First, create the function.
00418   FunctionType *STy=FunctionType::get(RetTy, std::vector<const Type*>(), false);
00419   Function *Stub = Function::Create(STy, Function::InternalLinkage, "",
00420                                     F->getParent());
00421 
00422   // Insert a basic block.
00423   BasicBlock *StubBB = BasicBlock::Create("", Stub);
00424 
00425   // Convert all of the GenericValue arguments over to constants.  Note that we
00426   // currently don't support varargs.
00427   SmallVector<Value*, 8> Args;
00428   for (unsigned i = 0, e = ArgValues.size(); i != e; ++i) {
00429     Constant *C = 0;
00430     const Type *ArgTy = FTy->getParamType(i);
00431     const GenericValue &AV = ArgValues[i];
00432     switch (ArgTy->getTypeID()) {
00433     default: assert(0 && "Unknown argument type for function call!");
00434     case Type::IntegerTyID:
00435         C = ConstantInt::get(AV.IntVal);
00436         break;
00437     case Type::FloatTyID:
00438         C = ConstantFP::get(APFloat(AV.FloatVal));
00439         break;
00440     case Type::DoubleTyID:
00441         C = ConstantFP::get(APFloat(AV.DoubleVal));
00442         break;
00443     case Type::PPC_FP128TyID:
00444     case Type::X86_FP80TyID:
00445     case Type::FP128TyID:
00446         C = ConstantFP::get(APFloat(AV.IntVal));
00447         break;
00448     case Type::PointerTyID:
00449       void *ArgPtr = GVTOP(AV);
00450       if (sizeof(void*) == 4)
00451         C = ConstantInt::get(Type::Int32Ty, (int)(intptr_t)ArgPtr);
00452       else
00453         C = ConstantInt::get(Type::Int64Ty, (intptr_t)ArgPtr);
00454       C = ConstantExpr::getIntToPtr(C, ArgTy);  // Cast the integer to pointer
00455       break;
00456     }
00457     Args.push_back(C);
00458   }
00459 
00460   CallInst *TheCall = CallInst::Create(F, Args.begin(), Args.end(),
00461                                        "", StubBB);
00462   TheCall->setCallingConv(F->getCallingConv());
00463   TheCall->setTailCall();
00464   if (TheCall->getType() != Type::VoidTy)
00465     ReturnInst::Create(TheCall, StubBB);    // Return result of the call.
00466   else
00467     ReturnInst::Create(StubBB);             // Just return void.
00468 
00469   // Finally, return the value returned by our nullary stub function.
00470   return runFunction(Stub, std::vector<GenericValue>());
00471 }
00472 
00473 /// runJITOnFunction - Run the FunctionPassManager full of
00474 /// just-in-time compilation passes on F, hopefully filling in
00475 /// GlobalAddress[F] with the address of F's machine code.
00476 ///
00477 void JIT::runJITOnFunction(Function *F) {
00478   static bool isAlreadyCodeGenerating = false;
00479 
00480   MutexGuard locked(lock);
00481   assert(!isAlreadyCodeGenerating && "Error: Recursive compilation detected!");
00482 
00483   // JIT the function
00484   isAlreadyCodeGenerating = true;
00485   jitstate->getPM(locked).run(*F);
00486   isAlreadyCodeGenerating = false;
00487 
00488   // If the function referred to a global variable that had not yet been
00489   // emitted, it allocates memory for the global, but doesn't emit it yet.  Emit
00490   // all of these globals now.
00491   while (!jitstate->getPendingGlobals(locked).empty()) {
00492     const GlobalVariable *GV = jitstate->getPendingGlobals(locked).back();
00493     jitstate->getPendingGlobals(locked).pop_back();
00494     EmitGlobalVariable(GV);
00495   }
00496 }
00497 
00498 /// getPointerToFunction - This method is used to get the address of the
00499 /// specified function, compiling it if neccesary.
00500 ///
00501 void *JIT::getPointerToFunction(Function *F) {
00502 
00503   if (void *Addr = getPointerToGlobalIfAvailable(F))
00504     return Addr;   // Check if function already code gen'd
00505 
00506   // Make sure we read in the function if it exists in this Module.
00507   if (F->hasNotBeenReadFromBitcode()) {
00508     // Determine the module provider this function is provided by.
00509     Module *M = F->getParent();
00510     ModuleProvider *MP = 0;
00511     for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
00512       if (Modules[i]->getModule() == M) {
00513         MP = Modules[i];
00514         break;
00515       }
00516     }
00517     assert(MP && "Function isn't in a module we know about!");
00518     
00519     std::string ErrorMsg;
00520     if (MP->materializeFunction(F, &ErrorMsg)) {
00521       cerr << "Error reading function '" << F->getName()
00522            << "' from bitcode file: " << ErrorMsg << "\n";
00523       abort();
00524     }
00525 
00526     // Now retry to get the address.
00527     if (void *Addr = getPointerToGlobalIfAvailable(F))
00528       return Addr;
00529   }
00530 
00531   MutexGuard locked(lock);
00532 
00533   if (F->isDeclaration()) {
00534     bool AbortOnFailure = F->getLinkage() != GlobalValue::ExternalWeakLinkage;
00535     void *Addr = getPointerToNamedFunction(F->getName(), AbortOnFailure);
00536     addGlobalMapping(F, Addr);
00537     return Addr;
00538   }
00539 
00540   runJITOnFunction(F);
00541 
00542   void *Addr = getPointerToGlobalIfAvailable(F);
00543   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
00544   return Addr;
00545 }
00546 
00547 /// getOrEmitGlobalVariable - Return the address of the specified global
00548 /// variable, possibly emitting it to memory if needed.  This is used by the
00549 /// Emitter.
00550 void *JIT::getOrEmitGlobalVariable(const GlobalVariable *GV) {
00551   MutexGuard locked(lock);
00552 
00553   void *Ptr = getPointerToGlobalIfAvailable(GV);
00554   if (Ptr) return Ptr;
00555 
00556   // If the global is external, just remember the address.
00557   if (GV->isDeclaration()) {
00558 #if HAVE___DSO_HANDLE
00559     if (GV->getName() == "__dso_handle")
00560       return (void*)&__dso_handle;
00561 #endif
00562     Ptr = sys::DynamicLibrary::SearchForAddressOfSymbol(GV->getName().c_str());
00563     if (Ptr == 0) {
00564       cerr << "Could not resolve external global address: "
00565            << GV->getName() << "\n";
00566       abort();
00567     addGlobalMapping(GV, Ptr);
00568     }
00569   } else {
00570     // GlobalVariable's which are not "constant" will cause trouble in a server
00571     // situation. It's returned in the same block of memory as code which may
00572     // not be writable.
00573     if (isGVCompilationDisabled() && !GV->isConstant()) {
00574       cerr << "Compilation of non-internal GlobalValue is disabled!\n";
00575       abort();
00576     }
00577     // If the global hasn't been emitted to memory yet, allocate space and
00578     // emit it into memory.  It goes in the same array as the generated
00579     // code, jump tables, etc.
00580     const Type *GlobalType = GV->getType()->getElementType();
00581     size_t S = getTargetData()->getTypePaddedSize(GlobalType);
00582     size_t A = getTargetData()->getPreferredAlignment(GV);
00583     if (GV->isThreadLocal()) {
00584       MutexGuard locked(lock);
00585       Ptr = TJI.allocateThreadLocalMemory(S);
00586     } else if (TJI.allocateSeparateGVMemory()) {
00587       if (A <= 8) {
00588         Ptr = malloc(S);
00589       } else {
00590         // Allocate S+A bytes of memory, then use an aligned pointer within that
00591         // space.
00592         Ptr = malloc(S+A);
00593         unsigned MisAligned = ((intptr_t)Ptr & (A-1));
00594         Ptr = (char*)Ptr + (MisAligned ? (A-MisAligned) : 0);
00595       }
00596     } else {
00597       Ptr = MCE->allocateSpace(S, A);
00598     }
00599     addGlobalMapping(GV, Ptr);
00600     EmitGlobalVariable(GV);
00601   }
00602   return Ptr;
00603 }
00604 
00605 /// recompileAndRelinkFunction - This method is used to force a function
00606 /// which has already been compiled, to be compiled again, possibly
00607 /// after it has been modified. Then the entry to the old copy is overwritten
00608 /// with a branch to the new copy. If there was no old copy, this acts
00609 /// just like JIT::getPointerToFunction().
00610 ///
00611 void *JIT::recompileAndRelinkFunction(Function *F) {
00612   void *OldAddr = getPointerToGlobalIfAvailable(F);
00613 
00614   // If it's not already compiled there is no reason to patch it up.
00615   if (OldAddr == 0) { return getPointerToFunction(F); }
00616 
00617   // Delete the old function mapping.
00618   addGlobalMapping(F, 0);
00619 
00620   // Recodegen the function
00621   runJITOnFunction(F);
00622 
00623   // Update state, forward the old function to the new function.
00624   void *Addr = getPointerToGlobalIfAvailable(F);
00625   assert(Addr && "Code generation didn't add function to GlobalAddress table!");
00626   TJI.replaceMachineCodeForFunction(OldAddr, Addr);
00627   return Addr;
00628 }
00629 
00630 /// getMemoryForGV - This method abstracts memory allocation of global
00631 /// variable so that the JIT can allocate thread local variables depending
00632 /// on the target.
00633 ///
00634 char* JIT::getMemoryForGV(const GlobalVariable* GV) {
00635   const Type *ElTy = GV->getType()->getElementType();
00636   size_t GVSize = (size_t)getTargetData()->getTypePaddedSize(ElTy);
00637   if (GV->isThreadLocal()) {
00638     MutexGuard locked(lock);
00639     return TJI.allocateThreadLocalMemory(GVSize);
00640   } else {
00641     return new char[GVSize];
00642   }
00643 }