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