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