LLVM API Documentation

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