LLVM API Documentation

ExecutionEngine.cpp

Go to the documentation of this file.
00001 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
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 file defines the common interface used by the various execution engine
00011 // subclasses.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "jit"
00016 #include "llvm/ExecutionEngine/ExecutionEngine.h"
00017 
00018 #include "llvm/Constants.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/ModuleProvider.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Config/alloca.h"
00024 #include "llvm/ExecutionEngine/GenericValue.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/MutexGuard.h"
00028 #include "llvm/Support/ValueHandle.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/System/DynamicLibrary.h"
00031 #include "llvm/System/Host.h"
00032 #include "llvm/Target/TargetData.h"
00033 #include <cmath>
00034 #include <cstring>
00035 using namespace llvm;
00036 
00037 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
00038 STATISTIC(NumGlobals  , "Number of global vars initialized");
00039 
00040 ExecutionEngine *(*ExecutionEngine::JITCtor)(ModuleProvider *MP,
00041                                              std::string *ErrorStr,
00042                                              JITMemoryManager *JMM,
00043                                              CodeGenOpt::Level OptLevel,
00044                                              bool GVsWithCode) = 0;
00045 ExecutionEngine *(*ExecutionEngine::InterpCtor)(ModuleProvider *MP,
00046                                                 std::string *ErrorStr) = 0;
00047 ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
00048 
00049 
00050 ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
00051   LazyCompilationDisabled = false;
00052   GVCompilationDisabled   = false;
00053   SymbolSearchingDisabled = false;
00054   DlsymStubsEnabled       = false;
00055   Modules.push_back(P);
00056   assert(P && "ModuleProvider is null?");
00057 }
00058 
00059 ExecutionEngine::~ExecutionEngine() {
00060   clearAllGlobalMappings();
00061   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
00062     delete Modules[i];
00063 }
00064 
00065 char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
00066   const Type *ElTy = GV->getType()->getElementType();
00067   size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
00068   return new char[GVSize];
00069 }
00070 
00071 /// removeModuleProvider - Remove a ModuleProvider from the list of modules.
00072 /// Relases the Module from the ModuleProvider, materializing it in the
00073 /// process, and returns the materialized Module.
00074 Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P, 
00075                                               std::string *ErrInfo) {
00076   for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 
00077         E = Modules.end(); I != E; ++I) {
00078     ModuleProvider *MP = *I;
00079     if (MP == P) {
00080       Modules.erase(I);
00081       clearGlobalMappingsFromModule(MP->getModule());
00082       return MP->releaseModule(ErrInfo);
00083     }
00084   }
00085   return NULL;
00086 }
00087 
00088 /// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
00089 /// and deletes the ModuleProvider and owned Module.  Avoids materializing 
00090 /// the underlying module.
00091 void ExecutionEngine::deleteModuleProvider(ModuleProvider *P, 
00092                                            std::string *ErrInfo) {
00093   for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(), 
00094       E = Modules.end(); I != E; ++I) {
00095     ModuleProvider *MP = *I;
00096     if (MP == P) {
00097       Modules.erase(I);
00098       clearGlobalMappingsFromModule(MP->getModule());
00099       delete MP;
00100       return;
00101     }
00102   }
00103 }
00104 
00105 /// FindFunctionNamed - Search all of the active modules to find the one that
00106 /// defines FnName.  This is very slow operation and shouldn't be used for
00107 /// general code.
00108 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
00109   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
00110     if (Function *F = Modules[i]->getModule()->getFunction(FnName))
00111       return F;
00112   }
00113   return 0;
00114 }
00115 
00116 
00117 /// addGlobalMapping - Tell the execution engine that the specified global is
00118 /// at the specified location.  This is used internally as functions are JIT'd
00119 /// and as global variables are laid out in memory.  It can and should also be
00120 /// used by clients of the EE that want to have an LLVM global overlay
00121 /// existing data in memory.
00122 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
00123   MutexGuard locked(lock);
00124 
00125   DEBUG(errs() << "JIT: Map \'" << GV->getName() 
00126         << "\' to [" << Addr << "]\n";);
00127   void *&CurVal = state.getGlobalAddressMap(locked)[GV];
00128   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
00129   CurVal = Addr;
00130   
00131   // If we are using the reverse mapping, add it too
00132   if (!state.getGlobalAddressReverseMap(locked).empty()) {
00133     AssertingVH<const GlobalValue> &V =
00134       state.getGlobalAddressReverseMap(locked)[Addr];
00135     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
00136     V = GV;
00137   }
00138 }
00139 
00140 /// clearAllGlobalMappings - Clear all global mappings and start over again
00141 /// use in dynamic compilation scenarios when you want to move globals
00142 void ExecutionEngine::clearAllGlobalMappings() {
00143   MutexGuard locked(lock);
00144   
00145   state.getGlobalAddressMap(locked).clear();
00146   state.getGlobalAddressReverseMap(locked).clear();
00147 }
00148 
00149 /// clearGlobalMappingsFromModule - Clear all global mappings that came from a
00150 /// particular module, because it has been removed from the JIT.
00151 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
00152   MutexGuard locked(lock);
00153   
00154   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
00155     state.getGlobalAddressMap(locked).erase(&*FI);
00156     state.getGlobalAddressReverseMap(locked).erase(&*FI);
00157   }
00158   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 
00159        GI != GE; ++GI) {
00160     state.getGlobalAddressMap(locked).erase(&*GI);
00161     state.getGlobalAddressReverseMap(locked).erase(&*GI);
00162   }
00163 }
00164 
00165 /// updateGlobalMapping - Replace an existing mapping for GV with a new
00166 /// address.  This updates both maps as required.  If "Addr" is null, the
00167 /// entry for the global is removed from the mappings.
00168 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
00169   MutexGuard locked(lock);
00170 
00171   std::map<AssertingVH<const GlobalValue>, void *> &Map =
00172     state.getGlobalAddressMap(locked);
00173 
00174   // Deleting from the mapping?
00175   if (Addr == 0) {
00176     std::map<AssertingVH<const GlobalValue>, void *>::iterator I = Map.find(GV);
00177     void *OldVal;
00178     if (I == Map.end())
00179       OldVal = 0;
00180     else {
00181       OldVal = I->second;
00182       Map.erase(I); 
00183     }
00184     
00185     if (!state.getGlobalAddressReverseMap(locked).empty())
00186       state.getGlobalAddressReverseMap(locked).erase(OldVal);
00187     return OldVal;
00188   }
00189   
00190   void *&CurVal = Map[GV];
00191   void *OldVal = CurVal;
00192 
00193   if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
00194     state.getGlobalAddressReverseMap(locked).erase(CurVal);
00195   CurVal = Addr;
00196   
00197   // If we are using the reverse mapping, add it too
00198   if (!state.getGlobalAddressReverseMap(locked).empty()) {
00199     AssertingVH<const GlobalValue> &V =
00200       state.getGlobalAddressReverseMap(locked)[Addr];
00201     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
00202     V = GV;
00203   }
00204   return OldVal;
00205 }
00206 
00207 /// getPointerToGlobalIfAvailable - This returns the address of the specified
00208 /// global value if it is has already been codegen'd, otherwise it returns null.
00209 ///
00210 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
00211   MutexGuard locked(lock);
00212   
00213   std::map<AssertingVH<const GlobalValue>, void*>::iterator I =
00214     state.getGlobalAddressMap(locked).find(GV);
00215   return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
00216 }
00217 
00218 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
00219 /// at the specified address.
00220 ///
00221 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
00222   MutexGuard locked(lock);
00223 
00224   // If we haven't computed the reverse mapping yet, do so first.
00225   if (state.getGlobalAddressReverseMap(locked).empty()) {
00226     for (std::map<AssertingVH<const GlobalValue>, void *>::iterator
00227          I = state.getGlobalAddressMap(locked).begin(),
00228          E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
00229       state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
00230                                                                      I->first));
00231   }
00232 
00233   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
00234     state.getGlobalAddressReverseMap(locked).find(Addr);
00235   return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
00236 }
00237 
00238 // CreateArgv - Turn a vector of strings into a nice argv style array of
00239 // pointers to null terminated strings.
00240 //
00241 static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
00242                         const std::vector<std::string> &InputArgv) {
00243   unsigned PtrSize = EE->getTargetData()->getPointerSize();
00244   char *Result = new char[(InputArgv.size()+1)*PtrSize];
00245 
00246   DOUT << "JIT: ARGV = " << (void*)Result << "\n";
00247   const Type *SBytePtr = PointerType::getUnqual(Type::getInt8Ty(C));
00248 
00249   for (unsigned i = 0; i != InputArgv.size(); ++i) {
00250     unsigned Size = InputArgv[i].size()+1;
00251     char *Dest = new char[Size];
00252     DOUT << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n";
00253 
00254     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
00255     Dest[Size-1] = 0;
00256 
00257     // Endian safe: Result[i] = (PointerTy)Dest;
00258     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
00259                            SBytePtr);
00260   }
00261 
00262   // Null terminate it
00263   EE->StoreValueToMemory(PTOGV(0),
00264                          (GenericValue*)(Result+InputArgv.size()*PtrSize),
00265                          SBytePtr);
00266   return Result;
00267 }
00268 
00269 
00270 /// runStaticConstructorsDestructors - This method is used to execute all of
00271 /// the static constructors or destructors for a module, depending on the
00272 /// value of isDtors.
00273 void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) {
00274   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
00275   
00276   // Execute global ctors/dtors for each module in the program.
00277   
00278  GlobalVariable *GV = module->getNamedGlobal(Name);
00279 
00280  // If this global has internal linkage, or if it has a use, then it must be
00281  // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
00282  // this is the case, don't execute any of the global ctors, __main will do
00283  // it.
00284  if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
00285  
00286  // Should be an array of '{ int, void ()* }' structs.  The first value is
00287  // the init priority, which we ignore.
00288  ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
00289  if (!InitList) return;
00290  for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
00291    if (ConstantStruct *CS = 
00292        dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
00293      if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
00294    
00295      Constant *FP = CS->getOperand(1);
00296      if (FP->isNullValue())
00297        break;  // Found a null terminator, exit.
00298    
00299      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
00300        if (CE->isCast())
00301          FP = CE->getOperand(0);
00302      if (Function *F = dyn_cast<Function>(FP)) {
00303        // Execute the ctor/dtor function!
00304        runFunction(F, std::vector<GenericValue>());
00305      }
00306    }
00307 }
00308 
00309 /// runStaticConstructorsDestructors - This method is used to execute all of
00310 /// the static constructors or destructors for a program, depending on the
00311 /// value of isDtors.
00312 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
00313   // Execute global ctors/dtors for each module in the program.
00314   for (unsigned m = 0, e = Modules.size(); m != e; ++m)
00315     runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
00316 }
00317 
00318 #ifndef NDEBUG
00319 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
00320 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
00321   unsigned PtrSize = EE->getTargetData()->getPointerSize();
00322   for (unsigned i = 0; i < PtrSize; ++i)
00323     if (*(i + (uint8_t*)Loc))
00324       return false;
00325   return true;
00326 }
00327 #endif
00328 
00329 /// runFunctionAsMain - This is a helper function which wraps runFunction to
00330 /// handle the common task of starting up main with the specified argc, argv,
00331 /// and envp parameters.
00332 int ExecutionEngine::runFunctionAsMain(Function *Fn,
00333                                        const std::vector<std::string> &argv,
00334                                        const char * const * envp) {
00335   std::vector<GenericValue> GVArgs;
00336   GenericValue GVArgc;
00337   GVArgc.IntVal = APInt(32, argv.size());
00338 
00339   // Check main() type
00340   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
00341   const FunctionType *FTy = Fn->getFunctionType();
00342   const Type* PPInt8Ty = 
00343     PointerType::getUnqual(PointerType::getUnqual(
00344           Type::getInt8Ty(Fn->getContext())));
00345   switch (NumArgs) {
00346   case 3:
00347    if (FTy->getParamType(2) != PPInt8Ty) {
00348      llvm_report_error("Invalid type for third argument of main() supplied");
00349    }
00350    // FALLS THROUGH
00351   case 2:
00352    if (FTy->getParamType(1) != PPInt8Ty) {
00353      llvm_report_error("Invalid type for second argument of main() supplied");
00354    }
00355    // FALLS THROUGH
00356   case 1:
00357    if (FTy->getParamType(0) != Type::getInt32Ty(Fn->getContext())) {
00358      llvm_report_error("Invalid type for first argument of main() supplied");
00359    }
00360    // FALLS THROUGH
00361   case 0:
00362    if (!isa<IntegerType>(FTy->getReturnType()) &&
00363        FTy->getReturnType() != Type::getVoidTy(FTy->getContext())) {
00364      llvm_report_error("Invalid return type of main() supplied");
00365    }
00366    break;
00367   default:
00368    llvm_report_error("Invalid number of arguments of main() supplied");
00369   }
00370   
00371   if (NumArgs) {
00372     GVArgs.push_back(GVArgc); // Arg #0 = argc.
00373     if (NumArgs > 1) {
00374       // Arg #1 = argv.
00375       GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv))); 
00376       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
00377              "argv[0] was null after CreateArgv");
00378       if (NumArgs > 2) {
00379         std::vector<std::string> EnvVars;
00380         for (unsigned i = 0; envp[i]; ++i)
00381           EnvVars.push_back(envp[i]);
00382         // Arg #2 = envp.
00383         GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
00384       }
00385     }
00386   }
00387   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
00388 }
00389 
00390 /// If possible, create a JIT, unless the caller specifically requests an
00391 /// Interpreter or there's an error. If even an Interpreter cannot be created,
00392 /// NULL is returned.
00393 ///
00394 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
00395                                          bool ForceInterpreter,
00396                                          std::string *ErrorStr,
00397                                          CodeGenOpt::Level OptLevel,
00398                                          bool GVsWithCode) {
00399   return EngineBuilder(MP)
00400       .setEngineKind(ForceInterpreter
00401                      ? EngineKind::Interpreter
00402                      : EngineKind::JIT)
00403       .setErrorStr(ErrorStr)
00404       .setOptLevel(OptLevel)
00405       .setAllocateGVsWithCode(GVsWithCode)
00406       .create();
00407 }
00408 
00409 ExecutionEngine *ExecutionEngine::create(Module *M) {
00410   return EngineBuilder(M).create();
00411 }
00412 
00413 /// EngineBuilder - Overloaded constructor that automatically creates an
00414 /// ExistingModuleProvider for an existing module.
00415 EngineBuilder::EngineBuilder(Module *m) : MP(new ExistingModuleProvider(m)) {
00416   InitEngine();
00417 }
00418 
00419 ExecutionEngine *EngineBuilder::create() {
00420   // Make sure we can resolve symbols in the program as well. The zero arg
00421   // to the function tells DynamicLibrary to load the program, not a library.
00422   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
00423     return 0;
00424 
00425   // If the user specified a memory manager but didn't specify which engine to
00426   // create, we assume they only want the JIT, and we fail if they only want
00427   // the interpreter.
00428   if (JMM) {
00429     if (WhichEngine & EngineKind::JIT) {
00430       WhichEngine = EngineKind::JIT;
00431     } else {
00432       *ErrorStr = "Cannot create an interpreter with a memory manager.";
00433     }
00434   }
00435 
00436   ExecutionEngine *EE = 0;
00437 
00438   // Unless the interpreter was explicitly selected or the JIT is not linked,
00439   // try making a JIT.
00440   if (WhichEngine & EngineKind::JIT && ExecutionEngine::JITCtor) {
00441     EE = ExecutionEngine::JITCtor(MP, ErrorStr, JMM, OptLevel,
00442                                   AllocateGVsWithCode);
00443   }
00444 
00445   // If we can't make a JIT and we didn't request one specifically, try making
00446   // an interpreter instead.
00447   if (WhichEngine & EngineKind::Interpreter && EE == 0 &&
00448       ExecutionEngine::InterpCtor) {
00449     EE = ExecutionEngine::InterpCtor(MP, ErrorStr);
00450   }
00451 
00452   return EE;
00453 }
00454 
00455 /// getPointerToGlobal - This returns the address of the specified global
00456 /// value.  This may involve code generation if it's a function.
00457 ///
00458 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
00459   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
00460     return getPointerToFunction(F);
00461 
00462   MutexGuard locked(lock);
00463   void *p = state.getGlobalAddressMap(locked)[GV];
00464   if (p)
00465     return p;
00466 
00467   // Global variable might have been added since interpreter started.
00468   if (GlobalVariable *GVar =
00469           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
00470     EmitGlobalVariable(GVar);
00471   else
00472     llvm_unreachable("Global hasn't had an address allocated yet!");
00473   return state.getGlobalAddressMap(locked)[GV];
00474 }
00475 
00476 /// This function converts a Constant* into a GenericValue. The interesting 
00477 /// part is if C is a ConstantExpr.
00478 /// @brief Get a GenericValue for a Constant*
00479 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
00480   // If its undefined, return the garbage.
00481   if (isa<UndefValue>(C)) 
00482     return GenericValue();
00483 
00484   // If the value is a ConstantExpr
00485   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00486     Constant *Op0 = CE->getOperand(0);
00487     switch (CE->getOpcode()) {
00488     case Instruction::GetElementPtr: {
00489       // Compute the index 
00490       GenericValue Result = getConstantValue(Op0);
00491       SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
00492       uint64_t Offset =
00493         TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
00494 
00495       char* tmp = (char*) Result.PointerVal;
00496       Result = PTOGV(tmp + Offset);
00497       return Result;
00498     }
00499     case Instruction::Trunc: {
00500       GenericValue GV = getConstantValue(Op0);
00501       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00502       GV.IntVal = GV.IntVal.trunc(BitWidth);
00503       return GV;
00504     }
00505     case Instruction::ZExt: {
00506       GenericValue GV = getConstantValue(Op0);
00507       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00508       GV.IntVal = GV.IntVal.zext(BitWidth);
00509       return GV;
00510     }
00511     case Instruction::SExt: {
00512       GenericValue GV = getConstantValue(Op0);
00513       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00514       GV.IntVal = GV.IntVal.sext(BitWidth);
00515       return GV;
00516     }
00517     case Instruction::FPTrunc: {
00518       // FIXME long double
00519       GenericValue GV = getConstantValue(Op0);
00520       GV.FloatVal = float(GV.DoubleVal);
00521       return GV;
00522     }
00523     case Instruction::FPExt:{
00524       // FIXME long double
00525       GenericValue GV = getConstantValue(Op0);
00526       GV.DoubleVal = double(GV.FloatVal);
00527       return GV;
00528     }
00529     case Instruction::UIToFP: {
00530       GenericValue GV = getConstantValue(Op0);
00531       if (CE->getType() == Type::getFloatTy(CE->getContext()))
00532         GV.FloatVal = float(GV.IntVal.roundToDouble());
00533       else if (CE->getType() == Type::getDoubleTy(CE->getContext()))
00534         GV.DoubleVal = GV.IntVal.roundToDouble();
00535       else if (CE->getType() == Type::getX86_FP80Ty(Op0->getContext())) {
00536         const uint64_t zero[] = {0, 0};
00537         APFloat apf = APFloat(APInt(80, 2, zero));
00538         (void)apf.convertFromAPInt(GV.IntVal, 
00539                                    false,
00540                                    APFloat::rmNearestTiesToEven);
00541         GV.IntVal = apf.bitcastToAPInt();
00542       }
00543       return GV;
00544     }
00545     case Instruction::SIToFP: {
00546       GenericValue GV = getConstantValue(Op0);
00547       if (CE->getType() == Type::getFloatTy(CE->getContext()))
00548         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
00549       else if (CE->getType() == Type::getDoubleTy(CE->getContext()))
00550         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
00551       else if (CE->getType() == Type::getX86_FP80Ty(CE->getContext())) {
00552         const uint64_t zero[] = { 0, 0};
00553         APFloat apf = APFloat(APInt(80, 2, zero));
00554         (void)apf.convertFromAPInt(GV.IntVal, 
00555                                    true,
00556                                    APFloat::rmNearestTiesToEven);
00557         GV.IntVal = apf.bitcastToAPInt();
00558       }
00559       return GV;
00560     }
00561     case Instruction::FPToUI: // double->APInt conversion handles sign
00562     case Instruction::FPToSI: {
00563       GenericValue GV = getConstantValue(Op0);
00564       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
00565       if (Op0->getType() == Type::getFloatTy(Op0->getContext()))
00566         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
00567       else if (Op0->getType() == Type::getDoubleTy(Op0->getContext()))
00568         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
00569       else if (Op0->getType() == Type::getX86_FP80Ty(Op0->getContext())) {
00570         APFloat apf = APFloat(GV.IntVal);
00571         uint64_t v;
00572         bool ignored;
00573         (void)apf.convertToInteger(&v, BitWidth,
00574                                    CE->getOpcode()==Instruction::FPToSI, 
00575                                    APFloat::rmTowardZero, &ignored);
00576         GV.IntVal = v; // endian?
00577       }
00578       return GV;
00579     }
00580     case Instruction::PtrToInt: {
00581       GenericValue GV = getConstantValue(Op0);
00582       uint32_t PtrWidth = TD->getPointerSizeInBits();
00583       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
00584       return GV;
00585     }
00586     case Instruction::IntToPtr: {
00587       GenericValue GV = getConstantValue(Op0);
00588       uint32_t PtrWidth = TD->getPointerSizeInBits();
00589       if (PtrWidth != GV.IntVal.getBitWidth())
00590         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
00591       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
00592       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
00593       return GV;
00594     }
00595     case Instruction::BitCast: {
00596       GenericValue GV = getConstantValue(Op0);
00597       const Type* DestTy = CE->getType();
00598       switch (Op0->getType()->getTypeID()) {
00599         default: llvm_unreachable("Invalid bitcast operand");
00600         case Type::IntegerTyID:
00601           assert(DestTy->isFloatingPoint() && "invalid bitcast");
00602           if (DestTy == Type::getFloatTy(Op0->getContext()))
00603             GV.FloatVal = GV.IntVal.bitsToFloat();
00604           else if (DestTy == Type::getDoubleTy(DestTy->getContext()))
00605             GV.DoubleVal = GV.IntVal.bitsToDouble();
00606           break;
00607         case Type::FloatTyID: 
00608           assert(DestTy == Type::getInt32Ty(DestTy->getContext()) &&
00609                  "Invalid bitcast");
00610           GV.IntVal.floatToBits(GV.FloatVal);
00611           break;
00612         case Type::DoubleTyID:
00613           assert(DestTy == Type::getInt64Ty(DestTy->getContext()) &&
00614                  "Invalid bitcast");
00615           GV.IntVal.doubleToBits(GV.DoubleVal);
00616           break;
00617         case Type::PointerTyID:
00618           assert(isa<PointerType>(DestTy) && "Invalid bitcast");
00619           break; // getConstantValue(Op0)  above already converted it
00620       }
00621       return GV;
00622     }
00623     case Instruction::Add:
00624     case Instruction::FAdd:
00625     case Instruction::Sub:
00626     case Instruction::FSub:
00627     case Instruction::Mul:
00628     case Instruction::FMul:
00629     case Instruction::UDiv:
00630     case Instruction::SDiv:
00631     case Instruction::URem:
00632     case Instruction::SRem:
00633     case Instruction::And:
00634     case Instruction::Or:
00635     case Instruction::Xor: {
00636       GenericValue LHS = getConstantValue(Op0);
00637       GenericValue RHS = getConstantValue(CE->getOperand(1));
00638       GenericValue GV;
00639       switch (CE->getOperand(0)->getType()->getTypeID()) {
00640       default: llvm_unreachable("Bad add type!");
00641       case Type::IntegerTyID:
00642         switch (CE->getOpcode()) {
00643           default: llvm_unreachable("Invalid integer opcode");
00644           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
00645           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
00646           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
00647           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
00648           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
00649           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
00650           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
00651           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
00652           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
00653           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
00654         }
00655         break;
00656       case Type::FloatTyID:
00657         switch (CE->getOpcode()) {
00658           default: llvm_unreachable("Invalid float opcode");
00659           case Instruction::FAdd:
00660             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
00661           case Instruction::FSub:
00662             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
00663           case Instruction::FMul:
00664             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
00665           case Instruction::FDiv: 
00666             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
00667           case Instruction::FRem: 
00668             GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
00669         }
00670         break;
00671       case Type::DoubleTyID:
00672         switch (CE->getOpcode()) {
00673           default: llvm_unreachable("Invalid double opcode");
00674           case Instruction::FAdd:
00675             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
00676           case Instruction::FSub:
00677             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
00678           case Instruction::FMul:
00679             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
00680           case Instruction::FDiv: 
00681             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
00682           case Instruction::FRem: 
00683             GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
00684         }
00685         break;
00686       case Type::X86_FP80TyID:
00687       case Type::PPC_FP128TyID:
00688       case Type::FP128TyID: {
00689         APFloat apfLHS = APFloat(LHS.IntVal);
00690         switch (CE->getOpcode()) {
00691           default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
00692           case Instruction::FAdd:
00693             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
00694             GV.IntVal = apfLHS.bitcastToAPInt();
00695             break;
00696           case Instruction::FSub:
00697             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
00698             GV.IntVal = apfLHS.bitcastToAPInt();
00699             break;
00700           case Instruction::FMul:
00701             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
00702             GV.IntVal = apfLHS.bitcastToAPInt();
00703             break;
00704           case Instruction::FDiv: 
00705             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
00706             GV.IntVal = apfLHS.bitcastToAPInt();
00707             break;
00708           case Instruction::FRem: 
00709             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
00710             GV.IntVal = apfLHS.bitcastToAPInt();
00711             break;
00712           }
00713         }
00714         break;
00715       }
00716       return GV;
00717     }
00718     default:
00719       break;
00720     }
00721     std::string msg;
00722     raw_string_ostream Msg(msg);
00723     Msg << "ConstantExpr not handled: " << *CE;
00724     llvm_report_error(Msg.str());
00725   }
00726 
00727   GenericValue Result;
00728   switch (C->getType()->getTypeID()) {
00729   case Type::FloatTyID: 
00730     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 
00731     break;
00732   case Type::DoubleTyID:
00733     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
00734     break;
00735   case Type::X86_FP80TyID:
00736   case Type::FP128TyID:
00737   case Type::PPC_FP128TyID:
00738     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
00739     break;
00740   case Type::IntegerTyID:
00741     Result.IntVal = cast<ConstantInt>(C)->getValue();
00742     break;
00743   case Type::PointerTyID:
00744     if (isa<ConstantPointerNull>(C))
00745       Result.PointerVal = 0;
00746     else if (const Function *F = dyn_cast<Function>(C))
00747       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
00748     else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
00749       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
00750     else
00751       llvm_unreachable("Unknown constant pointer type!");
00752     break;
00753   default:
00754     std::string msg;
00755     raw_string_ostream Msg(msg);
00756     Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
00757     llvm_report_error(Msg.str());
00758   }
00759   return Result;
00760 }
00761 
00762 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
00763 /// with the integer held in IntVal.
00764 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
00765                              unsigned StoreBytes) {
00766   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
00767   uint8_t *Src = (uint8_t *)IntVal.getRawData();
00768 
00769   if (sys::isLittleEndianHost())
00770     // Little-endian host - the source is ordered from LSB to MSB.  Order the
00771     // destination from LSB to MSB: Do a straight copy.
00772     memcpy(Dst, Src, StoreBytes);
00773   else {
00774     // Big-endian host - the source is an array of 64 bit words ordered from
00775     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
00776     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
00777     while (StoreBytes > sizeof(uint64_t)) {
00778       StoreBytes -= sizeof(uint64_t);
00779       // May not be aligned so use memcpy.
00780       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
00781       Src += sizeof(uint64_t);
00782     }
00783 
00784     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
00785   }
00786 }
00787 
00788 /// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr.  Ptr
00789 /// is the address of the memory at which to store Val, cast to GenericValue *.
00790 /// It is not a pointer to a GenericValue containing the address at which to
00791 /// store Val.
00792 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
00793                                          GenericValue *Ptr, const Type *Ty) {
00794   const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
00795 
00796   switch (Ty->getTypeID()) {
00797   case Type::IntegerTyID:
00798     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
00799     break;
00800   case Type::FloatTyID:
00801     *((float*)Ptr) = Val.FloatVal;
00802     break;
00803   case Type::DoubleTyID:
00804     *((double*)Ptr) = Val.DoubleVal;
00805     break;
00806   case Type::X86_FP80TyID:
00807     memcpy(Ptr, Val.IntVal.getRawData(), 10);
00808     break;
00809   case Type::PointerTyID:
00810     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
00811     if (StoreBytes != sizeof(PointerTy))
00812       memset(Ptr, 0, StoreBytes);
00813 
00814     *((PointerTy*)Ptr) = Val.PointerVal;
00815     break;
00816   default:
00817     cerr << "Cannot store value of type " << *Ty << "!\n";
00818   }
00819 
00820   if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
00821     // Host and target are different endian - reverse the stored bytes.
00822     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
00823 }
00824 
00825 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
00826 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
00827 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
00828   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
00829   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
00830 
00831   if (sys::isLittleEndianHost())
00832     // Little-endian host - the destination must be ordered from LSB to MSB.
00833     // The source is ordered from LSB to MSB: Do a straight copy.
00834     memcpy(Dst, Src, LoadBytes);
00835   else {
00836     // Big-endian - the destination is an array of 64 bit words ordered from
00837     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
00838     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
00839     // a word.
00840     while (LoadBytes > sizeof(uint64_t)) {
00841       LoadBytes -= sizeof(uint64_t);
00842       // May not be aligned so use memcpy.
00843       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
00844       Dst += sizeof(uint64_t);
00845     }
00846 
00847     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
00848   }
00849 }
00850 
00851 /// FIXME: document
00852 ///
00853 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
00854                                           GenericValue *Ptr,
00855                                           const Type *Ty) {
00856   const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
00857 
00858   if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian()) {
00859     // Host and target are different endian - reverse copy the stored
00860     // bytes into a buffer, and load from that.
00861     uint8_t *Src = (uint8_t*)Ptr;
00862     uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
00863     std::reverse_copy(Src, Src + LoadBytes, Buf);
00864     Ptr = (GenericValue*)Buf;
00865   }
00866 
00867   switch (Ty->getTypeID()) {
00868   case Type::IntegerTyID:
00869     // An APInt with all words initially zero.
00870     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
00871     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
00872     break;
00873   case Type::FloatTyID:
00874     Result.FloatVal = *((float*)Ptr);
00875     break;
00876   case Type::DoubleTyID:
00877     Result.DoubleVal = *((double*)Ptr);
00878     break;
00879   case Type::PointerTyID:
00880     Result.PointerVal = *((PointerTy*)Ptr);
00881     break;
00882   case Type::X86_FP80TyID: {
00883     // This is endian dependent, but it will only work on x86 anyway.
00884     // FIXME: Will not trap if loading a signaling NaN.
00885     uint64_t y[2];
00886     memcpy(y, Ptr, 10);
00887     Result.IntVal = APInt(80, 2, y);
00888     break;
00889   }
00890   default:
00891     std::string msg;
00892     raw_string_ostream Msg(msg);
00893     Msg << "Cannot load value of type " << *Ty << "!";
00894     llvm_report_error(Msg.str());
00895   }
00896 }
00897 
00898 // InitializeMemory - Recursive function to apply a Constant value into the
00899 // specified memory location...
00900 //
00901 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
00902   DOUT << "JIT: Initializing " << Addr << " ";
00903   DEBUG(Init->dump());
00904   if (isa<UndefValue>(Init)) {
00905     return;
00906   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
00907     unsigned ElementSize =
00908       getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
00909     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
00910       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
00911     return;
00912   } else if (isa<ConstantAggregateZero>(Init)) {
00913     memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
00914     return;
00915   } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
00916     unsigned ElementSize =
00917       getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
00918     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
00919       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
00920     return;
00921   } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
00922     const StructLayout *SL =
00923       getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
00924     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
00925       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
00926     return;
00927   } else if (Init->getType()->isFirstClassType()) {
00928     GenericValue Val = getConstantValue(Init);
00929     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
00930     return;
00931   }
00932 
00933   cerr << "Bad Type: " << *Init->getType() << "\n";
00934   llvm_unreachable("Unknown constant type to initialize memory with!");
00935 }
00936 
00937 /// EmitGlobals - Emit all of the global variables to memory, storing their
00938 /// addresses into GlobalAddress.  This must make sure to copy the contents of
00939 /// their initializers into the memory.
00940 ///
00941 void ExecutionEngine::emitGlobals() {
00942 
00943   // Loop over all of the global variables in the program, allocating the memory
00944   // to hold them.  If there is more than one module, do a prepass over globals
00945   // to figure out how the different modules should link together.
00946   //
00947   std::map<std::pair<std::string, const Type*>,
00948            const GlobalValue*> LinkedGlobalsMap;
00949 
00950   if (Modules.size() != 1) {
00951     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
00952       Module &M = *Modules[m]->getModule();
00953       for (Module::const_global_iterator I = M.global_begin(),
00954            E = M.global_end(); I != E; ++I) {
00955         const GlobalValue *GV = I;
00956         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
00957             GV->hasAppendingLinkage() || !GV->hasName())
00958           continue;// Ignore external globals and globals with internal linkage.
00959           
00960         const GlobalValue *&GVEntry = 
00961           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
00962 
00963         // If this is the first time we've seen this global, it is the canonical
00964         // version.
00965         if (!GVEntry) {
00966           GVEntry = GV;
00967           continue;
00968         }
00969         
00970         // If the existing global is strong, never replace it.
00971         if (GVEntry->hasExternalLinkage() ||
00972             GVEntry->hasDLLImportLinkage() ||
00973             GVEntry->hasDLLExportLinkage())
00974           continue;
00975         
00976         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
00977         // symbol.  FIXME is this right for common?
00978         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
00979           GVEntry = GV;
00980       }
00981     }
00982   }
00983   
00984   std::vector<const GlobalValue*> NonCanonicalGlobals;
00985   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
00986     Module &M = *Modules[m]->getModule();
00987     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00988          I != E; ++I) {
00989       // In the multi-module case, see what this global maps to.
00990       if (!LinkedGlobalsMap.empty()) {
00991         if (const GlobalValue *GVEntry = 
00992               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
00993           // If something else is the canonical global, ignore this one.
00994           if (GVEntry != &*I) {
00995             NonCanonicalGlobals.push_back(I);
00996             continue;
00997           }
00998         }
00999       }
01000       
01001       if (!I->isDeclaration()) {
01002         addGlobalMapping(I, getMemoryForGV(I));
01003       } else {
01004         // External variable reference. Try to use the dynamic loader to
01005         // get a pointer to it.
01006         if (void *SymAddr =
01007             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
01008           addGlobalMapping(I, SymAddr);
01009         else {
01010           llvm_report_error("Could not resolve external global address: "
01011                             +I->getName());
01012         }
01013       }
01014     }
01015     
01016     // If there are multiple modules, map the non-canonical globals to their
01017     // canonical location.
01018     if (!NonCanonicalGlobals.empty()) {
01019       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
01020         const GlobalValue *GV = NonCanonicalGlobals[i];
01021         const GlobalValue *CGV =
01022           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
01023         void *Ptr = getPointerToGlobalIfAvailable(CGV);
01024         assert(Ptr && "Canonical global wasn't codegen'd!");
01025         addGlobalMapping(GV, Ptr);
01026       }
01027     }
01028     
01029     // Now that all of the globals are set up in memory, loop through them all 
01030     // and initialize their contents.
01031     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
01032          I != E; ++I) {
01033       if (!I->isDeclaration()) {
01034         if (!LinkedGlobalsMap.empty()) {
01035           if (const GlobalValue *GVEntry = 
01036                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
01037             if (GVEntry != &*I)  // Not the canonical variable.
01038               continue;
01039         }
01040         EmitGlobalVariable(I);
01041       }
01042     }
01043   }
01044 }
01045 
01046 // EmitGlobalVariable - This method emits the specified global variable to the
01047 // address specified in GlobalAddresses, or allocates new memory if it's not
01048 // already in the map.
01049 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
01050   void *GA = getPointerToGlobalIfAvailable(GV);
01051 
01052   if (GA == 0) {
01053     // If it's not already specified, allocate memory for the global.
01054     GA = getMemoryForGV(GV);
01055     addGlobalMapping(GV, GA);
01056   }
01057   
01058   // Don't initialize if it's thread local, let the client do it.
01059   if (!GV->isThreadLocal())
01060     InitializeMemory(GV->getInitializer(), GA);
01061   
01062   const Type *ElTy = GV->getType()->getElementType();
01063   size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
01064   NumInitBytes += (unsigned)GVSize;
01065   ++NumGlobals;
01066 }