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