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