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