109467b48Spatrick //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file defines the common interface used by the various execution engine
1009467b48Spatrick // subclasses.
1109467b48Spatrick //
12097a140dSpatrick // FIXME: This file needs to be updated to support scalable vectors
13097a140dSpatrick //
1409467b48Spatrick //===----------------------------------------------------------------------===//
1509467b48Spatrick 
1609467b48Spatrick #include "llvm/ExecutionEngine/ExecutionEngine.h"
1709467b48Spatrick #include "llvm/ADT/STLExtras.h"
1809467b48Spatrick #include "llvm/ADT/SmallString.h"
1909467b48Spatrick #include "llvm/ADT/Statistic.h"
2009467b48Spatrick #include "llvm/ExecutionEngine/GenericValue.h"
2109467b48Spatrick #include "llvm/ExecutionEngine/JITEventListener.h"
2209467b48Spatrick #include "llvm/ExecutionEngine/ObjectCache.h"
2309467b48Spatrick #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
2409467b48Spatrick #include "llvm/IR/Constants.h"
2509467b48Spatrick #include "llvm/IR/DataLayout.h"
2609467b48Spatrick #include "llvm/IR/DerivedTypes.h"
2709467b48Spatrick #include "llvm/IR/Mangler.h"
2809467b48Spatrick #include "llvm/IR/Module.h"
2909467b48Spatrick #include "llvm/IR/Operator.h"
3009467b48Spatrick #include "llvm/IR/ValueHandle.h"
31*d415bd75Srobert #include "llvm/MC/TargetRegistry.h"
3209467b48Spatrick #include "llvm/Object/Archive.h"
3309467b48Spatrick #include "llvm/Object/ObjectFile.h"
3409467b48Spatrick #include "llvm/Support/Debug.h"
3509467b48Spatrick #include "llvm/Support/DynamicLibrary.h"
3609467b48Spatrick #include "llvm/Support/ErrorHandling.h"
3709467b48Spatrick #include "llvm/Support/Host.h"
3809467b48Spatrick #include "llvm/Support/raw_ostream.h"
3909467b48Spatrick #include "llvm/Target/TargetMachine.h"
4009467b48Spatrick #include <cmath>
4109467b48Spatrick #include <cstring>
4209467b48Spatrick #include <mutex>
4309467b48Spatrick using namespace llvm;
4409467b48Spatrick 
4509467b48Spatrick #define DEBUG_TYPE "jit"
4609467b48Spatrick 
4709467b48Spatrick STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
4809467b48Spatrick STATISTIC(NumGlobals  , "Number of global vars initialized");
4909467b48Spatrick 
5009467b48Spatrick ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
5109467b48Spatrick     std::unique_ptr<Module> M, std::string *ErrorStr,
5209467b48Spatrick     std::shared_ptr<MCJITMemoryManager> MemMgr,
5309467b48Spatrick     std::shared_ptr<LegacyJITSymbolResolver> Resolver,
5409467b48Spatrick     std::unique_ptr<TargetMachine> TM) = nullptr;
5509467b48Spatrick 
5609467b48Spatrick ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
5709467b48Spatrick                                                 std::string *ErrorStr) =nullptr;
5809467b48Spatrick 
anchor()5909467b48Spatrick void JITEventListener::anchor() {}
6009467b48Spatrick 
anchor()6109467b48Spatrick void ObjectCache::anchor() {}
6209467b48Spatrick 
Init(std::unique_ptr<Module> M)6309467b48Spatrick void ExecutionEngine::Init(std::unique_ptr<Module> M) {
6409467b48Spatrick   CompilingLazily         = false;
6509467b48Spatrick   GVCompilationDisabled   = false;
6609467b48Spatrick   SymbolSearchingDisabled = false;
6709467b48Spatrick 
6809467b48Spatrick   // IR module verification is enabled by default in debug builds, and disabled
6909467b48Spatrick   // by default in release builds.
7009467b48Spatrick #ifndef NDEBUG
7109467b48Spatrick   VerifyModules = true;
7209467b48Spatrick #else
7309467b48Spatrick   VerifyModules = false;
7409467b48Spatrick #endif
7509467b48Spatrick 
7609467b48Spatrick   assert(M && "Module is null?");
7709467b48Spatrick   Modules.push_back(std::move(M));
7809467b48Spatrick }
7909467b48Spatrick 
ExecutionEngine(std::unique_ptr<Module> M)8009467b48Spatrick ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
8109467b48Spatrick     : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
8209467b48Spatrick   Init(std::move(M));
8309467b48Spatrick }
8409467b48Spatrick 
ExecutionEngine(DataLayout DL,std::unique_ptr<Module> M)8509467b48Spatrick ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
8609467b48Spatrick     : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
8709467b48Spatrick   Init(std::move(M));
8809467b48Spatrick }
8909467b48Spatrick 
~ExecutionEngine()9009467b48Spatrick ExecutionEngine::~ExecutionEngine() {
9109467b48Spatrick   clearAllGlobalMappings();
9209467b48Spatrick }
9309467b48Spatrick 
9409467b48Spatrick namespace {
9509467b48Spatrick /// Helper class which uses a value handler to automatically deletes the
9609467b48Spatrick /// memory block when the GlobalVariable is destroyed.
9709467b48Spatrick class GVMemoryBlock final : public CallbackVH {
GVMemoryBlock(const GlobalVariable * GV)9809467b48Spatrick   GVMemoryBlock(const GlobalVariable *GV)
9909467b48Spatrick     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
10009467b48Spatrick 
10109467b48Spatrick public:
10209467b48Spatrick   /// Returns the address the GlobalVariable should be written into.  The
10309467b48Spatrick   /// GVMemoryBlock object prefixes that.
Create(const GlobalVariable * GV,const DataLayout & TD)10409467b48Spatrick   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
10509467b48Spatrick     Type *ElTy = GV->getValueType();
10609467b48Spatrick     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
10709467b48Spatrick     void *RawMemory = ::operator new(
108097a140dSpatrick         alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlign(GV)) + GVSize);
10909467b48Spatrick     new(RawMemory) GVMemoryBlock(GV);
11009467b48Spatrick     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
11109467b48Spatrick   }
11209467b48Spatrick 
deleted()11309467b48Spatrick   void deleted() override {
11409467b48Spatrick     // We allocated with operator new and with some extra memory hanging off the
11509467b48Spatrick     // end, so don't just delete this.  I'm not sure if this is actually
11609467b48Spatrick     // required.
11709467b48Spatrick     this->~GVMemoryBlock();
11809467b48Spatrick     ::operator delete(this);
11909467b48Spatrick   }
12009467b48Spatrick };
12109467b48Spatrick }  // anonymous namespace
12209467b48Spatrick 
getMemoryForGV(const GlobalVariable * GV)12309467b48Spatrick char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
12409467b48Spatrick   return GVMemoryBlock::Create(GV, getDataLayout());
12509467b48Spatrick }
12609467b48Spatrick 
addObjectFile(std::unique_ptr<object::ObjectFile> O)12709467b48Spatrick void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
12809467b48Spatrick   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
12909467b48Spatrick }
13009467b48Spatrick 
13109467b48Spatrick void
addObjectFile(object::OwningBinary<object::ObjectFile> O)13209467b48Spatrick ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
13309467b48Spatrick   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
13409467b48Spatrick }
13509467b48Spatrick 
addArchive(object::OwningBinary<object::Archive> A)13609467b48Spatrick void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
13709467b48Spatrick   llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
13809467b48Spatrick }
13909467b48Spatrick 
removeModule(Module * M)14009467b48Spatrick bool ExecutionEngine::removeModule(Module *M) {
14109467b48Spatrick   for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
14209467b48Spatrick     Module *Found = I->get();
14309467b48Spatrick     if (Found == M) {
14409467b48Spatrick       I->release();
14509467b48Spatrick       Modules.erase(I);
14609467b48Spatrick       clearGlobalMappingsFromModule(M);
14709467b48Spatrick       return true;
14809467b48Spatrick     }
14909467b48Spatrick   }
15009467b48Spatrick   return false;
15109467b48Spatrick }
15209467b48Spatrick 
FindFunctionNamed(StringRef FnName)15309467b48Spatrick Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
15409467b48Spatrick   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
15509467b48Spatrick     Function *F = Modules[i]->getFunction(FnName);
15609467b48Spatrick     if (F && !F->isDeclaration())
15709467b48Spatrick       return F;
15809467b48Spatrick   }
15909467b48Spatrick   return nullptr;
16009467b48Spatrick }
16109467b48Spatrick 
FindGlobalVariableNamed(StringRef Name,bool AllowInternal)16209467b48Spatrick GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
16309467b48Spatrick   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
16409467b48Spatrick     GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
16509467b48Spatrick     if (GV && !GV->isDeclaration())
16609467b48Spatrick       return GV;
16709467b48Spatrick   }
16809467b48Spatrick   return nullptr;
16909467b48Spatrick }
17009467b48Spatrick 
RemoveMapping(StringRef Name)17109467b48Spatrick uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
17209467b48Spatrick   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
17309467b48Spatrick   uint64_t OldVal;
17409467b48Spatrick 
17509467b48Spatrick   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
17609467b48Spatrick   // GlobalAddressMap.
17709467b48Spatrick   if (I == GlobalAddressMap.end())
17809467b48Spatrick     OldVal = 0;
17909467b48Spatrick   else {
18009467b48Spatrick     GlobalAddressReverseMap.erase(I->second);
18109467b48Spatrick     OldVal = I->second;
18209467b48Spatrick     GlobalAddressMap.erase(I);
18309467b48Spatrick   }
18409467b48Spatrick 
18509467b48Spatrick   return OldVal;
18609467b48Spatrick }
18709467b48Spatrick 
getMangledName(const GlobalValue * GV)18809467b48Spatrick std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
18909467b48Spatrick   assert(GV->hasName() && "Global must have name.");
19009467b48Spatrick 
19109467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
19209467b48Spatrick   SmallString<128> FullName;
19309467b48Spatrick 
19409467b48Spatrick   const DataLayout &DL =
19509467b48Spatrick     GV->getParent()->getDataLayout().isDefault()
19609467b48Spatrick       ? getDataLayout()
19709467b48Spatrick       : GV->getParent()->getDataLayout();
19809467b48Spatrick 
19909467b48Spatrick   Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
200097a140dSpatrick   return std::string(FullName.str());
20109467b48Spatrick }
20209467b48Spatrick 
addGlobalMapping(const GlobalValue * GV,void * Addr)20309467b48Spatrick void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
20409467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
20509467b48Spatrick   addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
20609467b48Spatrick }
20709467b48Spatrick 
addGlobalMapping(StringRef Name,uint64_t Addr)20809467b48Spatrick void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
20909467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
21009467b48Spatrick 
21109467b48Spatrick   assert(!Name.empty() && "Empty GlobalMapping symbol name!");
21209467b48Spatrick 
21309467b48Spatrick   LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
21409467b48Spatrick   uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
21509467b48Spatrick   assert((!CurVal || !Addr) && "GlobalMapping already established!");
21609467b48Spatrick   CurVal = Addr;
21709467b48Spatrick 
21809467b48Spatrick   // If we are using the reverse mapping, add it too.
21909467b48Spatrick   if (!EEState.getGlobalAddressReverseMap().empty()) {
22009467b48Spatrick     std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
22109467b48Spatrick     assert((!V.empty() || !Name.empty()) &&
22209467b48Spatrick            "GlobalMapping already established!");
223097a140dSpatrick     V = std::string(Name);
22409467b48Spatrick   }
22509467b48Spatrick }
22609467b48Spatrick 
clearAllGlobalMappings()22709467b48Spatrick void ExecutionEngine::clearAllGlobalMappings() {
22809467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
22909467b48Spatrick 
23009467b48Spatrick   EEState.getGlobalAddressMap().clear();
23109467b48Spatrick   EEState.getGlobalAddressReverseMap().clear();
23209467b48Spatrick }
23309467b48Spatrick 
clearGlobalMappingsFromModule(Module * M)23409467b48Spatrick void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
23509467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
23609467b48Spatrick 
23709467b48Spatrick   for (GlobalObject &GO : M->global_objects())
23809467b48Spatrick     EEState.RemoveMapping(getMangledName(&GO));
23909467b48Spatrick }
24009467b48Spatrick 
updateGlobalMapping(const GlobalValue * GV,void * Addr)24109467b48Spatrick uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
24209467b48Spatrick                                               void *Addr) {
24309467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
24409467b48Spatrick   return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
24509467b48Spatrick }
24609467b48Spatrick 
updateGlobalMapping(StringRef Name,uint64_t Addr)24709467b48Spatrick uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
24809467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
24909467b48Spatrick 
25009467b48Spatrick   ExecutionEngineState::GlobalAddressMapTy &Map =
25109467b48Spatrick     EEState.getGlobalAddressMap();
25209467b48Spatrick 
25309467b48Spatrick   // Deleting from the mapping?
25409467b48Spatrick   if (!Addr)
25509467b48Spatrick     return EEState.RemoveMapping(Name);
25609467b48Spatrick 
25709467b48Spatrick   uint64_t &CurVal = Map[Name];
25809467b48Spatrick   uint64_t OldVal = CurVal;
25909467b48Spatrick 
26009467b48Spatrick   if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
26109467b48Spatrick     EEState.getGlobalAddressReverseMap().erase(CurVal);
26209467b48Spatrick   CurVal = Addr;
26309467b48Spatrick 
26409467b48Spatrick   // If we are using the reverse mapping, add it too.
26509467b48Spatrick   if (!EEState.getGlobalAddressReverseMap().empty()) {
26609467b48Spatrick     std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
26709467b48Spatrick     assert((!V.empty() || !Name.empty()) &&
26809467b48Spatrick            "GlobalMapping already established!");
269097a140dSpatrick     V = std::string(Name);
27009467b48Spatrick   }
27109467b48Spatrick   return OldVal;
27209467b48Spatrick }
27309467b48Spatrick 
getAddressToGlobalIfAvailable(StringRef S)27409467b48Spatrick uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
27509467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
27609467b48Spatrick   uint64_t Address = 0;
27709467b48Spatrick   ExecutionEngineState::GlobalAddressMapTy::iterator I =
27809467b48Spatrick     EEState.getGlobalAddressMap().find(S);
27909467b48Spatrick   if (I != EEState.getGlobalAddressMap().end())
28009467b48Spatrick     Address = I->second;
28109467b48Spatrick   return Address;
28209467b48Spatrick }
28309467b48Spatrick 
28409467b48Spatrick 
getPointerToGlobalIfAvailable(StringRef S)28509467b48Spatrick void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
28609467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
28709467b48Spatrick   if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
28809467b48Spatrick     return Address;
28909467b48Spatrick   return nullptr;
29009467b48Spatrick }
29109467b48Spatrick 
getPointerToGlobalIfAvailable(const GlobalValue * GV)29209467b48Spatrick void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
29309467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
29409467b48Spatrick   return getPointerToGlobalIfAvailable(getMangledName(GV));
29509467b48Spatrick }
29609467b48Spatrick 
getGlobalValueAtAddress(void * Addr)29709467b48Spatrick const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
29809467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
29909467b48Spatrick 
30009467b48Spatrick   // If we haven't computed the reverse mapping yet, do so first.
30109467b48Spatrick   if (EEState.getGlobalAddressReverseMap().empty()) {
30209467b48Spatrick     for (ExecutionEngineState::GlobalAddressMapTy::iterator
30309467b48Spatrick            I = EEState.getGlobalAddressMap().begin(),
30409467b48Spatrick            E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
30509467b48Spatrick       StringRef Name = I->first();
30609467b48Spatrick       uint64_t Addr = I->second;
307097a140dSpatrick       EEState.getGlobalAddressReverseMap().insert(
308097a140dSpatrick           std::make_pair(Addr, std::string(Name)));
30909467b48Spatrick     }
31009467b48Spatrick   }
31109467b48Spatrick 
31209467b48Spatrick   std::map<uint64_t, std::string>::iterator I =
31309467b48Spatrick     EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
31409467b48Spatrick 
31509467b48Spatrick   if (I != EEState.getGlobalAddressReverseMap().end()) {
31609467b48Spatrick     StringRef Name = I->second;
31709467b48Spatrick     for (unsigned i = 0, e = Modules.size(); i != e; ++i)
31809467b48Spatrick       if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
31909467b48Spatrick         return GV;
32009467b48Spatrick   }
32109467b48Spatrick   return nullptr;
32209467b48Spatrick }
32309467b48Spatrick 
32409467b48Spatrick namespace {
32509467b48Spatrick class ArgvArray {
32609467b48Spatrick   std::unique_ptr<char[]> Array;
32709467b48Spatrick   std::vector<std::unique_ptr<char[]>> Values;
32809467b48Spatrick public:
32909467b48Spatrick   /// Turn a vector of strings into a nice argv style array of pointers to null
33009467b48Spatrick   /// terminated strings.
33109467b48Spatrick   void *reset(LLVMContext &C, ExecutionEngine *EE,
33209467b48Spatrick               const std::vector<std::string> &InputArgv);
33309467b48Spatrick };
33409467b48Spatrick }  // anonymous namespace
reset(LLVMContext & C,ExecutionEngine * EE,const std::vector<std::string> & InputArgv)33509467b48Spatrick void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
33609467b48Spatrick                        const std::vector<std::string> &InputArgv) {
33709467b48Spatrick   Values.clear();  // Free the old contents.
33809467b48Spatrick   Values.reserve(InputArgv.size());
33909467b48Spatrick   unsigned PtrSize = EE->getDataLayout().getPointerSize();
34009467b48Spatrick   Array = std::make_unique<char[]>((InputArgv.size()+1)*PtrSize);
34109467b48Spatrick 
34209467b48Spatrick   LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array.get() << "\n");
34309467b48Spatrick   Type *SBytePtr = Type::getInt8PtrTy(C);
34409467b48Spatrick 
34509467b48Spatrick   for (unsigned i = 0; i != InputArgv.size(); ++i) {
34609467b48Spatrick     unsigned Size = InputArgv[i].size()+1;
34709467b48Spatrick     auto Dest = std::make_unique<char[]>(Size);
34809467b48Spatrick     LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void *)Dest.get()
34909467b48Spatrick                       << "\n");
35009467b48Spatrick 
35109467b48Spatrick     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
35209467b48Spatrick     Dest[Size-1] = 0;
35309467b48Spatrick 
35409467b48Spatrick     // Endian safe: Array[i] = (PointerTy)Dest;
35509467b48Spatrick     EE->StoreValueToMemory(PTOGV(Dest.get()),
35609467b48Spatrick                            (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
35709467b48Spatrick     Values.push_back(std::move(Dest));
35809467b48Spatrick   }
35909467b48Spatrick 
36009467b48Spatrick   // Null terminate it
36109467b48Spatrick   EE->StoreValueToMemory(PTOGV(nullptr),
36209467b48Spatrick                          (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
36309467b48Spatrick                          SBytePtr);
36409467b48Spatrick   return Array.get();
36509467b48Spatrick }
36609467b48Spatrick 
runStaticConstructorsDestructors(Module & module,bool isDtors)36709467b48Spatrick void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
36809467b48Spatrick                                                        bool isDtors) {
36909467b48Spatrick   StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");
37009467b48Spatrick   GlobalVariable *GV = module.getNamedGlobal(Name);
37109467b48Spatrick 
37209467b48Spatrick   // If this global has internal linkage, or if it has a use, then it must be
37309467b48Spatrick   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
37409467b48Spatrick   // this is the case, don't execute any of the global ctors, __main will do
37509467b48Spatrick   // it.
37609467b48Spatrick   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
37709467b48Spatrick 
37809467b48Spatrick   // Should be an array of '{ i32, void ()* }' structs.  The first value is
37909467b48Spatrick   // the init priority, which we ignore.
38009467b48Spatrick   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
38109467b48Spatrick   if (!InitList)
38209467b48Spatrick     return;
38309467b48Spatrick   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
38409467b48Spatrick     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
38509467b48Spatrick     if (!CS) continue;
38609467b48Spatrick 
38709467b48Spatrick     Constant *FP = CS->getOperand(1);
38809467b48Spatrick     if (FP->isNullValue())
38909467b48Spatrick       continue;  // Found a sentinal value, ignore.
39009467b48Spatrick 
39109467b48Spatrick     // Strip off constant expression casts.
39209467b48Spatrick     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
39309467b48Spatrick       if (CE->isCast())
39409467b48Spatrick         FP = CE->getOperand(0);
39509467b48Spatrick 
39609467b48Spatrick     // Execute the ctor/dtor function!
39709467b48Spatrick     if (Function *F = dyn_cast<Function>(FP))
398*d415bd75Srobert       runFunction(F, std::nullopt);
39909467b48Spatrick 
40009467b48Spatrick     // FIXME: It is marginally lame that we just do nothing here if we see an
40109467b48Spatrick     // entry we don't recognize. It might not be unreasonable for the verifier
40209467b48Spatrick     // to not even allow this and just assert here.
40309467b48Spatrick   }
40409467b48Spatrick }
40509467b48Spatrick 
runStaticConstructorsDestructors(bool isDtors)40609467b48Spatrick void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
40709467b48Spatrick   // Execute global ctors/dtors for each module in the program.
40809467b48Spatrick   for (std::unique_ptr<Module> &M : Modules)
40909467b48Spatrick     runStaticConstructorsDestructors(*M, isDtors);
41009467b48Spatrick }
41109467b48Spatrick 
41209467b48Spatrick #ifndef NDEBUG
41309467b48Spatrick /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
isTargetNullPtr(ExecutionEngine * EE,void * Loc)41409467b48Spatrick static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
41509467b48Spatrick   unsigned PtrSize = EE->getDataLayout().getPointerSize();
41609467b48Spatrick   for (unsigned i = 0; i < PtrSize; ++i)
41709467b48Spatrick     if (*(i + (uint8_t*)Loc))
41809467b48Spatrick       return false;
41909467b48Spatrick   return true;
42009467b48Spatrick }
42109467b48Spatrick #endif
42209467b48Spatrick 
runFunctionAsMain(Function * Fn,const std::vector<std::string> & argv,const char * const * envp)42309467b48Spatrick int ExecutionEngine::runFunctionAsMain(Function *Fn,
42409467b48Spatrick                                        const std::vector<std::string> &argv,
42509467b48Spatrick                                        const char * const * envp) {
42609467b48Spatrick   std::vector<GenericValue> GVArgs;
42709467b48Spatrick   GenericValue GVArgc;
42809467b48Spatrick   GVArgc.IntVal = APInt(32, argv.size());
42909467b48Spatrick 
43009467b48Spatrick   // Check main() type
43109467b48Spatrick   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
43209467b48Spatrick   FunctionType *FTy = Fn->getFunctionType();
43309467b48Spatrick   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
43409467b48Spatrick 
43509467b48Spatrick   // Check the argument types.
43609467b48Spatrick   if (NumArgs > 3)
43709467b48Spatrick     report_fatal_error("Invalid number of arguments of main() supplied");
43809467b48Spatrick   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
43909467b48Spatrick     report_fatal_error("Invalid type for third argument of main() supplied");
44009467b48Spatrick   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
44109467b48Spatrick     report_fatal_error("Invalid type for second argument of main() supplied");
44209467b48Spatrick   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
44309467b48Spatrick     report_fatal_error("Invalid type for first argument of main() supplied");
44409467b48Spatrick   if (!FTy->getReturnType()->isIntegerTy() &&
44509467b48Spatrick       !FTy->getReturnType()->isVoidTy())
44609467b48Spatrick     report_fatal_error("Invalid return type of main() supplied");
44709467b48Spatrick 
44809467b48Spatrick   ArgvArray CArgv;
44909467b48Spatrick   ArgvArray CEnv;
45009467b48Spatrick   if (NumArgs) {
45109467b48Spatrick     GVArgs.push_back(GVArgc); // Arg #0 = argc.
45209467b48Spatrick     if (NumArgs > 1) {
45309467b48Spatrick       // Arg #1 = argv.
45409467b48Spatrick       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
45509467b48Spatrick       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
45609467b48Spatrick              "argv[0] was null after CreateArgv");
45709467b48Spatrick       if (NumArgs > 2) {
45809467b48Spatrick         std::vector<std::string> EnvVars;
45909467b48Spatrick         for (unsigned i = 0; envp[i]; ++i)
46009467b48Spatrick           EnvVars.emplace_back(envp[i]);
46109467b48Spatrick         // Arg #2 = envp.
46209467b48Spatrick         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
46309467b48Spatrick       }
46409467b48Spatrick     }
46509467b48Spatrick   }
46609467b48Spatrick 
46709467b48Spatrick   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
46809467b48Spatrick }
46909467b48Spatrick 
EngineBuilder()47009467b48Spatrick EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
47109467b48Spatrick 
EngineBuilder(std::unique_ptr<Module> M)47209467b48Spatrick EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
47309467b48Spatrick     : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
47473471bf0Spatrick       OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr) {
47509467b48Spatrick // IR module verification is enabled by default in debug builds, and disabled
47609467b48Spatrick // by default in release builds.
47709467b48Spatrick #ifndef NDEBUG
47809467b48Spatrick   VerifyModules = true;
47909467b48Spatrick #else
48009467b48Spatrick   VerifyModules = false;
48109467b48Spatrick #endif
48209467b48Spatrick }
48309467b48Spatrick 
48409467b48Spatrick EngineBuilder::~EngineBuilder() = default;
48509467b48Spatrick 
setMCJITMemoryManager(std::unique_ptr<RTDyldMemoryManager> mcjmm)48609467b48Spatrick EngineBuilder &EngineBuilder::setMCJITMemoryManager(
48709467b48Spatrick                                    std::unique_ptr<RTDyldMemoryManager> mcjmm) {
48809467b48Spatrick   auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
48909467b48Spatrick   MemMgr = SharedMM;
49009467b48Spatrick   Resolver = SharedMM;
49109467b48Spatrick   return *this;
49209467b48Spatrick }
49309467b48Spatrick 
49409467b48Spatrick EngineBuilder&
setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM)49509467b48Spatrick EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
49609467b48Spatrick   MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
49709467b48Spatrick   return *this;
49809467b48Spatrick }
49909467b48Spatrick 
50009467b48Spatrick EngineBuilder &
setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR)50109467b48Spatrick EngineBuilder::setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR) {
50209467b48Spatrick   Resolver = std::shared_ptr<LegacyJITSymbolResolver>(std::move(SR));
50309467b48Spatrick   return *this;
50409467b48Spatrick }
50509467b48Spatrick 
create(TargetMachine * TM)50609467b48Spatrick ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
50709467b48Spatrick   std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
50809467b48Spatrick 
50909467b48Spatrick   // Make sure we can resolve symbols in the program as well. The zero arg
51009467b48Spatrick   // to the function tells DynamicLibrary to load the program, not a library.
51109467b48Spatrick   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
51209467b48Spatrick     return nullptr;
51309467b48Spatrick 
51409467b48Spatrick   // If the user specified a memory manager but didn't specify which engine to
51509467b48Spatrick   // create, we assume they only want the JIT, and we fail if they only want
51609467b48Spatrick   // the interpreter.
51709467b48Spatrick   if (MemMgr) {
51809467b48Spatrick     if (WhichEngine & EngineKind::JIT)
51909467b48Spatrick       WhichEngine = EngineKind::JIT;
52009467b48Spatrick     else {
52109467b48Spatrick       if (ErrorStr)
52209467b48Spatrick         *ErrorStr = "Cannot create an interpreter with a memory manager.";
52309467b48Spatrick       return nullptr;
52409467b48Spatrick     }
52509467b48Spatrick   }
52609467b48Spatrick 
52709467b48Spatrick   // Unless the interpreter was explicitly selected or the JIT is not linked,
52809467b48Spatrick   // try making a JIT.
52909467b48Spatrick   if ((WhichEngine & EngineKind::JIT) && TheTM) {
53009467b48Spatrick     if (!TM->getTarget().hasJIT()) {
53109467b48Spatrick       errs() << "WARNING: This target JIT is not designed for the host"
53209467b48Spatrick              << " you are running.  If bad things happen, please choose"
53309467b48Spatrick              << " a different -march switch.\n";
53409467b48Spatrick     }
53509467b48Spatrick 
53609467b48Spatrick     ExecutionEngine *EE = nullptr;
53773471bf0Spatrick     if (ExecutionEngine::MCJITCtor)
53809467b48Spatrick       EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
53909467b48Spatrick                                       std::move(Resolver), std::move(TheTM));
54009467b48Spatrick 
54109467b48Spatrick     if (EE) {
54209467b48Spatrick       EE->setVerifyModules(VerifyModules);
54309467b48Spatrick       return EE;
54409467b48Spatrick     }
54509467b48Spatrick   }
54609467b48Spatrick 
54709467b48Spatrick   // If we can't make a JIT and we didn't request one specifically, try making
54809467b48Spatrick   // an interpreter instead.
54909467b48Spatrick   if (WhichEngine & EngineKind::Interpreter) {
55009467b48Spatrick     if (ExecutionEngine::InterpCtor)
55109467b48Spatrick       return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
55209467b48Spatrick     if (ErrorStr)
55309467b48Spatrick       *ErrorStr = "Interpreter has not been linked in.";
55409467b48Spatrick     return nullptr;
55509467b48Spatrick   }
55609467b48Spatrick 
55709467b48Spatrick   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
55809467b48Spatrick     if (ErrorStr)
55909467b48Spatrick       *ErrorStr = "JIT has not been linked in.";
56009467b48Spatrick   }
56109467b48Spatrick 
56209467b48Spatrick   return nullptr;
56309467b48Spatrick }
56409467b48Spatrick 
getPointerToGlobal(const GlobalValue * GV)56509467b48Spatrick void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
56609467b48Spatrick   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
56709467b48Spatrick     return getPointerToFunction(F);
56809467b48Spatrick 
56909467b48Spatrick   std::lock_guard<sys::Mutex> locked(lock);
57009467b48Spatrick   if (void* P = getPointerToGlobalIfAvailable(GV))
57109467b48Spatrick     return P;
57209467b48Spatrick 
57309467b48Spatrick   // Global variable might have been added since interpreter started.
57409467b48Spatrick   if (GlobalVariable *GVar =
57509467b48Spatrick           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
576097a140dSpatrick     emitGlobalVariable(GVar);
57709467b48Spatrick   else
57809467b48Spatrick     llvm_unreachable("Global hasn't had an address allocated yet!");
57909467b48Spatrick 
58009467b48Spatrick   return getPointerToGlobalIfAvailable(GV);
58109467b48Spatrick }
58209467b48Spatrick 
58309467b48Spatrick /// Converts a Constant* into a GenericValue, including handling of
58409467b48Spatrick /// ConstantExpr values.
getConstantValue(const Constant * C)58509467b48Spatrick GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
58609467b48Spatrick   // If its undefined, return the garbage.
58709467b48Spatrick   if (isa<UndefValue>(C)) {
58809467b48Spatrick     GenericValue Result;
58909467b48Spatrick     switch (C->getType()->getTypeID()) {
59009467b48Spatrick     default:
59109467b48Spatrick       break;
59209467b48Spatrick     case Type::IntegerTyID:
59309467b48Spatrick     case Type::X86_FP80TyID:
59409467b48Spatrick     case Type::FP128TyID:
59509467b48Spatrick     case Type::PPC_FP128TyID:
59609467b48Spatrick       // Although the value is undefined, we still have to construct an APInt
59709467b48Spatrick       // with the correct bit width.
59809467b48Spatrick       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
59909467b48Spatrick       break;
60009467b48Spatrick     case Type::StructTyID: {
60109467b48Spatrick       // if the whole struct is 'undef' just reserve memory for the value.
60209467b48Spatrick       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
60309467b48Spatrick         unsigned int elemNum = STy->getNumElements();
60409467b48Spatrick         Result.AggregateVal.resize(elemNum);
60509467b48Spatrick         for (unsigned int i = 0; i < elemNum; ++i) {
60609467b48Spatrick           Type *ElemTy = STy->getElementType(i);
60709467b48Spatrick           if (ElemTy->isIntegerTy())
60809467b48Spatrick             Result.AggregateVal[i].IntVal =
60909467b48Spatrick               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
61009467b48Spatrick           else if (ElemTy->isAggregateType()) {
61109467b48Spatrick               const Constant *ElemUndef = UndefValue::get(ElemTy);
61209467b48Spatrick               Result.AggregateVal[i] = getConstantValue(ElemUndef);
61309467b48Spatrick             }
61409467b48Spatrick           }
61509467b48Spatrick         }
61609467b48Spatrick       }
61709467b48Spatrick       break;
618097a140dSpatrick       case Type::ScalableVectorTyID:
619097a140dSpatrick         report_fatal_error(
620097a140dSpatrick             "Scalable vector support not yet implemented in ExecutionEngine");
621097a140dSpatrick       case Type::FixedVectorTyID:
62209467b48Spatrick         // if the whole vector is 'undef' just reserve memory for the value.
623097a140dSpatrick         auto *VTy = cast<FixedVectorType>(C->getType());
62409467b48Spatrick         Type *ElemTy = VTy->getElementType();
62509467b48Spatrick         unsigned int elemNum = VTy->getNumElements();
62609467b48Spatrick         Result.AggregateVal.resize(elemNum);
62709467b48Spatrick         if (ElemTy->isIntegerTy())
62809467b48Spatrick           for (unsigned int i = 0; i < elemNum; ++i)
62909467b48Spatrick             Result.AggregateVal[i].IntVal =
63009467b48Spatrick                 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
63109467b48Spatrick         break;
63209467b48Spatrick     }
63309467b48Spatrick     return Result;
63409467b48Spatrick   }
63509467b48Spatrick 
63609467b48Spatrick   // Otherwise, if the value is a ConstantExpr...
63709467b48Spatrick   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
63809467b48Spatrick     Constant *Op0 = CE->getOperand(0);
63909467b48Spatrick     switch (CE->getOpcode()) {
64009467b48Spatrick     case Instruction::GetElementPtr: {
64109467b48Spatrick       // Compute the index
64209467b48Spatrick       GenericValue Result = getConstantValue(Op0);
64309467b48Spatrick       APInt Offset(DL.getPointerSizeInBits(), 0);
64409467b48Spatrick       cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
64509467b48Spatrick 
64609467b48Spatrick       char* tmp = (char*) Result.PointerVal;
64709467b48Spatrick       Result = PTOGV(tmp + Offset.getSExtValue());
64809467b48Spatrick       return Result;
64909467b48Spatrick     }
65009467b48Spatrick     case Instruction::Trunc: {
65109467b48Spatrick       GenericValue GV = getConstantValue(Op0);
65209467b48Spatrick       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
65309467b48Spatrick       GV.IntVal = GV.IntVal.trunc(BitWidth);
65409467b48Spatrick       return GV;
65509467b48Spatrick     }
65609467b48Spatrick     case Instruction::ZExt: {
65709467b48Spatrick       GenericValue GV = getConstantValue(Op0);
65809467b48Spatrick       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
65909467b48Spatrick       GV.IntVal = GV.IntVal.zext(BitWidth);
66009467b48Spatrick       return GV;
66109467b48Spatrick     }
66209467b48Spatrick     case Instruction::SExt: {
66309467b48Spatrick       GenericValue GV = getConstantValue(Op0);
66409467b48Spatrick       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
66509467b48Spatrick       GV.IntVal = GV.IntVal.sext(BitWidth);
66609467b48Spatrick       return GV;
66709467b48Spatrick     }
66809467b48Spatrick     case Instruction::FPTrunc: {
66909467b48Spatrick       // FIXME long double
67009467b48Spatrick       GenericValue GV = getConstantValue(Op0);
67109467b48Spatrick       GV.FloatVal = float(GV.DoubleVal);
67209467b48Spatrick       return GV;
67309467b48Spatrick     }
67409467b48Spatrick     case Instruction::FPExt:{
67509467b48Spatrick       // FIXME long double
67609467b48Spatrick       GenericValue GV = getConstantValue(Op0);
67709467b48Spatrick       GV.DoubleVal = double(GV.FloatVal);
67809467b48Spatrick       return GV;
67909467b48Spatrick     }
68009467b48Spatrick     case Instruction::UIToFP: {
68109467b48Spatrick       GenericValue GV = getConstantValue(Op0);
68209467b48Spatrick       if (CE->getType()->isFloatTy())
68309467b48Spatrick         GV.FloatVal = float(GV.IntVal.roundToDouble());
68409467b48Spatrick       else if (CE->getType()->isDoubleTy())
68509467b48Spatrick         GV.DoubleVal = GV.IntVal.roundToDouble();
68609467b48Spatrick       else if (CE->getType()->isX86_FP80Ty()) {
68709467b48Spatrick         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
68809467b48Spatrick         (void)apf.convertFromAPInt(GV.IntVal,
68909467b48Spatrick                                    false,
69009467b48Spatrick                                    APFloat::rmNearestTiesToEven);
69109467b48Spatrick         GV.IntVal = apf.bitcastToAPInt();
69209467b48Spatrick       }
69309467b48Spatrick       return GV;
69409467b48Spatrick     }
69509467b48Spatrick     case Instruction::SIToFP: {
69609467b48Spatrick       GenericValue GV = getConstantValue(Op0);
69709467b48Spatrick       if (CE->getType()->isFloatTy())
69809467b48Spatrick         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
69909467b48Spatrick       else if (CE->getType()->isDoubleTy())
70009467b48Spatrick         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
70109467b48Spatrick       else if (CE->getType()->isX86_FP80Ty()) {
70209467b48Spatrick         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
70309467b48Spatrick         (void)apf.convertFromAPInt(GV.IntVal,
70409467b48Spatrick                                    true,
70509467b48Spatrick                                    APFloat::rmNearestTiesToEven);
70609467b48Spatrick         GV.IntVal = apf.bitcastToAPInt();
70709467b48Spatrick       }
70809467b48Spatrick       return GV;
70909467b48Spatrick     }
71009467b48Spatrick     case Instruction::FPToUI: // double->APInt conversion handles sign
71109467b48Spatrick     case Instruction::FPToSI: {
71209467b48Spatrick       GenericValue GV = getConstantValue(Op0);
71309467b48Spatrick       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
71409467b48Spatrick       if (Op0->getType()->isFloatTy())
71509467b48Spatrick         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
71609467b48Spatrick       else if (Op0->getType()->isDoubleTy())
71709467b48Spatrick         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
71809467b48Spatrick       else if (Op0->getType()->isX86_FP80Ty()) {
71909467b48Spatrick         APFloat apf = APFloat(APFloat::x87DoubleExtended(), GV.IntVal);
72009467b48Spatrick         uint64_t v;
72109467b48Spatrick         bool ignored;
722*d415bd75Srobert         (void)apf.convertToInteger(MutableArrayRef(v), BitWidth,
72309467b48Spatrick                                    CE->getOpcode()==Instruction::FPToSI,
72409467b48Spatrick                                    APFloat::rmTowardZero, &ignored);
72509467b48Spatrick         GV.IntVal = v; // endian?
72609467b48Spatrick       }
72709467b48Spatrick       return GV;
72809467b48Spatrick     }
72909467b48Spatrick     case Instruction::PtrToInt: {
73009467b48Spatrick       GenericValue GV = getConstantValue(Op0);
73109467b48Spatrick       uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
73209467b48Spatrick       assert(PtrWidth <= 64 && "Bad pointer width");
73309467b48Spatrick       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
73409467b48Spatrick       uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
73509467b48Spatrick       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
73609467b48Spatrick       return GV;
73709467b48Spatrick     }
73809467b48Spatrick     case Instruction::IntToPtr: {
73909467b48Spatrick       GenericValue GV = getConstantValue(Op0);
74009467b48Spatrick       uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
74109467b48Spatrick       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
74209467b48Spatrick       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
74309467b48Spatrick       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
74409467b48Spatrick       return GV;
74509467b48Spatrick     }
74609467b48Spatrick     case Instruction::BitCast: {
74709467b48Spatrick       GenericValue GV = getConstantValue(Op0);
74809467b48Spatrick       Type* DestTy = CE->getType();
74909467b48Spatrick       switch (Op0->getType()->getTypeID()) {
75009467b48Spatrick         default: llvm_unreachable("Invalid bitcast operand");
75109467b48Spatrick         case Type::IntegerTyID:
75209467b48Spatrick           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
75309467b48Spatrick           if (DestTy->isFloatTy())
75409467b48Spatrick             GV.FloatVal = GV.IntVal.bitsToFloat();
75509467b48Spatrick           else if (DestTy->isDoubleTy())
75609467b48Spatrick             GV.DoubleVal = GV.IntVal.bitsToDouble();
75709467b48Spatrick           break;
75809467b48Spatrick         case Type::FloatTyID:
75909467b48Spatrick           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
76009467b48Spatrick           GV.IntVal = APInt::floatToBits(GV.FloatVal);
76109467b48Spatrick           break;
76209467b48Spatrick         case Type::DoubleTyID:
76309467b48Spatrick           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
76409467b48Spatrick           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
76509467b48Spatrick           break;
76609467b48Spatrick         case Type::PointerTyID:
76709467b48Spatrick           assert(DestTy->isPointerTy() && "Invalid bitcast");
76809467b48Spatrick           break; // getConstantValue(Op0)  above already converted it
76909467b48Spatrick       }
77009467b48Spatrick       return GV;
77109467b48Spatrick     }
77209467b48Spatrick     case Instruction::Add:
77309467b48Spatrick     case Instruction::FAdd:
77409467b48Spatrick     case Instruction::Sub:
77509467b48Spatrick     case Instruction::FSub:
77609467b48Spatrick     case Instruction::Mul:
77709467b48Spatrick     case Instruction::FMul:
77809467b48Spatrick     case Instruction::UDiv:
77909467b48Spatrick     case Instruction::SDiv:
78009467b48Spatrick     case Instruction::URem:
78109467b48Spatrick     case Instruction::SRem:
78209467b48Spatrick     case Instruction::And:
78309467b48Spatrick     case Instruction::Or:
78409467b48Spatrick     case Instruction::Xor: {
78509467b48Spatrick       GenericValue LHS = getConstantValue(Op0);
78609467b48Spatrick       GenericValue RHS = getConstantValue(CE->getOperand(1));
78709467b48Spatrick       GenericValue GV;
78809467b48Spatrick       switch (CE->getOperand(0)->getType()->getTypeID()) {
78909467b48Spatrick       default: llvm_unreachable("Bad add type!");
79009467b48Spatrick       case Type::IntegerTyID:
79109467b48Spatrick         switch (CE->getOpcode()) {
79209467b48Spatrick           default: llvm_unreachable("Invalid integer opcode");
79309467b48Spatrick           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
79409467b48Spatrick           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
79509467b48Spatrick           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
79609467b48Spatrick           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
79709467b48Spatrick           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
79809467b48Spatrick           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
79909467b48Spatrick           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
80009467b48Spatrick           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
80109467b48Spatrick           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
80209467b48Spatrick           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
80309467b48Spatrick         }
80409467b48Spatrick         break;
80509467b48Spatrick       case Type::FloatTyID:
80609467b48Spatrick         switch (CE->getOpcode()) {
80709467b48Spatrick           default: llvm_unreachable("Invalid float opcode");
80809467b48Spatrick           case Instruction::FAdd:
80909467b48Spatrick             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
81009467b48Spatrick           case Instruction::FSub:
81109467b48Spatrick             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
81209467b48Spatrick           case Instruction::FMul:
81309467b48Spatrick             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
81409467b48Spatrick           case Instruction::FDiv:
81509467b48Spatrick             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
81609467b48Spatrick           case Instruction::FRem:
81709467b48Spatrick             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
81809467b48Spatrick         }
81909467b48Spatrick         break;
82009467b48Spatrick       case Type::DoubleTyID:
82109467b48Spatrick         switch (CE->getOpcode()) {
82209467b48Spatrick           default: llvm_unreachable("Invalid double opcode");
82309467b48Spatrick           case Instruction::FAdd:
82409467b48Spatrick             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
82509467b48Spatrick           case Instruction::FSub:
82609467b48Spatrick             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
82709467b48Spatrick           case Instruction::FMul:
82809467b48Spatrick             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
82909467b48Spatrick           case Instruction::FDiv:
83009467b48Spatrick             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
83109467b48Spatrick           case Instruction::FRem:
83209467b48Spatrick             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
83309467b48Spatrick         }
83409467b48Spatrick         break;
83509467b48Spatrick       case Type::X86_FP80TyID:
83609467b48Spatrick       case Type::PPC_FP128TyID:
83709467b48Spatrick       case Type::FP128TyID: {
83809467b48Spatrick         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
83909467b48Spatrick         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
84009467b48Spatrick         switch (CE->getOpcode()) {
84109467b48Spatrick           default: llvm_unreachable("Invalid long double opcode");
84209467b48Spatrick           case Instruction::FAdd:
84309467b48Spatrick             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
84409467b48Spatrick             GV.IntVal = apfLHS.bitcastToAPInt();
84509467b48Spatrick             break;
84609467b48Spatrick           case Instruction::FSub:
84709467b48Spatrick             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
84809467b48Spatrick                             APFloat::rmNearestTiesToEven);
84909467b48Spatrick             GV.IntVal = apfLHS.bitcastToAPInt();
85009467b48Spatrick             break;
85109467b48Spatrick           case Instruction::FMul:
85209467b48Spatrick             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
85309467b48Spatrick                             APFloat::rmNearestTiesToEven);
85409467b48Spatrick             GV.IntVal = apfLHS.bitcastToAPInt();
85509467b48Spatrick             break;
85609467b48Spatrick           case Instruction::FDiv:
85709467b48Spatrick             apfLHS.divide(APFloat(Sem, RHS.IntVal),
85809467b48Spatrick                           APFloat::rmNearestTiesToEven);
85909467b48Spatrick             GV.IntVal = apfLHS.bitcastToAPInt();
86009467b48Spatrick             break;
86109467b48Spatrick           case Instruction::FRem:
86209467b48Spatrick             apfLHS.mod(APFloat(Sem, RHS.IntVal));
86309467b48Spatrick             GV.IntVal = apfLHS.bitcastToAPInt();
86409467b48Spatrick             break;
86509467b48Spatrick           }
86609467b48Spatrick         }
86709467b48Spatrick         break;
86809467b48Spatrick       }
86909467b48Spatrick       return GV;
87009467b48Spatrick     }
87109467b48Spatrick     default:
87209467b48Spatrick       break;
87309467b48Spatrick     }
87409467b48Spatrick 
87509467b48Spatrick     SmallString<256> Msg;
87609467b48Spatrick     raw_svector_ostream OS(Msg);
87709467b48Spatrick     OS << "ConstantExpr not handled: " << *CE;
87809467b48Spatrick     report_fatal_error(OS.str());
87909467b48Spatrick   }
88009467b48Spatrick 
88109467b48Spatrick   // Otherwise, we have a simple constant.
88209467b48Spatrick   GenericValue Result;
88309467b48Spatrick   switch (C->getType()->getTypeID()) {
88409467b48Spatrick   case Type::FloatTyID:
88509467b48Spatrick     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
88609467b48Spatrick     break;
88709467b48Spatrick   case Type::DoubleTyID:
88809467b48Spatrick     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
88909467b48Spatrick     break;
89009467b48Spatrick   case Type::X86_FP80TyID:
89109467b48Spatrick   case Type::FP128TyID:
89209467b48Spatrick   case Type::PPC_FP128TyID:
89309467b48Spatrick     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
89409467b48Spatrick     break;
89509467b48Spatrick   case Type::IntegerTyID:
89609467b48Spatrick     Result.IntVal = cast<ConstantInt>(C)->getValue();
89709467b48Spatrick     break;
89809467b48Spatrick   case Type::PointerTyID:
89909467b48Spatrick     while (auto *A = dyn_cast<GlobalAlias>(C)) {
90009467b48Spatrick       C = A->getAliasee();
90109467b48Spatrick     }
90209467b48Spatrick     if (isa<ConstantPointerNull>(C))
90309467b48Spatrick       Result.PointerVal = nullptr;
90409467b48Spatrick     else if (const Function *F = dyn_cast<Function>(C))
90509467b48Spatrick       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
90609467b48Spatrick     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
90709467b48Spatrick       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
90809467b48Spatrick     else
90909467b48Spatrick       llvm_unreachable("Unknown constant pointer type!");
91009467b48Spatrick     break;
911097a140dSpatrick   case Type::ScalableVectorTyID:
912097a140dSpatrick     report_fatal_error(
913097a140dSpatrick         "Scalable vector support not yet implemented in ExecutionEngine");
914097a140dSpatrick   case Type::FixedVectorTyID: {
91509467b48Spatrick     unsigned elemNum;
91609467b48Spatrick     Type* ElemTy;
91709467b48Spatrick     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
91809467b48Spatrick     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
91909467b48Spatrick     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
92009467b48Spatrick 
92109467b48Spatrick     if (CDV) {
92209467b48Spatrick         elemNum = CDV->getNumElements();
92309467b48Spatrick         ElemTy = CDV->getElementType();
92409467b48Spatrick     } else if (CV || CAZ) {
925097a140dSpatrick       auto *VTy = cast<FixedVectorType>(C->getType());
92609467b48Spatrick       elemNum = VTy->getNumElements();
92709467b48Spatrick       ElemTy = VTy->getElementType();
92809467b48Spatrick     } else {
92909467b48Spatrick         llvm_unreachable("Unknown constant vector type!");
93009467b48Spatrick     }
93109467b48Spatrick 
93209467b48Spatrick     Result.AggregateVal.resize(elemNum);
93309467b48Spatrick     // Check if vector holds floats.
93409467b48Spatrick     if(ElemTy->isFloatTy()) {
93509467b48Spatrick       if (CAZ) {
93609467b48Spatrick         GenericValue floatZero;
93709467b48Spatrick         floatZero.FloatVal = 0.f;
93809467b48Spatrick         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
93909467b48Spatrick                   floatZero);
94009467b48Spatrick         break;
94109467b48Spatrick       }
94209467b48Spatrick       if(CV) {
94309467b48Spatrick         for (unsigned i = 0; i < elemNum; ++i)
94409467b48Spatrick           if (!isa<UndefValue>(CV->getOperand(i)))
94509467b48Spatrick             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
94609467b48Spatrick               CV->getOperand(i))->getValueAPF().convertToFloat();
94709467b48Spatrick         break;
94809467b48Spatrick       }
94909467b48Spatrick       if(CDV)
95009467b48Spatrick         for (unsigned i = 0; i < elemNum; ++i)
95109467b48Spatrick           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
95209467b48Spatrick 
95309467b48Spatrick       break;
95409467b48Spatrick     }
95509467b48Spatrick     // Check if vector holds doubles.
95609467b48Spatrick     if (ElemTy->isDoubleTy()) {
95709467b48Spatrick       if (CAZ) {
95809467b48Spatrick         GenericValue doubleZero;
95909467b48Spatrick         doubleZero.DoubleVal = 0.0;
96009467b48Spatrick         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
96109467b48Spatrick                   doubleZero);
96209467b48Spatrick         break;
96309467b48Spatrick       }
96409467b48Spatrick       if(CV) {
96509467b48Spatrick         for (unsigned i = 0; i < elemNum; ++i)
96609467b48Spatrick           if (!isa<UndefValue>(CV->getOperand(i)))
96709467b48Spatrick             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
96809467b48Spatrick               CV->getOperand(i))->getValueAPF().convertToDouble();
96909467b48Spatrick         break;
97009467b48Spatrick       }
97109467b48Spatrick       if(CDV)
97209467b48Spatrick         for (unsigned i = 0; i < elemNum; ++i)
97309467b48Spatrick           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
97409467b48Spatrick 
97509467b48Spatrick       break;
97609467b48Spatrick     }
97709467b48Spatrick     // Check if vector holds integers.
97809467b48Spatrick     if (ElemTy->isIntegerTy()) {
97909467b48Spatrick       if (CAZ) {
98009467b48Spatrick         GenericValue intZero;
98109467b48Spatrick         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
98209467b48Spatrick         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
98309467b48Spatrick                   intZero);
98409467b48Spatrick         break;
98509467b48Spatrick       }
98609467b48Spatrick       if(CV) {
98709467b48Spatrick         for (unsigned i = 0; i < elemNum; ++i)
98809467b48Spatrick           if (!isa<UndefValue>(CV->getOperand(i)))
98909467b48Spatrick             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
99009467b48Spatrick                                             CV->getOperand(i))->getValue();
99109467b48Spatrick           else {
99209467b48Spatrick             Result.AggregateVal[i].IntVal =
99309467b48Spatrick               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
99409467b48Spatrick           }
99509467b48Spatrick         break;
99609467b48Spatrick       }
99709467b48Spatrick       if(CDV)
99809467b48Spatrick         for (unsigned i = 0; i < elemNum; ++i)
99909467b48Spatrick           Result.AggregateVal[i].IntVal = APInt(
100009467b48Spatrick             CDV->getElementType()->getPrimitiveSizeInBits(),
100109467b48Spatrick             CDV->getElementAsInteger(i));
100209467b48Spatrick 
100309467b48Spatrick       break;
100409467b48Spatrick     }
100509467b48Spatrick     llvm_unreachable("Unknown constant pointer type!");
1006097a140dSpatrick   } break;
100709467b48Spatrick 
100809467b48Spatrick   default:
100909467b48Spatrick     SmallString<256> Msg;
101009467b48Spatrick     raw_svector_ostream OS(Msg);
101109467b48Spatrick     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
101209467b48Spatrick     report_fatal_error(OS.str());
101309467b48Spatrick   }
101409467b48Spatrick 
101509467b48Spatrick   return Result;
101609467b48Spatrick }
101709467b48Spatrick 
StoreValueToMemory(const GenericValue & Val,GenericValue * Ptr,Type * Ty)101809467b48Spatrick void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
101909467b48Spatrick                                          GenericValue *Ptr, Type *Ty) {
102009467b48Spatrick   const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
102109467b48Spatrick 
102209467b48Spatrick   switch (Ty->getTypeID()) {
102309467b48Spatrick   default:
102409467b48Spatrick     dbgs() << "Cannot store value of type " << *Ty << "!\n";
102509467b48Spatrick     break;
102609467b48Spatrick   case Type::IntegerTyID:
102709467b48Spatrick     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
102809467b48Spatrick     break;
102909467b48Spatrick   case Type::FloatTyID:
103009467b48Spatrick     *((float*)Ptr) = Val.FloatVal;
103109467b48Spatrick     break;
103209467b48Spatrick   case Type::DoubleTyID:
103309467b48Spatrick     *((double*)Ptr) = Val.DoubleVal;
103409467b48Spatrick     break;
103509467b48Spatrick   case Type::X86_FP80TyID:
103609467b48Spatrick     memcpy(Ptr, Val.IntVal.getRawData(), 10);
103709467b48Spatrick     break;
103809467b48Spatrick   case Type::PointerTyID:
103909467b48Spatrick     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
104009467b48Spatrick     if (StoreBytes != sizeof(PointerTy))
104109467b48Spatrick       memset(&(Ptr->PointerVal), 0, StoreBytes);
104209467b48Spatrick 
104309467b48Spatrick     *((PointerTy*)Ptr) = Val.PointerVal;
104409467b48Spatrick     break;
1045097a140dSpatrick   case Type::FixedVectorTyID:
1046097a140dSpatrick   case Type::ScalableVectorTyID:
104709467b48Spatrick     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
104809467b48Spatrick       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
104909467b48Spatrick         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
105009467b48Spatrick       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
105109467b48Spatrick         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
105209467b48Spatrick       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
105309467b48Spatrick         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
105409467b48Spatrick         StoreIntToMemory(Val.AggregateVal[i].IntVal,
105509467b48Spatrick           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
105609467b48Spatrick       }
105709467b48Spatrick     }
105809467b48Spatrick     break;
105909467b48Spatrick   }
106009467b48Spatrick 
106109467b48Spatrick   if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
106209467b48Spatrick     // Host and target are different endian - reverse the stored bytes.
106309467b48Spatrick     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
106409467b48Spatrick }
106509467b48Spatrick 
106609467b48Spatrick /// FIXME: document
106709467b48Spatrick ///
LoadValueFromMemory(GenericValue & Result,GenericValue * Ptr,Type * Ty)106809467b48Spatrick void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
106909467b48Spatrick                                           GenericValue *Ptr,
107009467b48Spatrick                                           Type *Ty) {
107109467b48Spatrick   const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
107209467b48Spatrick 
107309467b48Spatrick   switch (Ty->getTypeID()) {
107409467b48Spatrick   case Type::IntegerTyID:
107509467b48Spatrick     // An APInt with all words initially zero.
107609467b48Spatrick     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
107709467b48Spatrick     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
107809467b48Spatrick     break;
107909467b48Spatrick   case Type::FloatTyID:
108009467b48Spatrick     Result.FloatVal = *((float*)Ptr);
108109467b48Spatrick     break;
108209467b48Spatrick   case Type::DoubleTyID:
108309467b48Spatrick     Result.DoubleVal = *((double*)Ptr);
108409467b48Spatrick     break;
108509467b48Spatrick   case Type::PointerTyID:
108609467b48Spatrick     Result.PointerVal = *((PointerTy*)Ptr);
108709467b48Spatrick     break;
108809467b48Spatrick   case Type::X86_FP80TyID: {
108909467b48Spatrick     // This is endian dependent, but it will only work on x86 anyway.
109009467b48Spatrick     // FIXME: Will not trap if loading a signaling NaN.
109109467b48Spatrick     uint64_t y[2];
109209467b48Spatrick     memcpy(y, Ptr, 10);
109309467b48Spatrick     Result.IntVal = APInt(80, y);
109409467b48Spatrick     break;
109509467b48Spatrick   }
1096097a140dSpatrick   case Type::ScalableVectorTyID:
1097097a140dSpatrick     report_fatal_error(
1098097a140dSpatrick         "Scalable vector support not yet implemented in ExecutionEngine");
1099097a140dSpatrick   case Type::FixedVectorTyID: {
1100097a140dSpatrick     auto *VT = cast<FixedVectorType>(Ty);
110109467b48Spatrick     Type *ElemT = VT->getElementType();
110209467b48Spatrick     const unsigned numElems = VT->getNumElements();
110309467b48Spatrick     if (ElemT->isFloatTy()) {
110409467b48Spatrick       Result.AggregateVal.resize(numElems);
110509467b48Spatrick       for (unsigned i = 0; i < numElems; ++i)
110609467b48Spatrick         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
110709467b48Spatrick     }
110809467b48Spatrick     if (ElemT->isDoubleTy()) {
110909467b48Spatrick       Result.AggregateVal.resize(numElems);
111009467b48Spatrick       for (unsigned i = 0; i < numElems; ++i)
111109467b48Spatrick         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
111209467b48Spatrick     }
111309467b48Spatrick     if (ElemT->isIntegerTy()) {
111409467b48Spatrick       GenericValue intZero;
111509467b48Spatrick       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
111609467b48Spatrick       intZero.IntVal = APInt(elemBitWidth, 0);
111709467b48Spatrick       Result.AggregateVal.resize(numElems, intZero);
111809467b48Spatrick       for (unsigned i = 0; i < numElems; ++i)
111909467b48Spatrick         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
112009467b48Spatrick           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
112109467b48Spatrick     }
112209467b48Spatrick   break;
112309467b48Spatrick   }
112409467b48Spatrick   default:
112509467b48Spatrick     SmallString<256> Msg;
112609467b48Spatrick     raw_svector_ostream OS(Msg);
112709467b48Spatrick     OS << "Cannot load value of type " << *Ty << "!";
112809467b48Spatrick     report_fatal_error(OS.str());
112909467b48Spatrick   }
113009467b48Spatrick }
113109467b48Spatrick 
InitializeMemory(const Constant * Init,void * Addr)113209467b48Spatrick void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
113309467b48Spatrick   LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
113409467b48Spatrick   LLVM_DEBUG(Init->dump());
113509467b48Spatrick   if (isa<UndefValue>(Init))
113609467b48Spatrick     return;
113709467b48Spatrick 
113809467b48Spatrick   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
113909467b48Spatrick     unsigned ElementSize =
114009467b48Spatrick         getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
114109467b48Spatrick     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
114209467b48Spatrick       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
114309467b48Spatrick     return;
114409467b48Spatrick   }
114509467b48Spatrick 
114609467b48Spatrick   if (isa<ConstantAggregateZero>(Init)) {
114709467b48Spatrick     memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
114809467b48Spatrick     return;
114909467b48Spatrick   }
115009467b48Spatrick 
115109467b48Spatrick   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
115209467b48Spatrick     unsigned ElementSize =
115309467b48Spatrick         getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
115409467b48Spatrick     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
115509467b48Spatrick       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
115609467b48Spatrick     return;
115709467b48Spatrick   }
115809467b48Spatrick 
115909467b48Spatrick   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
116009467b48Spatrick     const StructLayout *SL =
116109467b48Spatrick         getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
116209467b48Spatrick     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
116309467b48Spatrick       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
116409467b48Spatrick     return;
116509467b48Spatrick   }
116609467b48Spatrick 
116709467b48Spatrick   if (const ConstantDataSequential *CDS =
116809467b48Spatrick                dyn_cast<ConstantDataSequential>(Init)) {
116909467b48Spatrick     // CDS is already laid out in host memory order.
117009467b48Spatrick     StringRef Data = CDS->getRawDataValues();
117109467b48Spatrick     memcpy(Addr, Data.data(), Data.size());
117209467b48Spatrick     return;
117309467b48Spatrick   }
117409467b48Spatrick 
117509467b48Spatrick   if (Init->getType()->isFirstClassType()) {
117609467b48Spatrick     GenericValue Val = getConstantValue(Init);
117709467b48Spatrick     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
117809467b48Spatrick     return;
117909467b48Spatrick   }
118009467b48Spatrick 
118109467b48Spatrick   LLVM_DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
118209467b48Spatrick   llvm_unreachable("Unknown constant type to initialize memory with!");
118309467b48Spatrick }
118409467b48Spatrick 
118509467b48Spatrick /// EmitGlobals - Emit all of the global variables to memory, storing their
118609467b48Spatrick /// addresses into GlobalAddress.  This must make sure to copy the contents of
118709467b48Spatrick /// their initializers into the memory.
emitGlobals()118809467b48Spatrick void ExecutionEngine::emitGlobals() {
118909467b48Spatrick   // Loop over all of the global variables in the program, allocating the memory
119009467b48Spatrick   // to hold them.  If there is more than one module, do a prepass over globals
119109467b48Spatrick   // to figure out how the different modules should link together.
119209467b48Spatrick   std::map<std::pair<std::string, Type*>,
119309467b48Spatrick            const GlobalValue*> LinkedGlobalsMap;
119409467b48Spatrick 
119509467b48Spatrick   if (Modules.size() != 1) {
119609467b48Spatrick     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
119709467b48Spatrick       Module &M = *Modules[m];
119809467b48Spatrick       for (const auto &GV : M.globals()) {
119909467b48Spatrick         if (GV.hasLocalLinkage() || GV.isDeclaration() ||
120009467b48Spatrick             GV.hasAppendingLinkage() || !GV.hasName())
120109467b48Spatrick           continue;// Ignore external globals and globals with internal linkage.
120209467b48Spatrick 
1203097a140dSpatrick         const GlobalValue *&GVEntry = LinkedGlobalsMap[std::make_pair(
1204097a140dSpatrick             std::string(GV.getName()), GV.getType())];
120509467b48Spatrick 
120609467b48Spatrick         // If this is the first time we've seen this global, it is the canonical
120709467b48Spatrick         // version.
120809467b48Spatrick         if (!GVEntry) {
120909467b48Spatrick           GVEntry = &GV;
121009467b48Spatrick           continue;
121109467b48Spatrick         }
121209467b48Spatrick 
121309467b48Spatrick         // If the existing global is strong, never replace it.
121409467b48Spatrick         if (GVEntry->hasExternalLinkage())
121509467b48Spatrick           continue;
121609467b48Spatrick 
121709467b48Spatrick         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
121809467b48Spatrick         // symbol.  FIXME is this right for common?
121909467b48Spatrick         if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
122009467b48Spatrick           GVEntry = &GV;
122109467b48Spatrick       }
122209467b48Spatrick     }
122309467b48Spatrick   }
122409467b48Spatrick 
122509467b48Spatrick   std::vector<const GlobalValue*> NonCanonicalGlobals;
122609467b48Spatrick   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
122709467b48Spatrick     Module &M = *Modules[m];
122809467b48Spatrick     for (const auto &GV : M.globals()) {
122909467b48Spatrick       // In the multi-module case, see what this global maps to.
123009467b48Spatrick       if (!LinkedGlobalsMap.empty()) {
1231097a140dSpatrick         if (const GlobalValue *GVEntry = LinkedGlobalsMap[std::make_pair(
1232097a140dSpatrick                 std::string(GV.getName()), GV.getType())]) {
123309467b48Spatrick           // If something else is the canonical global, ignore this one.
123409467b48Spatrick           if (GVEntry != &GV) {
123509467b48Spatrick             NonCanonicalGlobals.push_back(&GV);
123609467b48Spatrick             continue;
123709467b48Spatrick           }
123809467b48Spatrick         }
123909467b48Spatrick       }
124009467b48Spatrick 
124109467b48Spatrick       if (!GV.isDeclaration()) {
124209467b48Spatrick         addGlobalMapping(&GV, getMemoryForGV(&GV));
124309467b48Spatrick       } else {
124409467b48Spatrick         // External variable reference. Try to use the dynamic loader to
124509467b48Spatrick         // get a pointer to it.
1246097a140dSpatrick         if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
1247097a140dSpatrick                 std::string(GV.getName())))
124809467b48Spatrick           addGlobalMapping(&GV, SymAddr);
124909467b48Spatrick         else {
125009467b48Spatrick           report_fatal_error("Could not resolve external global address: "
125109467b48Spatrick                             +GV.getName());
125209467b48Spatrick         }
125309467b48Spatrick       }
125409467b48Spatrick     }
125509467b48Spatrick 
125609467b48Spatrick     // If there are multiple modules, map the non-canonical globals to their
125709467b48Spatrick     // canonical location.
125809467b48Spatrick     if (!NonCanonicalGlobals.empty()) {
1259*d415bd75Srobert       for (const GlobalValue *GV : NonCanonicalGlobals) {
1260097a140dSpatrick         const GlobalValue *CGV = LinkedGlobalsMap[std::make_pair(
1261097a140dSpatrick             std::string(GV->getName()), GV->getType())];
126209467b48Spatrick         void *Ptr = getPointerToGlobalIfAvailable(CGV);
126309467b48Spatrick         assert(Ptr && "Canonical global wasn't codegen'd!");
126409467b48Spatrick         addGlobalMapping(GV, Ptr);
126509467b48Spatrick       }
126609467b48Spatrick     }
126709467b48Spatrick 
126809467b48Spatrick     // Now that all of the globals are set up in memory, loop through them all
126909467b48Spatrick     // and initialize their contents.
127009467b48Spatrick     for (const auto &GV : M.globals()) {
127109467b48Spatrick       if (!GV.isDeclaration()) {
127209467b48Spatrick         if (!LinkedGlobalsMap.empty()) {
1273097a140dSpatrick           if (const GlobalValue *GVEntry = LinkedGlobalsMap[std::make_pair(
1274097a140dSpatrick                   std::string(GV.getName()), GV.getType())])
127509467b48Spatrick             if (GVEntry != &GV)  // Not the canonical variable.
127609467b48Spatrick               continue;
127709467b48Spatrick         }
1278097a140dSpatrick         emitGlobalVariable(&GV);
127909467b48Spatrick       }
128009467b48Spatrick     }
128109467b48Spatrick   }
128209467b48Spatrick }
128309467b48Spatrick 
128409467b48Spatrick // EmitGlobalVariable - This method emits the specified global variable to the
128509467b48Spatrick // address specified in GlobalAddresses, or allocates new memory if it's not
128609467b48Spatrick // already in the map.
emitGlobalVariable(const GlobalVariable * GV)1287097a140dSpatrick void ExecutionEngine::emitGlobalVariable(const GlobalVariable *GV) {
128809467b48Spatrick   void *GA = getPointerToGlobalIfAvailable(GV);
128909467b48Spatrick 
129009467b48Spatrick   if (!GA) {
129109467b48Spatrick     // If it's not already specified, allocate memory for the global.
129209467b48Spatrick     GA = getMemoryForGV(GV);
129309467b48Spatrick 
129409467b48Spatrick     // If we failed to allocate memory for this global, return.
129509467b48Spatrick     if (!GA) return;
129609467b48Spatrick 
129709467b48Spatrick     addGlobalMapping(GV, GA);
129809467b48Spatrick   }
129909467b48Spatrick 
130009467b48Spatrick   // Don't initialize if it's thread local, let the client do it.
130109467b48Spatrick   if (!GV->isThreadLocal())
130209467b48Spatrick     InitializeMemory(GV->getInitializer(), GA);
130309467b48Spatrick 
130409467b48Spatrick   Type *ElTy = GV->getValueType();
130509467b48Spatrick   size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
130609467b48Spatrick   NumInitBytes += (unsigned)GVSize;
130709467b48Spatrick   ++NumGlobals;
130809467b48Spatrick }
1309