xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp (revision 0b57cec536236d46e3dba9bd041533462f33dbb7)
1*0b57cec5SDimitry Andric //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file defines the common interface used by the various execution engine
10*0b57cec5SDimitry Andric // subclasses.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "llvm/ExecutionEngine/ExecutionEngine.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
18*0b57cec5SDimitry Andric #include "llvm/ExecutionEngine/GenericValue.h"
19*0b57cec5SDimitry Andric #include "llvm/ExecutionEngine/JITEventListener.h"
20*0b57cec5SDimitry Andric #include "llvm/ExecutionEngine/ObjectCache.h"
21*0b57cec5SDimitry Andric #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
22*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
23*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
24*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
25*0b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
26*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
28*0b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
29*0b57cec5SDimitry Andric #include "llvm/Object/Archive.h"
30*0b57cec5SDimitry Andric #include "llvm/Object/ObjectFile.h"
31*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
32*0b57cec5SDimitry Andric #include "llvm/Support/DynamicLibrary.h"
33*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
34*0b57cec5SDimitry Andric #include "llvm/Support/Host.h"
35*0b57cec5SDimitry Andric #include "llvm/Support/MutexGuard.h"
36*0b57cec5SDimitry Andric #include "llvm/Support/TargetRegistry.h"
37*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
38*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
39*0b57cec5SDimitry Andric #include <cmath>
40*0b57cec5SDimitry Andric #include <cstring>
41*0b57cec5SDimitry Andric using namespace llvm;
42*0b57cec5SDimitry Andric 
43*0b57cec5SDimitry Andric #define DEBUG_TYPE "jit"
44*0b57cec5SDimitry Andric 
45*0b57cec5SDimitry Andric STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
46*0b57cec5SDimitry Andric STATISTIC(NumGlobals  , "Number of global vars initialized");
47*0b57cec5SDimitry Andric 
48*0b57cec5SDimitry Andric ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
49*0b57cec5SDimitry Andric     std::unique_ptr<Module> M, std::string *ErrorStr,
50*0b57cec5SDimitry Andric     std::shared_ptr<MCJITMemoryManager> MemMgr,
51*0b57cec5SDimitry Andric     std::shared_ptr<LegacyJITSymbolResolver> Resolver,
52*0b57cec5SDimitry Andric     std::unique_ptr<TargetMachine> TM) = nullptr;
53*0b57cec5SDimitry Andric 
54*0b57cec5SDimitry Andric ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
55*0b57cec5SDimitry Andric     std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
56*0b57cec5SDimitry Andric     std::shared_ptr<LegacyJITSymbolResolver> Resolver,
57*0b57cec5SDimitry Andric     std::unique_ptr<TargetMachine> TM) = nullptr;
58*0b57cec5SDimitry Andric 
59*0b57cec5SDimitry Andric ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
60*0b57cec5SDimitry Andric                                                 std::string *ErrorStr) =nullptr;
61*0b57cec5SDimitry Andric 
62*0b57cec5SDimitry Andric void JITEventListener::anchor() {}
63*0b57cec5SDimitry Andric 
64*0b57cec5SDimitry Andric void ObjectCache::anchor() {}
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric void ExecutionEngine::Init(std::unique_ptr<Module> M) {
67*0b57cec5SDimitry Andric   CompilingLazily         = false;
68*0b57cec5SDimitry Andric   GVCompilationDisabled   = false;
69*0b57cec5SDimitry Andric   SymbolSearchingDisabled = false;
70*0b57cec5SDimitry Andric 
71*0b57cec5SDimitry Andric   // IR module verification is enabled by default in debug builds, and disabled
72*0b57cec5SDimitry Andric   // by default in release builds.
73*0b57cec5SDimitry Andric #ifndef NDEBUG
74*0b57cec5SDimitry Andric   VerifyModules = true;
75*0b57cec5SDimitry Andric #else
76*0b57cec5SDimitry Andric   VerifyModules = false;
77*0b57cec5SDimitry Andric #endif
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric   assert(M && "Module is null?");
80*0b57cec5SDimitry Andric   Modules.push_back(std::move(M));
81*0b57cec5SDimitry Andric }
82*0b57cec5SDimitry Andric 
83*0b57cec5SDimitry Andric ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
84*0b57cec5SDimitry Andric     : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
85*0b57cec5SDimitry Andric   Init(std::move(M));
86*0b57cec5SDimitry Andric }
87*0b57cec5SDimitry Andric 
88*0b57cec5SDimitry Andric ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
89*0b57cec5SDimitry Andric     : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
90*0b57cec5SDimitry Andric   Init(std::move(M));
91*0b57cec5SDimitry Andric }
92*0b57cec5SDimitry Andric 
93*0b57cec5SDimitry Andric ExecutionEngine::~ExecutionEngine() {
94*0b57cec5SDimitry Andric   clearAllGlobalMappings();
95*0b57cec5SDimitry Andric }
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric namespace {
98*0b57cec5SDimitry Andric /// Helper class which uses a value handler to automatically deletes the
99*0b57cec5SDimitry Andric /// memory block when the GlobalVariable is destroyed.
100*0b57cec5SDimitry Andric class GVMemoryBlock final : public CallbackVH {
101*0b57cec5SDimitry Andric   GVMemoryBlock(const GlobalVariable *GV)
102*0b57cec5SDimitry Andric     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric public:
105*0b57cec5SDimitry Andric   /// Returns the address the GlobalVariable should be written into.  The
106*0b57cec5SDimitry Andric   /// GVMemoryBlock object prefixes that.
107*0b57cec5SDimitry Andric   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
108*0b57cec5SDimitry Andric     Type *ElTy = GV->getValueType();
109*0b57cec5SDimitry Andric     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
110*0b57cec5SDimitry Andric     void *RawMemory = ::operator new(
111*0b57cec5SDimitry Andric         alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
112*0b57cec5SDimitry Andric     new(RawMemory) GVMemoryBlock(GV);
113*0b57cec5SDimitry Andric     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
114*0b57cec5SDimitry Andric   }
115*0b57cec5SDimitry Andric 
116*0b57cec5SDimitry Andric   void deleted() override {
117*0b57cec5SDimitry Andric     // We allocated with operator new and with some extra memory hanging off the
118*0b57cec5SDimitry Andric     // end, so don't just delete this.  I'm not sure if this is actually
119*0b57cec5SDimitry Andric     // required.
120*0b57cec5SDimitry Andric     this->~GVMemoryBlock();
121*0b57cec5SDimitry Andric     ::operator delete(this);
122*0b57cec5SDimitry Andric   }
123*0b57cec5SDimitry Andric };
124*0b57cec5SDimitry Andric }  // anonymous namespace
125*0b57cec5SDimitry Andric 
126*0b57cec5SDimitry Andric char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
127*0b57cec5SDimitry Andric   return GVMemoryBlock::Create(GV, getDataLayout());
128*0b57cec5SDimitry Andric }
129*0b57cec5SDimitry Andric 
130*0b57cec5SDimitry Andric void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
131*0b57cec5SDimitry Andric   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
132*0b57cec5SDimitry Andric }
133*0b57cec5SDimitry Andric 
134*0b57cec5SDimitry Andric void
135*0b57cec5SDimitry Andric ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
136*0b57cec5SDimitry Andric   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
137*0b57cec5SDimitry Andric }
138*0b57cec5SDimitry Andric 
139*0b57cec5SDimitry Andric void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
140*0b57cec5SDimitry Andric   llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
141*0b57cec5SDimitry Andric }
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric bool ExecutionEngine::removeModule(Module *M) {
144*0b57cec5SDimitry Andric   for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
145*0b57cec5SDimitry Andric     Module *Found = I->get();
146*0b57cec5SDimitry Andric     if (Found == M) {
147*0b57cec5SDimitry Andric       I->release();
148*0b57cec5SDimitry Andric       Modules.erase(I);
149*0b57cec5SDimitry Andric       clearGlobalMappingsFromModule(M);
150*0b57cec5SDimitry Andric       return true;
151*0b57cec5SDimitry Andric     }
152*0b57cec5SDimitry Andric   }
153*0b57cec5SDimitry Andric   return false;
154*0b57cec5SDimitry Andric }
155*0b57cec5SDimitry Andric 
156*0b57cec5SDimitry Andric Function *ExecutionEngine::FindFunctionNamed(StringRef FnName) {
157*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
158*0b57cec5SDimitry Andric     Function *F = Modules[i]->getFunction(FnName);
159*0b57cec5SDimitry Andric     if (F && !F->isDeclaration())
160*0b57cec5SDimitry Andric       return F;
161*0b57cec5SDimitry Andric   }
162*0b57cec5SDimitry Andric   return nullptr;
163*0b57cec5SDimitry Andric }
164*0b57cec5SDimitry Andric 
165*0b57cec5SDimitry Andric GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(StringRef Name, bool AllowInternal) {
166*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
167*0b57cec5SDimitry Andric     GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
168*0b57cec5SDimitry Andric     if (GV && !GV->isDeclaration())
169*0b57cec5SDimitry Andric       return GV;
170*0b57cec5SDimitry Andric   }
171*0b57cec5SDimitry Andric   return nullptr;
172*0b57cec5SDimitry Andric }
173*0b57cec5SDimitry Andric 
174*0b57cec5SDimitry Andric uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
175*0b57cec5SDimitry Andric   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
176*0b57cec5SDimitry Andric   uint64_t OldVal;
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
179*0b57cec5SDimitry Andric   // GlobalAddressMap.
180*0b57cec5SDimitry Andric   if (I == GlobalAddressMap.end())
181*0b57cec5SDimitry Andric     OldVal = 0;
182*0b57cec5SDimitry Andric   else {
183*0b57cec5SDimitry Andric     GlobalAddressReverseMap.erase(I->second);
184*0b57cec5SDimitry Andric     OldVal = I->second;
185*0b57cec5SDimitry Andric     GlobalAddressMap.erase(I);
186*0b57cec5SDimitry Andric   }
187*0b57cec5SDimitry Andric 
188*0b57cec5SDimitry Andric   return OldVal;
189*0b57cec5SDimitry Andric }
190*0b57cec5SDimitry Andric 
191*0b57cec5SDimitry Andric std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
192*0b57cec5SDimitry Andric   assert(GV->hasName() && "Global must have name.");
193*0b57cec5SDimitry Andric 
194*0b57cec5SDimitry Andric   MutexGuard locked(lock);
195*0b57cec5SDimitry Andric   SmallString<128> FullName;
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric   const DataLayout &DL =
198*0b57cec5SDimitry Andric     GV->getParent()->getDataLayout().isDefault()
199*0b57cec5SDimitry Andric       ? getDataLayout()
200*0b57cec5SDimitry Andric       : GV->getParent()->getDataLayout();
201*0b57cec5SDimitry Andric 
202*0b57cec5SDimitry Andric   Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
203*0b57cec5SDimitry Andric   return FullName.str();
204*0b57cec5SDimitry Andric }
205*0b57cec5SDimitry Andric 
206*0b57cec5SDimitry Andric void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
207*0b57cec5SDimitry Andric   MutexGuard locked(lock);
208*0b57cec5SDimitry Andric   addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
209*0b57cec5SDimitry Andric }
210*0b57cec5SDimitry Andric 
211*0b57cec5SDimitry Andric void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
212*0b57cec5SDimitry Andric   MutexGuard locked(lock);
213*0b57cec5SDimitry Andric 
214*0b57cec5SDimitry Andric   assert(!Name.empty() && "Empty GlobalMapping symbol name!");
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
217*0b57cec5SDimitry Andric   uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
218*0b57cec5SDimitry Andric   assert((!CurVal || !Addr) && "GlobalMapping already established!");
219*0b57cec5SDimitry Andric   CurVal = Addr;
220*0b57cec5SDimitry Andric 
221*0b57cec5SDimitry Andric   // If we are using the reverse mapping, add it too.
222*0b57cec5SDimitry Andric   if (!EEState.getGlobalAddressReverseMap().empty()) {
223*0b57cec5SDimitry Andric     std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
224*0b57cec5SDimitry Andric     assert((!V.empty() || !Name.empty()) &&
225*0b57cec5SDimitry Andric            "GlobalMapping already established!");
226*0b57cec5SDimitry Andric     V = Name;
227*0b57cec5SDimitry Andric   }
228*0b57cec5SDimitry Andric }
229*0b57cec5SDimitry Andric 
230*0b57cec5SDimitry Andric void ExecutionEngine::clearAllGlobalMappings() {
231*0b57cec5SDimitry Andric   MutexGuard locked(lock);
232*0b57cec5SDimitry Andric 
233*0b57cec5SDimitry Andric   EEState.getGlobalAddressMap().clear();
234*0b57cec5SDimitry Andric   EEState.getGlobalAddressReverseMap().clear();
235*0b57cec5SDimitry Andric }
236*0b57cec5SDimitry Andric 
237*0b57cec5SDimitry Andric void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
238*0b57cec5SDimitry Andric   MutexGuard locked(lock);
239*0b57cec5SDimitry Andric 
240*0b57cec5SDimitry Andric   for (GlobalObject &GO : M->global_objects())
241*0b57cec5SDimitry Andric     EEState.RemoveMapping(getMangledName(&GO));
242*0b57cec5SDimitry Andric }
243*0b57cec5SDimitry Andric 
244*0b57cec5SDimitry Andric uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
245*0b57cec5SDimitry Andric                                               void *Addr) {
246*0b57cec5SDimitry Andric   MutexGuard locked(lock);
247*0b57cec5SDimitry Andric   return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
248*0b57cec5SDimitry Andric }
249*0b57cec5SDimitry Andric 
250*0b57cec5SDimitry Andric uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
251*0b57cec5SDimitry Andric   MutexGuard locked(lock);
252*0b57cec5SDimitry Andric 
253*0b57cec5SDimitry Andric   ExecutionEngineState::GlobalAddressMapTy &Map =
254*0b57cec5SDimitry Andric     EEState.getGlobalAddressMap();
255*0b57cec5SDimitry Andric 
256*0b57cec5SDimitry Andric   // Deleting from the mapping?
257*0b57cec5SDimitry Andric   if (!Addr)
258*0b57cec5SDimitry Andric     return EEState.RemoveMapping(Name);
259*0b57cec5SDimitry Andric 
260*0b57cec5SDimitry Andric   uint64_t &CurVal = Map[Name];
261*0b57cec5SDimitry Andric   uint64_t OldVal = CurVal;
262*0b57cec5SDimitry Andric 
263*0b57cec5SDimitry Andric   if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
264*0b57cec5SDimitry Andric     EEState.getGlobalAddressReverseMap().erase(CurVal);
265*0b57cec5SDimitry Andric   CurVal = Addr;
266*0b57cec5SDimitry Andric 
267*0b57cec5SDimitry Andric   // If we are using the reverse mapping, add it too.
268*0b57cec5SDimitry Andric   if (!EEState.getGlobalAddressReverseMap().empty()) {
269*0b57cec5SDimitry Andric     std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
270*0b57cec5SDimitry Andric     assert((!V.empty() || !Name.empty()) &&
271*0b57cec5SDimitry Andric            "GlobalMapping already established!");
272*0b57cec5SDimitry Andric     V = Name;
273*0b57cec5SDimitry Andric   }
274*0b57cec5SDimitry Andric   return OldVal;
275*0b57cec5SDimitry Andric }
276*0b57cec5SDimitry Andric 
277*0b57cec5SDimitry Andric uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
278*0b57cec5SDimitry Andric   MutexGuard locked(lock);
279*0b57cec5SDimitry Andric   uint64_t Address = 0;
280*0b57cec5SDimitry Andric   ExecutionEngineState::GlobalAddressMapTy::iterator I =
281*0b57cec5SDimitry Andric     EEState.getGlobalAddressMap().find(S);
282*0b57cec5SDimitry Andric   if (I != EEState.getGlobalAddressMap().end())
283*0b57cec5SDimitry Andric     Address = I->second;
284*0b57cec5SDimitry Andric   return Address;
285*0b57cec5SDimitry Andric }
286*0b57cec5SDimitry Andric 
287*0b57cec5SDimitry Andric 
288*0b57cec5SDimitry Andric void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
289*0b57cec5SDimitry Andric   MutexGuard locked(lock);
290*0b57cec5SDimitry Andric   if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
291*0b57cec5SDimitry Andric     return Address;
292*0b57cec5SDimitry Andric   return nullptr;
293*0b57cec5SDimitry Andric }
294*0b57cec5SDimitry Andric 
295*0b57cec5SDimitry Andric void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
296*0b57cec5SDimitry Andric   MutexGuard locked(lock);
297*0b57cec5SDimitry Andric   return getPointerToGlobalIfAvailable(getMangledName(GV));
298*0b57cec5SDimitry Andric }
299*0b57cec5SDimitry Andric 
300*0b57cec5SDimitry Andric const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
301*0b57cec5SDimitry Andric   MutexGuard locked(lock);
302*0b57cec5SDimitry Andric 
303*0b57cec5SDimitry Andric   // If we haven't computed the reverse mapping yet, do so first.
304*0b57cec5SDimitry Andric   if (EEState.getGlobalAddressReverseMap().empty()) {
305*0b57cec5SDimitry Andric     for (ExecutionEngineState::GlobalAddressMapTy::iterator
306*0b57cec5SDimitry Andric            I = EEState.getGlobalAddressMap().begin(),
307*0b57cec5SDimitry Andric            E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
308*0b57cec5SDimitry Andric       StringRef Name = I->first();
309*0b57cec5SDimitry Andric       uint64_t Addr = I->second;
310*0b57cec5SDimitry Andric       EEState.getGlobalAddressReverseMap().insert(std::make_pair(
311*0b57cec5SDimitry Andric                                                           Addr, Name));
312*0b57cec5SDimitry Andric     }
313*0b57cec5SDimitry Andric   }
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric   std::map<uint64_t, std::string>::iterator I =
316*0b57cec5SDimitry Andric     EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
317*0b57cec5SDimitry Andric 
318*0b57cec5SDimitry Andric   if (I != EEState.getGlobalAddressReverseMap().end()) {
319*0b57cec5SDimitry Andric     StringRef Name = I->second;
320*0b57cec5SDimitry Andric     for (unsigned i = 0, e = Modules.size(); i != e; ++i)
321*0b57cec5SDimitry Andric       if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
322*0b57cec5SDimitry Andric         return GV;
323*0b57cec5SDimitry Andric   }
324*0b57cec5SDimitry Andric   return nullptr;
325*0b57cec5SDimitry Andric }
326*0b57cec5SDimitry Andric 
327*0b57cec5SDimitry Andric namespace {
328*0b57cec5SDimitry Andric class ArgvArray {
329*0b57cec5SDimitry Andric   std::unique_ptr<char[]> Array;
330*0b57cec5SDimitry Andric   std::vector<std::unique_ptr<char[]>> Values;
331*0b57cec5SDimitry Andric public:
332*0b57cec5SDimitry Andric   /// Turn a vector of strings into a nice argv style array of pointers to null
333*0b57cec5SDimitry Andric   /// terminated strings.
334*0b57cec5SDimitry Andric   void *reset(LLVMContext &C, ExecutionEngine *EE,
335*0b57cec5SDimitry Andric               const std::vector<std::string> &InputArgv);
336*0b57cec5SDimitry Andric };
337*0b57cec5SDimitry Andric }  // anonymous namespace
338*0b57cec5SDimitry Andric void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
339*0b57cec5SDimitry Andric                        const std::vector<std::string> &InputArgv) {
340*0b57cec5SDimitry Andric   Values.clear();  // Free the old contents.
341*0b57cec5SDimitry Andric   Values.reserve(InputArgv.size());
342*0b57cec5SDimitry Andric   unsigned PtrSize = EE->getDataLayout().getPointerSize();
343*0b57cec5SDimitry Andric   Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
344*0b57cec5SDimitry Andric 
345*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "JIT: ARGV = " << (void *)Array.get() << "\n");
346*0b57cec5SDimitry Andric   Type *SBytePtr = Type::getInt8PtrTy(C);
347*0b57cec5SDimitry Andric 
348*0b57cec5SDimitry Andric   for (unsigned i = 0; i != InputArgv.size(); ++i) {
349*0b57cec5SDimitry Andric     unsigned Size = InputArgv[i].size()+1;
350*0b57cec5SDimitry Andric     auto Dest = make_unique<char[]>(Size);
351*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void *)Dest.get()
352*0b57cec5SDimitry Andric                       << "\n");
353*0b57cec5SDimitry Andric 
354*0b57cec5SDimitry Andric     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
355*0b57cec5SDimitry Andric     Dest[Size-1] = 0;
356*0b57cec5SDimitry Andric 
357*0b57cec5SDimitry Andric     // Endian safe: Array[i] = (PointerTy)Dest;
358*0b57cec5SDimitry Andric     EE->StoreValueToMemory(PTOGV(Dest.get()),
359*0b57cec5SDimitry Andric                            (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
360*0b57cec5SDimitry Andric     Values.push_back(std::move(Dest));
361*0b57cec5SDimitry Andric   }
362*0b57cec5SDimitry Andric 
363*0b57cec5SDimitry Andric   // Null terminate it
364*0b57cec5SDimitry Andric   EE->StoreValueToMemory(PTOGV(nullptr),
365*0b57cec5SDimitry Andric                          (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
366*0b57cec5SDimitry Andric                          SBytePtr);
367*0b57cec5SDimitry Andric   return Array.get();
368*0b57cec5SDimitry Andric }
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
371*0b57cec5SDimitry Andric                                                        bool isDtors) {
372*0b57cec5SDimitry Andric   StringRef Name(isDtors ? "llvm.global_dtors" : "llvm.global_ctors");
373*0b57cec5SDimitry Andric   GlobalVariable *GV = module.getNamedGlobal(Name);
374*0b57cec5SDimitry Andric 
375*0b57cec5SDimitry Andric   // If this global has internal linkage, or if it has a use, then it must be
376*0b57cec5SDimitry Andric   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
377*0b57cec5SDimitry Andric   // this is the case, don't execute any of the global ctors, __main will do
378*0b57cec5SDimitry Andric   // it.
379*0b57cec5SDimitry Andric   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
380*0b57cec5SDimitry Andric 
381*0b57cec5SDimitry Andric   // Should be an array of '{ i32, void ()* }' structs.  The first value is
382*0b57cec5SDimitry Andric   // the init priority, which we ignore.
383*0b57cec5SDimitry Andric   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
384*0b57cec5SDimitry Andric   if (!InitList)
385*0b57cec5SDimitry Andric     return;
386*0b57cec5SDimitry Andric   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
387*0b57cec5SDimitry Andric     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
388*0b57cec5SDimitry Andric     if (!CS) continue;
389*0b57cec5SDimitry Andric 
390*0b57cec5SDimitry Andric     Constant *FP = CS->getOperand(1);
391*0b57cec5SDimitry Andric     if (FP->isNullValue())
392*0b57cec5SDimitry Andric       continue;  // Found a sentinal value, ignore.
393*0b57cec5SDimitry Andric 
394*0b57cec5SDimitry Andric     // Strip off constant expression casts.
395*0b57cec5SDimitry Andric     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
396*0b57cec5SDimitry Andric       if (CE->isCast())
397*0b57cec5SDimitry Andric         FP = CE->getOperand(0);
398*0b57cec5SDimitry Andric 
399*0b57cec5SDimitry Andric     // Execute the ctor/dtor function!
400*0b57cec5SDimitry Andric     if (Function *F = dyn_cast<Function>(FP))
401*0b57cec5SDimitry Andric       runFunction(F, None);
402*0b57cec5SDimitry Andric 
403*0b57cec5SDimitry Andric     // FIXME: It is marginally lame that we just do nothing here if we see an
404*0b57cec5SDimitry Andric     // entry we don't recognize. It might not be unreasonable for the verifier
405*0b57cec5SDimitry Andric     // to not even allow this and just assert here.
406*0b57cec5SDimitry Andric   }
407*0b57cec5SDimitry Andric }
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
410*0b57cec5SDimitry Andric   // Execute global ctors/dtors for each module in the program.
411*0b57cec5SDimitry Andric   for (std::unique_ptr<Module> &M : Modules)
412*0b57cec5SDimitry Andric     runStaticConstructorsDestructors(*M, isDtors);
413*0b57cec5SDimitry Andric }
414*0b57cec5SDimitry Andric 
415*0b57cec5SDimitry Andric #ifndef NDEBUG
416*0b57cec5SDimitry Andric /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
417*0b57cec5SDimitry Andric static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
418*0b57cec5SDimitry Andric   unsigned PtrSize = EE->getDataLayout().getPointerSize();
419*0b57cec5SDimitry Andric   for (unsigned i = 0; i < PtrSize; ++i)
420*0b57cec5SDimitry Andric     if (*(i + (uint8_t*)Loc))
421*0b57cec5SDimitry Andric       return false;
422*0b57cec5SDimitry Andric   return true;
423*0b57cec5SDimitry Andric }
424*0b57cec5SDimitry Andric #endif
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric int ExecutionEngine::runFunctionAsMain(Function *Fn,
427*0b57cec5SDimitry Andric                                        const std::vector<std::string> &argv,
428*0b57cec5SDimitry Andric                                        const char * const * envp) {
429*0b57cec5SDimitry Andric   std::vector<GenericValue> GVArgs;
430*0b57cec5SDimitry Andric   GenericValue GVArgc;
431*0b57cec5SDimitry Andric   GVArgc.IntVal = APInt(32, argv.size());
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric   // Check main() type
434*0b57cec5SDimitry Andric   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
435*0b57cec5SDimitry Andric   FunctionType *FTy = Fn->getFunctionType();
436*0b57cec5SDimitry Andric   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
437*0b57cec5SDimitry Andric 
438*0b57cec5SDimitry Andric   // Check the argument types.
439*0b57cec5SDimitry Andric   if (NumArgs > 3)
440*0b57cec5SDimitry Andric     report_fatal_error("Invalid number of arguments of main() supplied");
441*0b57cec5SDimitry Andric   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
442*0b57cec5SDimitry Andric     report_fatal_error("Invalid type for third argument of main() supplied");
443*0b57cec5SDimitry Andric   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
444*0b57cec5SDimitry Andric     report_fatal_error("Invalid type for second argument of main() supplied");
445*0b57cec5SDimitry Andric   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
446*0b57cec5SDimitry Andric     report_fatal_error("Invalid type for first argument of main() supplied");
447*0b57cec5SDimitry Andric   if (!FTy->getReturnType()->isIntegerTy() &&
448*0b57cec5SDimitry Andric       !FTy->getReturnType()->isVoidTy())
449*0b57cec5SDimitry Andric     report_fatal_error("Invalid return type of main() supplied");
450*0b57cec5SDimitry Andric 
451*0b57cec5SDimitry Andric   ArgvArray CArgv;
452*0b57cec5SDimitry Andric   ArgvArray CEnv;
453*0b57cec5SDimitry Andric   if (NumArgs) {
454*0b57cec5SDimitry Andric     GVArgs.push_back(GVArgc); // Arg #0 = argc.
455*0b57cec5SDimitry Andric     if (NumArgs > 1) {
456*0b57cec5SDimitry Andric       // Arg #1 = argv.
457*0b57cec5SDimitry Andric       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
458*0b57cec5SDimitry Andric       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
459*0b57cec5SDimitry Andric              "argv[0] was null after CreateArgv");
460*0b57cec5SDimitry Andric       if (NumArgs > 2) {
461*0b57cec5SDimitry Andric         std::vector<std::string> EnvVars;
462*0b57cec5SDimitry Andric         for (unsigned i = 0; envp[i]; ++i)
463*0b57cec5SDimitry Andric           EnvVars.emplace_back(envp[i]);
464*0b57cec5SDimitry Andric         // Arg #2 = envp.
465*0b57cec5SDimitry Andric         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
466*0b57cec5SDimitry Andric       }
467*0b57cec5SDimitry Andric     }
468*0b57cec5SDimitry Andric   }
469*0b57cec5SDimitry Andric 
470*0b57cec5SDimitry Andric   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
471*0b57cec5SDimitry Andric }
472*0b57cec5SDimitry Andric 
473*0b57cec5SDimitry Andric EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
474*0b57cec5SDimitry Andric 
475*0b57cec5SDimitry Andric EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
476*0b57cec5SDimitry Andric     : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
477*0b57cec5SDimitry Andric       OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
478*0b57cec5SDimitry Andric       UseOrcMCJITReplacement(false) {
479*0b57cec5SDimitry Andric // IR module verification is enabled by default in debug builds, and disabled
480*0b57cec5SDimitry Andric // by default in release builds.
481*0b57cec5SDimitry Andric #ifndef NDEBUG
482*0b57cec5SDimitry Andric   VerifyModules = true;
483*0b57cec5SDimitry Andric #else
484*0b57cec5SDimitry Andric   VerifyModules = false;
485*0b57cec5SDimitry Andric #endif
486*0b57cec5SDimitry Andric }
487*0b57cec5SDimitry Andric 
488*0b57cec5SDimitry Andric EngineBuilder::~EngineBuilder() = default;
489*0b57cec5SDimitry Andric 
490*0b57cec5SDimitry Andric EngineBuilder &EngineBuilder::setMCJITMemoryManager(
491*0b57cec5SDimitry Andric                                    std::unique_ptr<RTDyldMemoryManager> mcjmm) {
492*0b57cec5SDimitry Andric   auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
493*0b57cec5SDimitry Andric   MemMgr = SharedMM;
494*0b57cec5SDimitry Andric   Resolver = SharedMM;
495*0b57cec5SDimitry Andric   return *this;
496*0b57cec5SDimitry Andric }
497*0b57cec5SDimitry Andric 
498*0b57cec5SDimitry Andric EngineBuilder&
499*0b57cec5SDimitry Andric EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
500*0b57cec5SDimitry Andric   MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
501*0b57cec5SDimitry Andric   return *this;
502*0b57cec5SDimitry Andric }
503*0b57cec5SDimitry Andric 
504*0b57cec5SDimitry Andric EngineBuilder &
505*0b57cec5SDimitry Andric EngineBuilder::setSymbolResolver(std::unique_ptr<LegacyJITSymbolResolver> SR) {
506*0b57cec5SDimitry Andric   Resolver = std::shared_ptr<LegacyJITSymbolResolver>(std::move(SR));
507*0b57cec5SDimitry Andric   return *this;
508*0b57cec5SDimitry Andric }
509*0b57cec5SDimitry Andric 
510*0b57cec5SDimitry Andric ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
511*0b57cec5SDimitry Andric   std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
512*0b57cec5SDimitry Andric 
513*0b57cec5SDimitry Andric   // Make sure we can resolve symbols in the program as well. The zero arg
514*0b57cec5SDimitry Andric   // to the function tells DynamicLibrary to load the program, not a library.
515*0b57cec5SDimitry Andric   if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
516*0b57cec5SDimitry Andric     return nullptr;
517*0b57cec5SDimitry Andric 
518*0b57cec5SDimitry Andric   // If the user specified a memory manager but didn't specify which engine to
519*0b57cec5SDimitry Andric   // create, we assume they only want the JIT, and we fail if they only want
520*0b57cec5SDimitry Andric   // the interpreter.
521*0b57cec5SDimitry Andric   if (MemMgr) {
522*0b57cec5SDimitry Andric     if (WhichEngine & EngineKind::JIT)
523*0b57cec5SDimitry Andric       WhichEngine = EngineKind::JIT;
524*0b57cec5SDimitry Andric     else {
525*0b57cec5SDimitry Andric       if (ErrorStr)
526*0b57cec5SDimitry Andric         *ErrorStr = "Cannot create an interpreter with a memory manager.";
527*0b57cec5SDimitry Andric       return nullptr;
528*0b57cec5SDimitry Andric     }
529*0b57cec5SDimitry Andric   }
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric   // Unless the interpreter was explicitly selected or the JIT is not linked,
532*0b57cec5SDimitry Andric   // try making a JIT.
533*0b57cec5SDimitry Andric   if ((WhichEngine & EngineKind::JIT) && TheTM) {
534*0b57cec5SDimitry Andric     if (!TM->getTarget().hasJIT()) {
535*0b57cec5SDimitry Andric       errs() << "WARNING: This target JIT is not designed for the host"
536*0b57cec5SDimitry Andric              << " you are running.  If bad things happen, please choose"
537*0b57cec5SDimitry Andric              << " a different -march switch.\n";
538*0b57cec5SDimitry Andric     }
539*0b57cec5SDimitry Andric 
540*0b57cec5SDimitry Andric     ExecutionEngine *EE = nullptr;
541*0b57cec5SDimitry Andric     if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
542*0b57cec5SDimitry Andric       EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
543*0b57cec5SDimitry Andric                                                     std::move(Resolver),
544*0b57cec5SDimitry Andric                                                     std::move(TheTM));
545*0b57cec5SDimitry Andric       EE->addModule(std::move(M));
546*0b57cec5SDimitry Andric     } else if (ExecutionEngine::MCJITCtor)
547*0b57cec5SDimitry Andric       EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
548*0b57cec5SDimitry Andric                                       std::move(Resolver), std::move(TheTM));
549*0b57cec5SDimitry Andric 
550*0b57cec5SDimitry Andric     if (EE) {
551*0b57cec5SDimitry Andric       EE->setVerifyModules(VerifyModules);
552*0b57cec5SDimitry Andric       return EE;
553*0b57cec5SDimitry Andric     }
554*0b57cec5SDimitry Andric   }
555*0b57cec5SDimitry Andric 
556*0b57cec5SDimitry Andric   // If we can't make a JIT and we didn't request one specifically, try making
557*0b57cec5SDimitry Andric   // an interpreter instead.
558*0b57cec5SDimitry Andric   if (WhichEngine & EngineKind::Interpreter) {
559*0b57cec5SDimitry Andric     if (ExecutionEngine::InterpCtor)
560*0b57cec5SDimitry Andric       return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
561*0b57cec5SDimitry Andric     if (ErrorStr)
562*0b57cec5SDimitry Andric       *ErrorStr = "Interpreter has not been linked in.";
563*0b57cec5SDimitry Andric     return nullptr;
564*0b57cec5SDimitry Andric   }
565*0b57cec5SDimitry Andric 
566*0b57cec5SDimitry Andric   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
567*0b57cec5SDimitry Andric     if (ErrorStr)
568*0b57cec5SDimitry Andric       *ErrorStr = "JIT has not been linked in.";
569*0b57cec5SDimitry Andric   }
570*0b57cec5SDimitry Andric 
571*0b57cec5SDimitry Andric   return nullptr;
572*0b57cec5SDimitry Andric }
573*0b57cec5SDimitry Andric 
574*0b57cec5SDimitry Andric void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
575*0b57cec5SDimitry Andric   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
576*0b57cec5SDimitry Andric     return getPointerToFunction(F);
577*0b57cec5SDimitry Andric 
578*0b57cec5SDimitry Andric   MutexGuard locked(lock);
579*0b57cec5SDimitry Andric   if (void* P = getPointerToGlobalIfAvailable(GV))
580*0b57cec5SDimitry Andric     return P;
581*0b57cec5SDimitry Andric 
582*0b57cec5SDimitry Andric   // Global variable might have been added since interpreter started.
583*0b57cec5SDimitry Andric   if (GlobalVariable *GVar =
584*0b57cec5SDimitry Andric           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
585*0b57cec5SDimitry Andric     EmitGlobalVariable(GVar);
586*0b57cec5SDimitry Andric   else
587*0b57cec5SDimitry Andric     llvm_unreachable("Global hasn't had an address allocated yet!");
588*0b57cec5SDimitry Andric 
589*0b57cec5SDimitry Andric   return getPointerToGlobalIfAvailable(GV);
590*0b57cec5SDimitry Andric }
591*0b57cec5SDimitry Andric 
592*0b57cec5SDimitry Andric /// Converts a Constant* into a GenericValue, including handling of
593*0b57cec5SDimitry Andric /// ConstantExpr values.
594*0b57cec5SDimitry Andric GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
595*0b57cec5SDimitry Andric   // If its undefined, return the garbage.
596*0b57cec5SDimitry Andric   if (isa<UndefValue>(C)) {
597*0b57cec5SDimitry Andric     GenericValue Result;
598*0b57cec5SDimitry Andric     switch (C->getType()->getTypeID()) {
599*0b57cec5SDimitry Andric     default:
600*0b57cec5SDimitry Andric       break;
601*0b57cec5SDimitry Andric     case Type::IntegerTyID:
602*0b57cec5SDimitry Andric     case Type::X86_FP80TyID:
603*0b57cec5SDimitry Andric     case Type::FP128TyID:
604*0b57cec5SDimitry Andric     case Type::PPC_FP128TyID:
605*0b57cec5SDimitry Andric       // Although the value is undefined, we still have to construct an APInt
606*0b57cec5SDimitry Andric       // with the correct bit width.
607*0b57cec5SDimitry Andric       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
608*0b57cec5SDimitry Andric       break;
609*0b57cec5SDimitry Andric     case Type::StructTyID: {
610*0b57cec5SDimitry Andric       // if the whole struct is 'undef' just reserve memory for the value.
611*0b57cec5SDimitry Andric       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
612*0b57cec5SDimitry Andric         unsigned int elemNum = STy->getNumElements();
613*0b57cec5SDimitry Andric         Result.AggregateVal.resize(elemNum);
614*0b57cec5SDimitry Andric         for (unsigned int i = 0; i < elemNum; ++i) {
615*0b57cec5SDimitry Andric           Type *ElemTy = STy->getElementType(i);
616*0b57cec5SDimitry Andric           if (ElemTy->isIntegerTy())
617*0b57cec5SDimitry Andric             Result.AggregateVal[i].IntVal =
618*0b57cec5SDimitry Andric               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
619*0b57cec5SDimitry Andric           else if (ElemTy->isAggregateType()) {
620*0b57cec5SDimitry Andric               const Constant *ElemUndef = UndefValue::get(ElemTy);
621*0b57cec5SDimitry Andric               Result.AggregateVal[i] = getConstantValue(ElemUndef);
622*0b57cec5SDimitry Andric             }
623*0b57cec5SDimitry Andric           }
624*0b57cec5SDimitry Andric         }
625*0b57cec5SDimitry Andric       }
626*0b57cec5SDimitry Andric       break;
627*0b57cec5SDimitry Andric     case Type::VectorTyID:
628*0b57cec5SDimitry Andric       // if the whole vector is 'undef' just reserve memory for the value.
629*0b57cec5SDimitry Andric       auto* VTy = dyn_cast<VectorType>(C->getType());
630*0b57cec5SDimitry Andric       Type *ElemTy = VTy->getElementType();
631*0b57cec5SDimitry Andric       unsigned int elemNum = VTy->getNumElements();
632*0b57cec5SDimitry Andric       Result.AggregateVal.resize(elemNum);
633*0b57cec5SDimitry Andric       if (ElemTy->isIntegerTy())
634*0b57cec5SDimitry Andric         for (unsigned int i = 0; i < elemNum; ++i)
635*0b57cec5SDimitry Andric           Result.AggregateVal[i].IntVal =
636*0b57cec5SDimitry Andric             APInt(ElemTy->getPrimitiveSizeInBits(), 0);
637*0b57cec5SDimitry Andric       break;
638*0b57cec5SDimitry Andric     }
639*0b57cec5SDimitry Andric     return Result;
640*0b57cec5SDimitry Andric   }
641*0b57cec5SDimitry Andric 
642*0b57cec5SDimitry Andric   // Otherwise, if the value is a ConstantExpr...
643*0b57cec5SDimitry Andric   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
644*0b57cec5SDimitry Andric     Constant *Op0 = CE->getOperand(0);
645*0b57cec5SDimitry Andric     switch (CE->getOpcode()) {
646*0b57cec5SDimitry Andric     case Instruction::GetElementPtr: {
647*0b57cec5SDimitry Andric       // Compute the index
648*0b57cec5SDimitry Andric       GenericValue Result = getConstantValue(Op0);
649*0b57cec5SDimitry Andric       APInt Offset(DL.getPointerSizeInBits(), 0);
650*0b57cec5SDimitry Andric       cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
651*0b57cec5SDimitry Andric 
652*0b57cec5SDimitry Andric       char* tmp = (char*) Result.PointerVal;
653*0b57cec5SDimitry Andric       Result = PTOGV(tmp + Offset.getSExtValue());
654*0b57cec5SDimitry Andric       return Result;
655*0b57cec5SDimitry Andric     }
656*0b57cec5SDimitry Andric     case Instruction::Trunc: {
657*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
658*0b57cec5SDimitry Andric       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
659*0b57cec5SDimitry Andric       GV.IntVal = GV.IntVal.trunc(BitWidth);
660*0b57cec5SDimitry Andric       return GV;
661*0b57cec5SDimitry Andric     }
662*0b57cec5SDimitry Andric     case Instruction::ZExt: {
663*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
664*0b57cec5SDimitry Andric       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
665*0b57cec5SDimitry Andric       GV.IntVal = GV.IntVal.zext(BitWidth);
666*0b57cec5SDimitry Andric       return GV;
667*0b57cec5SDimitry Andric     }
668*0b57cec5SDimitry Andric     case Instruction::SExt: {
669*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
670*0b57cec5SDimitry Andric       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
671*0b57cec5SDimitry Andric       GV.IntVal = GV.IntVal.sext(BitWidth);
672*0b57cec5SDimitry Andric       return GV;
673*0b57cec5SDimitry Andric     }
674*0b57cec5SDimitry Andric     case Instruction::FPTrunc: {
675*0b57cec5SDimitry Andric       // FIXME long double
676*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
677*0b57cec5SDimitry Andric       GV.FloatVal = float(GV.DoubleVal);
678*0b57cec5SDimitry Andric       return GV;
679*0b57cec5SDimitry Andric     }
680*0b57cec5SDimitry Andric     case Instruction::FPExt:{
681*0b57cec5SDimitry Andric       // FIXME long double
682*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
683*0b57cec5SDimitry Andric       GV.DoubleVal = double(GV.FloatVal);
684*0b57cec5SDimitry Andric       return GV;
685*0b57cec5SDimitry Andric     }
686*0b57cec5SDimitry Andric     case Instruction::UIToFP: {
687*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
688*0b57cec5SDimitry Andric       if (CE->getType()->isFloatTy())
689*0b57cec5SDimitry Andric         GV.FloatVal = float(GV.IntVal.roundToDouble());
690*0b57cec5SDimitry Andric       else if (CE->getType()->isDoubleTy())
691*0b57cec5SDimitry Andric         GV.DoubleVal = GV.IntVal.roundToDouble();
692*0b57cec5SDimitry Andric       else if (CE->getType()->isX86_FP80Ty()) {
693*0b57cec5SDimitry Andric         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
694*0b57cec5SDimitry Andric         (void)apf.convertFromAPInt(GV.IntVal,
695*0b57cec5SDimitry Andric                                    false,
696*0b57cec5SDimitry Andric                                    APFloat::rmNearestTiesToEven);
697*0b57cec5SDimitry Andric         GV.IntVal = apf.bitcastToAPInt();
698*0b57cec5SDimitry Andric       }
699*0b57cec5SDimitry Andric       return GV;
700*0b57cec5SDimitry Andric     }
701*0b57cec5SDimitry Andric     case Instruction::SIToFP: {
702*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
703*0b57cec5SDimitry Andric       if (CE->getType()->isFloatTy())
704*0b57cec5SDimitry Andric         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
705*0b57cec5SDimitry Andric       else if (CE->getType()->isDoubleTy())
706*0b57cec5SDimitry Andric         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
707*0b57cec5SDimitry Andric       else if (CE->getType()->isX86_FP80Ty()) {
708*0b57cec5SDimitry Andric         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended());
709*0b57cec5SDimitry Andric         (void)apf.convertFromAPInt(GV.IntVal,
710*0b57cec5SDimitry Andric                                    true,
711*0b57cec5SDimitry Andric                                    APFloat::rmNearestTiesToEven);
712*0b57cec5SDimitry Andric         GV.IntVal = apf.bitcastToAPInt();
713*0b57cec5SDimitry Andric       }
714*0b57cec5SDimitry Andric       return GV;
715*0b57cec5SDimitry Andric     }
716*0b57cec5SDimitry Andric     case Instruction::FPToUI: // double->APInt conversion handles sign
717*0b57cec5SDimitry Andric     case Instruction::FPToSI: {
718*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
719*0b57cec5SDimitry Andric       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
720*0b57cec5SDimitry Andric       if (Op0->getType()->isFloatTy())
721*0b57cec5SDimitry Andric         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
722*0b57cec5SDimitry Andric       else if (Op0->getType()->isDoubleTy())
723*0b57cec5SDimitry Andric         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
724*0b57cec5SDimitry Andric       else if (Op0->getType()->isX86_FP80Ty()) {
725*0b57cec5SDimitry Andric         APFloat apf = APFloat(APFloat::x87DoubleExtended(), GV.IntVal);
726*0b57cec5SDimitry Andric         uint64_t v;
727*0b57cec5SDimitry Andric         bool ignored;
728*0b57cec5SDimitry Andric         (void)apf.convertToInteger(makeMutableArrayRef(v), BitWidth,
729*0b57cec5SDimitry Andric                                    CE->getOpcode()==Instruction::FPToSI,
730*0b57cec5SDimitry Andric                                    APFloat::rmTowardZero, &ignored);
731*0b57cec5SDimitry Andric         GV.IntVal = v; // endian?
732*0b57cec5SDimitry Andric       }
733*0b57cec5SDimitry Andric       return GV;
734*0b57cec5SDimitry Andric     }
735*0b57cec5SDimitry Andric     case Instruction::PtrToInt: {
736*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
737*0b57cec5SDimitry Andric       uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
738*0b57cec5SDimitry Andric       assert(PtrWidth <= 64 && "Bad pointer width");
739*0b57cec5SDimitry Andric       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
740*0b57cec5SDimitry Andric       uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
741*0b57cec5SDimitry Andric       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
742*0b57cec5SDimitry Andric       return GV;
743*0b57cec5SDimitry Andric     }
744*0b57cec5SDimitry Andric     case Instruction::IntToPtr: {
745*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
746*0b57cec5SDimitry Andric       uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
747*0b57cec5SDimitry Andric       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
748*0b57cec5SDimitry Andric       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
749*0b57cec5SDimitry Andric       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
750*0b57cec5SDimitry Andric       return GV;
751*0b57cec5SDimitry Andric     }
752*0b57cec5SDimitry Andric     case Instruction::BitCast: {
753*0b57cec5SDimitry Andric       GenericValue GV = getConstantValue(Op0);
754*0b57cec5SDimitry Andric       Type* DestTy = CE->getType();
755*0b57cec5SDimitry Andric       switch (Op0->getType()->getTypeID()) {
756*0b57cec5SDimitry Andric         default: llvm_unreachable("Invalid bitcast operand");
757*0b57cec5SDimitry Andric         case Type::IntegerTyID:
758*0b57cec5SDimitry Andric           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
759*0b57cec5SDimitry Andric           if (DestTy->isFloatTy())
760*0b57cec5SDimitry Andric             GV.FloatVal = GV.IntVal.bitsToFloat();
761*0b57cec5SDimitry Andric           else if (DestTy->isDoubleTy())
762*0b57cec5SDimitry Andric             GV.DoubleVal = GV.IntVal.bitsToDouble();
763*0b57cec5SDimitry Andric           break;
764*0b57cec5SDimitry Andric         case Type::FloatTyID:
765*0b57cec5SDimitry Andric           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
766*0b57cec5SDimitry Andric           GV.IntVal = APInt::floatToBits(GV.FloatVal);
767*0b57cec5SDimitry Andric           break;
768*0b57cec5SDimitry Andric         case Type::DoubleTyID:
769*0b57cec5SDimitry Andric           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
770*0b57cec5SDimitry Andric           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
771*0b57cec5SDimitry Andric           break;
772*0b57cec5SDimitry Andric         case Type::PointerTyID:
773*0b57cec5SDimitry Andric           assert(DestTy->isPointerTy() && "Invalid bitcast");
774*0b57cec5SDimitry Andric           break; // getConstantValue(Op0)  above already converted it
775*0b57cec5SDimitry Andric       }
776*0b57cec5SDimitry Andric       return GV;
777*0b57cec5SDimitry Andric     }
778*0b57cec5SDimitry Andric     case Instruction::Add:
779*0b57cec5SDimitry Andric     case Instruction::FAdd:
780*0b57cec5SDimitry Andric     case Instruction::Sub:
781*0b57cec5SDimitry Andric     case Instruction::FSub:
782*0b57cec5SDimitry Andric     case Instruction::Mul:
783*0b57cec5SDimitry Andric     case Instruction::FMul:
784*0b57cec5SDimitry Andric     case Instruction::UDiv:
785*0b57cec5SDimitry Andric     case Instruction::SDiv:
786*0b57cec5SDimitry Andric     case Instruction::URem:
787*0b57cec5SDimitry Andric     case Instruction::SRem:
788*0b57cec5SDimitry Andric     case Instruction::And:
789*0b57cec5SDimitry Andric     case Instruction::Or:
790*0b57cec5SDimitry Andric     case Instruction::Xor: {
791*0b57cec5SDimitry Andric       GenericValue LHS = getConstantValue(Op0);
792*0b57cec5SDimitry Andric       GenericValue RHS = getConstantValue(CE->getOperand(1));
793*0b57cec5SDimitry Andric       GenericValue GV;
794*0b57cec5SDimitry Andric       switch (CE->getOperand(0)->getType()->getTypeID()) {
795*0b57cec5SDimitry Andric       default: llvm_unreachable("Bad add type!");
796*0b57cec5SDimitry Andric       case Type::IntegerTyID:
797*0b57cec5SDimitry Andric         switch (CE->getOpcode()) {
798*0b57cec5SDimitry Andric           default: llvm_unreachable("Invalid integer opcode");
799*0b57cec5SDimitry Andric           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
800*0b57cec5SDimitry Andric           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
801*0b57cec5SDimitry Andric           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
802*0b57cec5SDimitry Andric           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
803*0b57cec5SDimitry Andric           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
804*0b57cec5SDimitry Andric           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
805*0b57cec5SDimitry Andric           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
806*0b57cec5SDimitry Andric           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
807*0b57cec5SDimitry Andric           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
808*0b57cec5SDimitry Andric           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
809*0b57cec5SDimitry Andric         }
810*0b57cec5SDimitry Andric         break;
811*0b57cec5SDimitry Andric       case Type::FloatTyID:
812*0b57cec5SDimitry Andric         switch (CE->getOpcode()) {
813*0b57cec5SDimitry Andric           default: llvm_unreachable("Invalid float opcode");
814*0b57cec5SDimitry Andric           case Instruction::FAdd:
815*0b57cec5SDimitry Andric             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
816*0b57cec5SDimitry Andric           case Instruction::FSub:
817*0b57cec5SDimitry Andric             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
818*0b57cec5SDimitry Andric           case Instruction::FMul:
819*0b57cec5SDimitry Andric             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
820*0b57cec5SDimitry Andric           case Instruction::FDiv:
821*0b57cec5SDimitry Andric             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
822*0b57cec5SDimitry Andric           case Instruction::FRem:
823*0b57cec5SDimitry Andric             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
824*0b57cec5SDimitry Andric         }
825*0b57cec5SDimitry Andric         break;
826*0b57cec5SDimitry Andric       case Type::DoubleTyID:
827*0b57cec5SDimitry Andric         switch (CE->getOpcode()) {
828*0b57cec5SDimitry Andric           default: llvm_unreachable("Invalid double opcode");
829*0b57cec5SDimitry Andric           case Instruction::FAdd:
830*0b57cec5SDimitry Andric             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
831*0b57cec5SDimitry Andric           case Instruction::FSub:
832*0b57cec5SDimitry Andric             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
833*0b57cec5SDimitry Andric           case Instruction::FMul:
834*0b57cec5SDimitry Andric             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
835*0b57cec5SDimitry Andric           case Instruction::FDiv:
836*0b57cec5SDimitry Andric             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
837*0b57cec5SDimitry Andric           case Instruction::FRem:
838*0b57cec5SDimitry Andric             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
839*0b57cec5SDimitry Andric         }
840*0b57cec5SDimitry Andric         break;
841*0b57cec5SDimitry Andric       case Type::X86_FP80TyID:
842*0b57cec5SDimitry Andric       case Type::PPC_FP128TyID:
843*0b57cec5SDimitry Andric       case Type::FP128TyID: {
844*0b57cec5SDimitry Andric         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
845*0b57cec5SDimitry Andric         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
846*0b57cec5SDimitry Andric         switch (CE->getOpcode()) {
847*0b57cec5SDimitry Andric           default: llvm_unreachable("Invalid long double opcode");
848*0b57cec5SDimitry Andric           case Instruction::FAdd:
849*0b57cec5SDimitry Andric             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
850*0b57cec5SDimitry Andric             GV.IntVal = apfLHS.bitcastToAPInt();
851*0b57cec5SDimitry Andric             break;
852*0b57cec5SDimitry Andric           case Instruction::FSub:
853*0b57cec5SDimitry Andric             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
854*0b57cec5SDimitry Andric                             APFloat::rmNearestTiesToEven);
855*0b57cec5SDimitry Andric             GV.IntVal = apfLHS.bitcastToAPInt();
856*0b57cec5SDimitry Andric             break;
857*0b57cec5SDimitry Andric           case Instruction::FMul:
858*0b57cec5SDimitry Andric             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
859*0b57cec5SDimitry Andric                             APFloat::rmNearestTiesToEven);
860*0b57cec5SDimitry Andric             GV.IntVal = apfLHS.bitcastToAPInt();
861*0b57cec5SDimitry Andric             break;
862*0b57cec5SDimitry Andric           case Instruction::FDiv:
863*0b57cec5SDimitry Andric             apfLHS.divide(APFloat(Sem, RHS.IntVal),
864*0b57cec5SDimitry Andric                           APFloat::rmNearestTiesToEven);
865*0b57cec5SDimitry Andric             GV.IntVal = apfLHS.bitcastToAPInt();
866*0b57cec5SDimitry Andric             break;
867*0b57cec5SDimitry Andric           case Instruction::FRem:
868*0b57cec5SDimitry Andric             apfLHS.mod(APFloat(Sem, RHS.IntVal));
869*0b57cec5SDimitry Andric             GV.IntVal = apfLHS.bitcastToAPInt();
870*0b57cec5SDimitry Andric             break;
871*0b57cec5SDimitry Andric           }
872*0b57cec5SDimitry Andric         }
873*0b57cec5SDimitry Andric         break;
874*0b57cec5SDimitry Andric       }
875*0b57cec5SDimitry Andric       return GV;
876*0b57cec5SDimitry Andric     }
877*0b57cec5SDimitry Andric     default:
878*0b57cec5SDimitry Andric       break;
879*0b57cec5SDimitry Andric     }
880*0b57cec5SDimitry Andric 
881*0b57cec5SDimitry Andric     SmallString<256> Msg;
882*0b57cec5SDimitry Andric     raw_svector_ostream OS(Msg);
883*0b57cec5SDimitry Andric     OS << "ConstantExpr not handled: " << *CE;
884*0b57cec5SDimitry Andric     report_fatal_error(OS.str());
885*0b57cec5SDimitry Andric   }
886*0b57cec5SDimitry Andric 
887*0b57cec5SDimitry Andric   // Otherwise, we have a simple constant.
888*0b57cec5SDimitry Andric   GenericValue Result;
889*0b57cec5SDimitry Andric   switch (C->getType()->getTypeID()) {
890*0b57cec5SDimitry Andric   case Type::FloatTyID:
891*0b57cec5SDimitry Andric     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
892*0b57cec5SDimitry Andric     break;
893*0b57cec5SDimitry Andric   case Type::DoubleTyID:
894*0b57cec5SDimitry Andric     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
895*0b57cec5SDimitry Andric     break;
896*0b57cec5SDimitry Andric   case Type::X86_FP80TyID:
897*0b57cec5SDimitry Andric   case Type::FP128TyID:
898*0b57cec5SDimitry Andric   case Type::PPC_FP128TyID:
899*0b57cec5SDimitry Andric     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
900*0b57cec5SDimitry Andric     break;
901*0b57cec5SDimitry Andric   case Type::IntegerTyID:
902*0b57cec5SDimitry Andric     Result.IntVal = cast<ConstantInt>(C)->getValue();
903*0b57cec5SDimitry Andric     break;
904*0b57cec5SDimitry Andric   case Type::PointerTyID:
905*0b57cec5SDimitry Andric     while (auto *A = dyn_cast<GlobalAlias>(C)) {
906*0b57cec5SDimitry Andric       C = A->getAliasee();
907*0b57cec5SDimitry Andric     }
908*0b57cec5SDimitry Andric     if (isa<ConstantPointerNull>(C))
909*0b57cec5SDimitry Andric       Result.PointerVal = nullptr;
910*0b57cec5SDimitry Andric     else if (const Function *F = dyn_cast<Function>(C))
911*0b57cec5SDimitry Andric       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
912*0b57cec5SDimitry Andric     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
913*0b57cec5SDimitry Andric       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
914*0b57cec5SDimitry Andric     else
915*0b57cec5SDimitry Andric       llvm_unreachable("Unknown constant pointer type!");
916*0b57cec5SDimitry Andric     break;
917*0b57cec5SDimitry Andric   case Type::VectorTyID: {
918*0b57cec5SDimitry Andric     unsigned elemNum;
919*0b57cec5SDimitry Andric     Type* ElemTy;
920*0b57cec5SDimitry Andric     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
921*0b57cec5SDimitry Andric     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
922*0b57cec5SDimitry Andric     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
923*0b57cec5SDimitry Andric 
924*0b57cec5SDimitry Andric     if (CDV) {
925*0b57cec5SDimitry Andric         elemNum = CDV->getNumElements();
926*0b57cec5SDimitry Andric         ElemTy = CDV->getElementType();
927*0b57cec5SDimitry Andric     } else if (CV || CAZ) {
928*0b57cec5SDimitry Andric         VectorType* VTy = dyn_cast<VectorType>(C->getType());
929*0b57cec5SDimitry Andric         elemNum = VTy->getNumElements();
930*0b57cec5SDimitry Andric         ElemTy = VTy->getElementType();
931*0b57cec5SDimitry Andric     } else {
932*0b57cec5SDimitry Andric         llvm_unreachable("Unknown constant vector type!");
933*0b57cec5SDimitry Andric     }
934*0b57cec5SDimitry Andric 
935*0b57cec5SDimitry Andric     Result.AggregateVal.resize(elemNum);
936*0b57cec5SDimitry Andric     // Check if vector holds floats.
937*0b57cec5SDimitry Andric     if(ElemTy->isFloatTy()) {
938*0b57cec5SDimitry Andric       if (CAZ) {
939*0b57cec5SDimitry Andric         GenericValue floatZero;
940*0b57cec5SDimitry Andric         floatZero.FloatVal = 0.f;
941*0b57cec5SDimitry Andric         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
942*0b57cec5SDimitry Andric                   floatZero);
943*0b57cec5SDimitry Andric         break;
944*0b57cec5SDimitry Andric       }
945*0b57cec5SDimitry Andric       if(CV) {
946*0b57cec5SDimitry Andric         for (unsigned i = 0; i < elemNum; ++i)
947*0b57cec5SDimitry Andric           if (!isa<UndefValue>(CV->getOperand(i)))
948*0b57cec5SDimitry Andric             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
949*0b57cec5SDimitry Andric               CV->getOperand(i))->getValueAPF().convertToFloat();
950*0b57cec5SDimitry Andric         break;
951*0b57cec5SDimitry Andric       }
952*0b57cec5SDimitry Andric       if(CDV)
953*0b57cec5SDimitry Andric         for (unsigned i = 0; i < elemNum; ++i)
954*0b57cec5SDimitry Andric           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
955*0b57cec5SDimitry Andric 
956*0b57cec5SDimitry Andric       break;
957*0b57cec5SDimitry Andric     }
958*0b57cec5SDimitry Andric     // Check if vector holds doubles.
959*0b57cec5SDimitry Andric     if (ElemTy->isDoubleTy()) {
960*0b57cec5SDimitry Andric       if (CAZ) {
961*0b57cec5SDimitry Andric         GenericValue doubleZero;
962*0b57cec5SDimitry Andric         doubleZero.DoubleVal = 0.0;
963*0b57cec5SDimitry Andric         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
964*0b57cec5SDimitry Andric                   doubleZero);
965*0b57cec5SDimitry Andric         break;
966*0b57cec5SDimitry Andric       }
967*0b57cec5SDimitry Andric       if(CV) {
968*0b57cec5SDimitry Andric         for (unsigned i = 0; i < elemNum; ++i)
969*0b57cec5SDimitry Andric           if (!isa<UndefValue>(CV->getOperand(i)))
970*0b57cec5SDimitry Andric             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
971*0b57cec5SDimitry Andric               CV->getOperand(i))->getValueAPF().convertToDouble();
972*0b57cec5SDimitry Andric         break;
973*0b57cec5SDimitry Andric       }
974*0b57cec5SDimitry Andric       if(CDV)
975*0b57cec5SDimitry Andric         for (unsigned i = 0; i < elemNum; ++i)
976*0b57cec5SDimitry Andric           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
977*0b57cec5SDimitry Andric 
978*0b57cec5SDimitry Andric       break;
979*0b57cec5SDimitry Andric     }
980*0b57cec5SDimitry Andric     // Check if vector holds integers.
981*0b57cec5SDimitry Andric     if (ElemTy->isIntegerTy()) {
982*0b57cec5SDimitry Andric       if (CAZ) {
983*0b57cec5SDimitry Andric         GenericValue intZero;
984*0b57cec5SDimitry Andric         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
985*0b57cec5SDimitry Andric         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
986*0b57cec5SDimitry Andric                   intZero);
987*0b57cec5SDimitry Andric         break;
988*0b57cec5SDimitry Andric       }
989*0b57cec5SDimitry Andric       if(CV) {
990*0b57cec5SDimitry Andric         for (unsigned i = 0; i < elemNum; ++i)
991*0b57cec5SDimitry Andric           if (!isa<UndefValue>(CV->getOperand(i)))
992*0b57cec5SDimitry Andric             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
993*0b57cec5SDimitry Andric                                             CV->getOperand(i))->getValue();
994*0b57cec5SDimitry Andric           else {
995*0b57cec5SDimitry Andric             Result.AggregateVal[i].IntVal =
996*0b57cec5SDimitry Andric               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
997*0b57cec5SDimitry Andric           }
998*0b57cec5SDimitry Andric         break;
999*0b57cec5SDimitry Andric       }
1000*0b57cec5SDimitry Andric       if(CDV)
1001*0b57cec5SDimitry Andric         for (unsigned i = 0; i < elemNum; ++i)
1002*0b57cec5SDimitry Andric           Result.AggregateVal[i].IntVal = APInt(
1003*0b57cec5SDimitry Andric             CDV->getElementType()->getPrimitiveSizeInBits(),
1004*0b57cec5SDimitry Andric             CDV->getElementAsInteger(i));
1005*0b57cec5SDimitry Andric 
1006*0b57cec5SDimitry Andric       break;
1007*0b57cec5SDimitry Andric     }
1008*0b57cec5SDimitry Andric     llvm_unreachable("Unknown constant pointer type!");
1009*0b57cec5SDimitry Andric   }
1010*0b57cec5SDimitry Andric   break;
1011*0b57cec5SDimitry Andric 
1012*0b57cec5SDimitry Andric   default:
1013*0b57cec5SDimitry Andric     SmallString<256> Msg;
1014*0b57cec5SDimitry Andric     raw_svector_ostream OS(Msg);
1015*0b57cec5SDimitry Andric     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1016*0b57cec5SDimitry Andric     report_fatal_error(OS.str());
1017*0b57cec5SDimitry Andric   }
1018*0b57cec5SDimitry Andric 
1019*0b57cec5SDimitry Andric   return Result;
1020*0b57cec5SDimitry Andric }
1021*0b57cec5SDimitry Andric 
1022*0b57cec5SDimitry Andric void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1023*0b57cec5SDimitry Andric                                          GenericValue *Ptr, Type *Ty) {
1024*0b57cec5SDimitry Andric   const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
1025*0b57cec5SDimitry Andric 
1026*0b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
1027*0b57cec5SDimitry Andric   default:
1028*0b57cec5SDimitry Andric     dbgs() << "Cannot store value of type " << *Ty << "!\n";
1029*0b57cec5SDimitry Andric     break;
1030*0b57cec5SDimitry Andric   case Type::IntegerTyID:
1031*0b57cec5SDimitry Andric     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1032*0b57cec5SDimitry Andric     break;
1033*0b57cec5SDimitry Andric   case Type::FloatTyID:
1034*0b57cec5SDimitry Andric     *((float*)Ptr) = Val.FloatVal;
1035*0b57cec5SDimitry Andric     break;
1036*0b57cec5SDimitry Andric   case Type::DoubleTyID:
1037*0b57cec5SDimitry Andric     *((double*)Ptr) = Val.DoubleVal;
1038*0b57cec5SDimitry Andric     break;
1039*0b57cec5SDimitry Andric   case Type::X86_FP80TyID:
1040*0b57cec5SDimitry Andric     memcpy(Ptr, Val.IntVal.getRawData(), 10);
1041*0b57cec5SDimitry Andric     break;
1042*0b57cec5SDimitry Andric   case Type::PointerTyID:
1043*0b57cec5SDimitry Andric     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1044*0b57cec5SDimitry Andric     if (StoreBytes != sizeof(PointerTy))
1045*0b57cec5SDimitry Andric       memset(&(Ptr->PointerVal), 0, StoreBytes);
1046*0b57cec5SDimitry Andric 
1047*0b57cec5SDimitry Andric     *((PointerTy*)Ptr) = Val.PointerVal;
1048*0b57cec5SDimitry Andric     break;
1049*0b57cec5SDimitry Andric   case Type::VectorTyID:
1050*0b57cec5SDimitry Andric     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1051*0b57cec5SDimitry Andric       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1052*0b57cec5SDimitry Andric         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1053*0b57cec5SDimitry Andric       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1054*0b57cec5SDimitry Andric         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1055*0b57cec5SDimitry Andric       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1056*0b57cec5SDimitry Andric         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1057*0b57cec5SDimitry Andric         StoreIntToMemory(Val.AggregateVal[i].IntVal,
1058*0b57cec5SDimitry Andric           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1059*0b57cec5SDimitry Andric       }
1060*0b57cec5SDimitry Andric     }
1061*0b57cec5SDimitry Andric     break;
1062*0b57cec5SDimitry Andric   }
1063*0b57cec5SDimitry Andric 
1064*0b57cec5SDimitry Andric   if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
1065*0b57cec5SDimitry Andric     // Host and target are different endian - reverse the stored bytes.
1066*0b57cec5SDimitry Andric     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1067*0b57cec5SDimitry Andric }
1068*0b57cec5SDimitry Andric 
1069*0b57cec5SDimitry Andric /// FIXME: document
1070*0b57cec5SDimitry Andric ///
1071*0b57cec5SDimitry Andric void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1072*0b57cec5SDimitry Andric                                           GenericValue *Ptr,
1073*0b57cec5SDimitry Andric                                           Type *Ty) {
1074*0b57cec5SDimitry Andric   const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
1075*0b57cec5SDimitry Andric 
1076*0b57cec5SDimitry Andric   switch (Ty->getTypeID()) {
1077*0b57cec5SDimitry Andric   case Type::IntegerTyID:
1078*0b57cec5SDimitry Andric     // An APInt with all words initially zero.
1079*0b57cec5SDimitry Andric     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1080*0b57cec5SDimitry Andric     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1081*0b57cec5SDimitry Andric     break;
1082*0b57cec5SDimitry Andric   case Type::FloatTyID:
1083*0b57cec5SDimitry Andric     Result.FloatVal = *((float*)Ptr);
1084*0b57cec5SDimitry Andric     break;
1085*0b57cec5SDimitry Andric   case Type::DoubleTyID:
1086*0b57cec5SDimitry Andric     Result.DoubleVal = *((double*)Ptr);
1087*0b57cec5SDimitry Andric     break;
1088*0b57cec5SDimitry Andric   case Type::PointerTyID:
1089*0b57cec5SDimitry Andric     Result.PointerVal = *((PointerTy*)Ptr);
1090*0b57cec5SDimitry Andric     break;
1091*0b57cec5SDimitry Andric   case Type::X86_FP80TyID: {
1092*0b57cec5SDimitry Andric     // This is endian dependent, but it will only work on x86 anyway.
1093*0b57cec5SDimitry Andric     // FIXME: Will not trap if loading a signaling NaN.
1094*0b57cec5SDimitry Andric     uint64_t y[2];
1095*0b57cec5SDimitry Andric     memcpy(y, Ptr, 10);
1096*0b57cec5SDimitry Andric     Result.IntVal = APInt(80, y);
1097*0b57cec5SDimitry Andric     break;
1098*0b57cec5SDimitry Andric   }
1099*0b57cec5SDimitry Andric   case Type::VectorTyID: {
1100*0b57cec5SDimitry Andric     auto *VT = cast<VectorType>(Ty);
1101*0b57cec5SDimitry Andric     Type *ElemT = VT->getElementType();
1102*0b57cec5SDimitry Andric     const unsigned numElems = VT->getNumElements();
1103*0b57cec5SDimitry Andric     if (ElemT->isFloatTy()) {
1104*0b57cec5SDimitry Andric       Result.AggregateVal.resize(numElems);
1105*0b57cec5SDimitry Andric       for (unsigned i = 0; i < numElems; ++i)
1106*0b57cec5SDimitry Andric         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1107*0b57cec5SDimitry Andric     }
1108*0b57cec5SDimitry Andric     if (ElemT->isDoubleTy()) {
1109*0b57cec5SDimitry Andric       Result.AggregateVal.resize(numElems);
1110*0b57cec5SDimitry Andric       for (unsigned i = 0; i < numElems; ++i)
1111*0b57cec5SDimitry Andric         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1112*0b57cec5SDimitry Andric     }
1113*0b57cec5SDimitry Andric     if (ElemT->isIntegerTy()) {
1114*0b57cec5SDimitry Andric       GenericValue intZero;
1115*0b57cec5SDimitry Andric       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1116*0b57cec5SDimitry Andric       intZero.IntVal = APInt(elemBitWidth, 0);
1117*0b57cec5SDimitry Andric       Result.AggregateVal.resize(numElems, intZero);
1118*0b57cec5SDimitry Andric       for (unsigned i = 0; i < numElems; ++i)
1119*0b57cec5SDimitry Andric         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1120*0b57cec5SDimitry Andric           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1121*0b57cec5SDimitry Andric     }
1122*0b57cec5SDimitry Andric   break;
1123*0b57cec5SDimitry Andric   }
1124*0b57cec5SDimitry Andric   default:
1125*0b57cec5SDimitry Andric     SmallString<256> Msg;
1126*0b57cec5SDimitry Andric     raw_svector_ostream OS(Msg);
1127*0b57cec5SDimitry Andric     OS << "Cannot load value of type " << *Ty << "!";
1128*0b57cec5SDimitry Andric     report_fatal_error(OS.str());
1129*0b57cec5SDimitry Andric   }
1130*0b57cec5SDimitry Andric }
1131*0b57cec5SDimitry Andric 
1132*0b57cec5SDimitry Andric void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1133*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1134*0b57cec5SDimitry Andric   LLVM_DEBUG(Init->dump());
1135*0b57cec5SDimitry Andric   if (isa<UndefValue>(Init))
1136*0b57cec5SDimitry Andric     return;
1137*0b57cec5SDimitry Andric 
1138*0b57cec5SDimitry Andric   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1139*0b57cec5SDimitry Andric     unsigned ElementSize =
1140*0b57cec5SDimitry Andric         getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
1141*0b57cec5SDimitry Andric     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1142*0b57cec5SDimitry Andric       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1143*0b57cec5SDimitry Andric     return;
1144*0b57cec5SDimitry Andric   }
1145*0b57cec5SDimitry Andric 
1146*0b57cec5SDimitry Andric   if (isa<ConstantAggregateZero>(Init)) {
1147*0b57cec5SDimitry Andric     memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
1148*0b57cec5SDimitry Andric     return;
1149*0b57cec5SDimitry Andric   }
1150*0b57cec5SDimitry Andric 
1151*0b57cec5SDimitry Andric   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1152*0b57cec5SDimitry Andric     unsigned ElementSize =
1153*0b57cec5SDimitry Andric         getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
1154*0b57cec5SDimitry Andric     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1155*0b57cec5SDimitry Andric       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1156*0b57cec5SDimitry Andric     return;
1157*0b57cec5SDimitry Andric   }
1158*0b57cec5SDimitry Andric 
1159*0b57cec5SDimitry Andric   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1160*0b57cec5SDimitry Andric     const StructLayout *SL =
1161*0b57cec5SDimitry Andric         getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
1162*0b57cec5SDimitry Andric     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1163*0b57cec5SDimitry Andric       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1164*0b57cec5SDimitry Andric     return;
1165*0b57cec5SDimitry Andric   }
1166*0b57cec5SDimitry Andric 
1167*0b57cec5SDimitry Andric   if (const ConstantDataSequential *CDS =
1168*0b57cec5SDimitry Andric                dyn_cast<ConstantDataSequential>(Init)) {
1169*0b57cec5SDimitry Andric     // CDS is already laid out in host memory order.
1170*0b57cec5SDimitry Andric     StringRef Data = CDS->getRawDataValues();
1171*0b57cec5SDimitry Andric     memcpy(Addr, Data.data(), Data.size());
1172*0b57cec5SDimitry Andric     return;
1173*0b57cec5SDimitry Andric   }
1174*0b57cec5SDimitry Andric 
1175*0b57cec5SDimitry Andric   if (Init->getType()->isFirstClassType()) {
1176*0b57cec5SDimitry Andric     GenericValue Val = getConstantValue(Init);
1177*0b57cec5SDimitry Andric     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1178*0b57cec5SDimitry Andric     return;
1179*0b57cec5SDimitry Andric   }
1180*0b57cec5SDimitry Andric 
1181*0b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1182*0b57cec5SDimitry Andric   llvm_unreachable("Unknown constant type to initialize memory with!");
1183*0b57cec5SDimitry Andric }
1184*0b57cec5SDimitry Andric 
1185*0b57cec5SDimitry Andric /// EmitGlobals - Emit all of the global variables to memory, storing their
1186*0b57cec5SDimitry Andric /// addresses into GlobalAddress.  This must make sure to copy the contents of
1187*0b57cec5SDimitry Andric /// their initializers into the memory.
1188*0b57cec5SDimitry Andric void ExecutionEngine::emitGlobals() {
1189*0b57cec5SDimitry Andric   // Loop over all of the global variables in the program, allocating the memory
1190*0b57cec5SDimitry Andric   // to hold them.  If there is more than one module, do a prepass over globals
1191*0b57cec5SDimitry Andric   // to figure out how the different modules should link together.
1192*0b57cec5SDimitry Andric   std::map<std::pair<std::string, Type*>,
1193*0b57cec5SDimitry Andric            const GlobalValue*> LinkedGlobalsMap;
1194*0b57cec5SDimitry Andric 
1195*0b57cec5SDimitry Andric   if (Modules.size() != 1) {
1196*0b57cec5SDimitry Andric     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1197*0b57cec5SDimitry Andric       Module &M = *Modules[m];
1198*0b57cec5SDimitry Andric       for (const auto &GV : M.globals()) {
1199*0b57cec5SDimitry Andric         if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1200*0b57cec5SDimitry Andric             GV.hasAppendingLinkage() || !GV.hasName())
1201*0b57cec5SDimitry Andric           continue;// Ignore external globals and globals with internal linkage.
1202*0b57cec5SDimitry Andric 
1203*0b57cec5SDimitry Andric         const GlobalValue *&GVEntry =
1204*0b57cec5SDimitry Andric           LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1205*0b57cec5SDimitry Andric 
1206*0b57cec5SDimitry Andric         // If this is the first time we've seen this global, it is the canonical
1207*0b57cec5SDimitry Andric         // version.
1208*0b57cec5SDimitry Andric         if (!GVEntry) {
1209*0b57cec5SDimitry Andric           GVEntry = &GV;
1210*0b57cec5SDimitry Andric           continue;
1211*0b57cec5SDimitry Andric         }
1212*0b57cec5SDimitry Andric 
1213*0b57cec5SDimitry Andric         // If the existing global is strong, never replace it.
1214*0b57cec5SDimitry Andric         if (GVEntry->hasExternalLinkage())
1215*0b57cec5SDimitry Andric           continue;
1216*0b57cec5SDimitry Andric 
1217*0b57cec5SDimitry Andric         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1218*0b57cec5SDimitry Andric         // symbol.  FIXME is this right for common?
1219*0b57cec5SDimitry Andric         if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1220*0b57cec5SDimitry Andric           GVEntry = &GV;
1221*0b57cec5SDimitry Andric       }
1222*0b57cec5SDimitry Andric     }
1223*0b57cec5SDimitry Andric   }
1224*0b57cec5SDimitry Andric 
1225*0b57cec5SDimitry Andric   std::vector<const GlobalValue*> NonCanonicalGlobals;
1226*0b57cec5SDimitry Andric   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1227*0b57cec5SDimitry Andric     Module &M = *Modules[m];
1228*0b57cec5SDimitry Andric     for (const auto &GV : M.globals()) {
1229*0b57cec5SDimitry Andric       // In the multi-module case, see what this global maps to.
1230*0b57cec5SDimitry Andric       if (!LinkedGlobalsMap.empty()) {
1231*0b57cec5SDimitry Andric         if (const GlobalValue *GVEntry =
1232*0b57cec5SDimitry Andric               LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1233*0b57cec5SDimitry Andric           // If something else is the canonical global, ignore this one.
1234*0b57cec5SDimitry Andric           if (GVEntry != &GV) {
1235*0b57cec5SDimitry Andric             NonCanonicalGlobals.push_back(&GV);
1236*0b57cec5SDimitry Andric             continue;
1237*0b57cec5SDimitry Andric           }
1238*0b57cec5SDimitry Andric         }
1239*0b57cec5SDimitry Andric       }
1240*0b57cec5SDimitry Andric 
1241*0b57cec5SDimitry Andric       if (!GV.isDeclaration()) {
1242*0b57cec5SDimitry Andric         addGlobalMapping(&GV, getMemoryForGV(&GV));
1243*0b57cec5SDimitry Andric       } else {
1244*0b57cec5SDimitry Andric         // External variable reference. Try to use the dynamic loader to
1245*0b57cec5SDimitry Andric         // get a pointer to it.
1246*0b57cec5SDimitry Andric         if (void *SymAddr =
1247*0b57cec5SDimitry Andric             sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1248*0b57cec5SDimitry Andric           addGlobalMapping(&GV, SymAddr);
1249*0b57cec5SDimitry Andric         else {
1250*0b57cec5SDimitry Andric           report_fatal_error("Could not resolve external global address: "
1251*0b57cec5SDimitry Andric                             +GV.getName());
1252*0b57cec5SDimitry Andric         }
1253*0b57cec5SDimitry Andric       }
1254*0b57cec5SDimitry Andric     }
1255*0b57cec5SDimitry Andric 
1256*0b57cec5SDimitry Andric     // If there are multiple modules, map the non-canonical globals to their
1257*0b57cec5SDimitry Andric     // canonical location.
1258*0b57cec5SDimitry Andric     if (!NonCanonicalGlobals.empty()) {
1259*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1260*0b57cec5SDimitry Andric         const GlobalValue *GV = NonCanonicalGlobals[i];
1261*0b57cec5SDimitry Andric         const GlobalValue *CGV =
1262*0b57cec5SDimitry Andric           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1263*0b57cec5SDimitry Andric         void *Ptr = getPointerToGlobalIfAvailable(CGV);
1264*0b57cec5SDimitry Andric         assert(Ptr && "Canonical global wasn't codegen'd!");
1265*0b57cec5SDimitry Andric         addGlobalMapping(GV, Ptr);
1266*0b57cec5SDimitry Andric       }
1267*0b57cec5SDimitry Andric     }
1268*0b57cec5SDimitry Andric 
1269*0b57cec5SDimitry Andric     // Now that all of the globals are set up in memory, loop through them all
1270*0b57cec5SDimitry Andric     // and initialize their contents.
1271*0b57cec5SDimitry Andric     for (const auto &GV : M.globals()) {
1272*0b57cec5SDimitry Andric       if (!GV.isDeclaration()) {
1273*0b57cec5SDimitry Andric         if (!LinkedGlobalsMap.empty()) {
1274*0b57cec5SDimitry Andric           if (const GlobalValue *GVEntry =
1275*0b57cec5SDimitry Andric                 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1276*0b57cec5SDimitry Andric             if (GVEntry != &GV)  // Not the canonical variable.
1277*0b57cec5SDimitry Andric               continue;
1278*0b57cec5SDimitry Andric         }
1279*0b57cec5SDimitry Andric         EmitGlobalVariable(&GV);
1280*0b57cec5SDimitry Andric       }
1281*0b57cec5SDimitry Andric     }
1282*0b57cec5SDimitry Andric   }
1283*0b57cec5SDimitry Andric }
1284*0b57cec5SDimitry Andric 
1285*0b57cec5SDimitry Andric // EmitGlobalVariable - This method emits the specified global variable to the
1286*0b57cec5SDimitry Andric // address specified in GlobalAddresses, or allocates new memory if it's not
1287*0b57cec5SDimitry Andric // already in the map.
1288*0b57cec5SDimitry Andric void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1289*0b57cec5SDimitry Andric   void *GA = getPointerToGlobalIfAvailable(GV);
1290*0b57cec5SDimitry Andric 
1291*0b57cec5SDimitry Andric   if (!GA) {
1292*0b57cec5SDimitry Andric     // If it's not already specified, allocate memory for the global.
1293*0b57cec5SDimitry Andric     GA = getMemoryForGV(GV);
1294*0b57cec5SDimitry Andric 
1295*0b57cec5SDimitry Andric     // If we failed to allocate memory for this global, return.
1296*0b57cec5SDimitry Andric     if (!GA) return;
1297*0b57cec5SDimitry Andric 
1298*0b57cec5SDimitry Andric     addGlobalMapping(GV, GA);
1299*0b57cec5SDimitry Andric   }
1300*0b57cec5SDimitry Andric 
1301*0b57cec5SDimitry Andric   // Don't initialize if it's thread local, let the client do it.
1302*0b57cec5SDimitry Andric   if (!GV->isThreadLocal())
1303*0b57cec5SDimitry Andric     InitializeMemory(GV->getInitializer(), GA);
1304*0b57cec5SDimitry Andric 
1305*0b57cec5SDimitry Andric   Type *ElTy = GV->getValueType();
1306*0b57cec5SDimitry Andric   size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
1307*0b57cec5SDimitry Andric   NumInitBytes += (unsigned)GVSize;
1308*0b57cec5SDimitry Andric   ++NumGlobals;
1309*0b57cec5SDimitry Andric }
1310