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