xref: /llvm-project/llvm/lib/ExecutionEngine/ExecutionEngine.cpp (revision 5f6eaac6115a44f4ef3d819123f8694d3d5825ea)
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     std::shared_ptr<RuntimeDyld::SymbolResolver> 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<RuntimeDyld::SymbolResolver> 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 ExecutionEngine::Init(std::unique_ptr<Module> M) {
65   CompilingLazily         = false;
66   GVCompilationDisabled   = false;
67   SymbolSearchingDisabled = false;
68 
69   // IR module verification is enabled by default in debug builds, and disabled
70   // by default in release builds.
71 #ifndef NDEBUG
72   VerifyModules = true;
73 #else
74   VerifyModules = false;
75 #endif
76 
77   assert(M && "Module is null?");
78   Modules.push_back(std::move(M));
79 }
80 
81 ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
82     : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
83   Init(std::move(M));
84 }
85 
86 ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
87     : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
88   Init(std::move(M));
89 }
90 
91 ExecutionEngine::~ExecutionEngine() {
92   clearAllGlobalMappings();
93 }
94 
95 namespace {
96 /// \brief Helper class which uses a value handler to automatically deletes the
97 /// memory block when the GlobalVariable is destroyed.
98 class GVMemoryBlock final : public CallbackVH {
99   GVMemoryBlock(const GlobalVariable *GV)
100     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
101 
102 public:
103   /// \brief Returns the address the GlobalVariable should be written into.  The
104   /// GVMemoryBlock object prefixes that.
105   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
106     Type *ElTy = GV->getValueType();
107     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
108     void *RawMemory = ::operator new(
109         alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
110     new(RawMemory) GVMemoryBlock(GV);
111     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
112   }
113 
114   void deleted() override {
115     // We allocated with operator new and with some extra memory hanging off the
116     // end, so don't just delete this.  I'm not sure if this is actually
117     // required.
118     this->~GVMemoryBlock();
119     ::operator delete(this);
120   }
121 };
122 }  // anonymous namespace
123 
124 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
125   return GVMemoryBlock::Create(GV, getDataLayout());
126 }
127 
128 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
129   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
130 }
131 
132 void
133 ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
134   llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
135 }
136 
137 void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
138   llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
139 }
140 
141 bool ExecutionEngine::removeModule(Module *M) {
142   for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
143     Module *Found = I->get();
144     if (Found == M) {
145       I->release();
146       Modules.erase(I);
147       clearGlobalMappingsFromModule(M);
148       return true;
149     }
150   }
151   return false;
152 }
153 
154 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
155   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
156     Function *F = Modules[i]->getFunction(FnName);
157     if (F && !F->isDeclaration())
158       return F;
159   }
160   return nullptr;
161 }
162 
163 GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
164   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
165     GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
166     if (GV && !GV->isDeclaration())
167       return GV;
168   }
169   return nullptr;
170 }
171 
172 uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
173   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
174   uint64_t OldVal;
175 
176   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
177   // GlobalAddressMap.
178   if (I == GlobalAddressMap.end())
179     OldVal = 0;
180   else {
181     GlobalAddressReverseMap.erase(I->second);
182     OldVal = I->second;
183     GlobalAddressMap.erase(I);
184   }
185 
186   return OldVal;
187 }
188 
189 std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
190   assert(GV->hasName() && "Global must have name.");
191 
192   MutexGuard locked(lock);
193   SmallString<128> FullName;
194 
195   const DataLayout &DL =
196     GV->getParent()->getDataLayout().isDefault()
197       ? getDataLayout()
198       : GV->getParent()->getDataLayout();
199 
200   Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
201   return FullName.str();
202 }
203 
204 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
205   MutexGuard locked(lock);
206   addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
207 }
208 
209 void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
210   MutexGuard locked(lock);
211 
212   assert(!Name.empty() && "Empty GlobalMapping symbol name!");
213 
214   DEBUG(dbgs() << "JIT: Map \'" << Name  << "\' to [" << Addr << "]\n";);
215   uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
216   assert((!CurVal || !Addr) && "GlobalMapping already established!");
217   CurVal = Addr;
218 
219   // If we are using the reverse mapping, add it too.
220   if (!EEState.getGlobalAddressReverseMap().empty()) {
221     std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
222     assert((!V.empty() || !Name.empty()) &&
223            "GlobalMapping already established!");
224     V = Name;
225   }
226 }
227 
228 void ExecutionEngine::clearAllGlobalMappings() {
229   MutexGuard locked(lock);
230 
231   EEState.getGlobalAddressMap().clear();
232   EEState.getGlobalAddressReverseMap().clear();
233 }
234 
235 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
236   MutexGuard locked(lock);
237 
238   for (Function &FI : *M)
239     EEState.RemoveMapping(getMangledName(&FI));
240   for (GlobalVariable &GI : M->globals())
241     EEState.RemoveMapping(getMangledName(&GI));
242 }
243 
244 uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
245                                               void *Addr) {
246   MutexGuard locked(lock);
247   return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
248 }
249 
250 uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
251   MutexGuard 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 = Name;
273   }
274   return OldVal;
275 }
276 
277 uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
278   MutexGuard 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   MutexGuard 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   MutexGuard locked(lock);
297   return getPointerToGlobalIfAvailable(getMangledName(GV));
298 }
299 
300 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
301   MutexGuard 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(std::make_pair(
311                                                           Addr, 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 = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
344 
345   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 = make_unique<char[]>(Size);
351     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
352 
353     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
354     Dest[Size-1] = 0;
355 
356     // Endian safe: Array[i] = (PointerTy)Dest;
357     EE->StoreValueToMemory(PTOGV(Dest.get()),
358                            (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
359     Values.push_back(std::move(Dest));
360   }
361 
362   // Null terminate it
363   EE->StoreValueToMemory(PTOGV(nullptr),
364                          (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
365                          SBytePtr);
366   return Array.get();
367 }
368 
369 void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
370                                                        bool isDtors) {
371   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
372   GlobalVariable *GV = module.getNamedGlobal(Name);
373 
374   // If this global has internal linkage, or if it has a use, then it must be
375   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
376   // this is the case, don't execute any of the global ctors, __main will do
377   // it.
378   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
379 
380   // Should be an array of '{ i32, void ()* }' structs.  The first value is
381   // the init priority, which we ignore.
382   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
383   if (!InitList)
384     return;
385   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
386     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
387     if (!CS) continue;
388 
389     Constant *FP = CS->getOperand(1);
390     if (FP->isNullValue())
391       continue;  // Found a sentinal value, ignore.
392 
393     // Strip off constant expression casts.
394     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
395       if (CE->isCast())
396         FP = CE->getOperand(0);
397 
398     // Execute the ctor/dtor function!
399     if (Function *F = dyn_cast<Function>(FP))
400       runFunction(F, None);
401 
402     // FIXME: It is marginally lame that we just do nothing here if we see an
403     // entry we don't recognize. It might not be unreasonable for the verifier
404     // to not even allow this and just assert here.
405   }
406 }
407 
408 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
409   // Execute global ctors/dtors for each module in the program.
410   for (std::unique_ptr<Module> &M : Modules)
411     runStaticConstructorsDestructors(*M, isDtors);
412 }
413 
414 #ifndef NDEBUG
415 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
416 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
417   unsigned PtrSize = EE->getDataLayout().getPointerSize();
418   for (unsigned i = 0; i < PtrSize; ++i)
419     if (*(i + (uint8_t*)Loc))
420       return false;
421   return true;
422 }
423 #endif
424 
425 int ExecutionEngine::runFunctionAsMain(Function *Fn,
426                                        const std::vector<std::string> &argv,
427                                        const char * const * envp) {
428   std::vector<GenericValue> GVArgs;
429   GenericValue GVArgc;
430   GVArgc.IntVal = APInt(32, argv.size());
431 
432   // Check main() type
433   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
434   FunctionType *FTy = Fn->getFunctionType();
435   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
436 
437   // Check the argument types.
438   if (NumArgs > 3)
439     report_fatal_error("Invalid number of arguments of main() supplied");
440   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
441     report_fatal_error("Invalid type for third argument of main() supplied");
442   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
443     report_fatal_error("Invalid type for second argument of main() supplied");
444   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
445     report_fatal_error("Invalid type for first argument of main() supplied");
446   if (!FTy->getReturnType()->isIntegerTy() &&
447       !FTy->getReturnType()->isVoidTy())
448     report_fatal_error("Invalid return type of main() supplied");
449 
450   ArgvArray CArgv;
451   ArgvArray CEnv;
452   if (NumArgs) {
453     GVArgs.push_back(GVArgc); // Arg #0 = argc.
454     if (NumArgs > 1) {
455       // Arg #1 = argv.
456       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
457       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
458              "argv[0] was null after CreateArgv");
459       if (NumArgs > 2) {
460         std::vector<std::string> EnvVars;
461         for (unsigned i = 0; envp[i]; ++i)
462           EnvVars.emplace_back(envp[i]);
463         // Arg #2 = envp.
464         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
465       }
466     }
467   }
468 
469   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
470 }
471 
472 EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
473 
474 EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
475     : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
476       OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
477       RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
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<RuntimeDyld::SymbolResolver> SR) {
506   Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(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     Triple TT(M->getTargetTriple());
535     if (!TM->getTarget().hasJIT()) {
536       errs() << "WARNING: This target JIT is not designed for the host"
537              << " you are running.  If bad things happen, please choose"
538              << " a different -march switch.\n";
539     }
540 
541     ExecutionEngine *EE = nullptr;
542     if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
543       EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
544                                                     std::move(Resolver),
545                                                     std::move(TheTM));
546       EE->addModule(std::move(M));
547     } else if (ExecutionEngine::MCJITCtor)
548       EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
549                                       std::move(Resolver), std::move(TheTM));
550 
551     if (EE) {
552       EE->setVerifyModules(VerifyModules);
553       return EE;
554     }
555   }
556 
557   // If we can't make a JIT and we didn't request one specifically, try making
558   // an interpreter instead.
559   if (WhichEngine & EngineKind::Interpreter) {
560     if (ExecutionEngine::InterpCtor)
561       return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
562     if (ErrorStr)
563       *ErrorStr = "Interpreter has not been linked in.";
564     return nullptr;
565   }
566 
567   if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
568     if (ErrorStr)
569       *ErrorStr = "JIT has not been linked in.";
570   }
571 
572   return nullptr;
573 }
574 
575 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
576   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
577     return getPointerToFunction(F);
578 
579   MutexGuard locked(lock);
580   if (void* P = getPointerToGlobalIfAvailable(GV))
581     return P;
582 
583   // Global variable might have been added since interpreter started.
584   if (GlobalVariable *GVar =
585           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
586     EmitGlobalVariable(GVar);
587   else
588     llvm_unreachable("Global hasn't had an address allocated yet!");
589 
590   return getPointerToGlobalIfAvailable(GV);
591 }
592 
593 /// \brief Converts a Constant* into a GenericValue, including handling of
594 /// ConstantExpr values.
595 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
596   // If its undefined, return the garbage.
597   if (isa<UndefValue>(C)) {
598     GenericValue Result;
599     switch (C->getType()->getTypeID()) {
600     default:
601       break;
602     case Type::IntegerTyID:
603     case Type::X86_FP80TyID:
604     case Type::FP128TyID:
605     case Type::PPC_FP128TyID:
606       // Although the value is undefined, we still have to construct an APInt
607       // with the correct bit width.
608       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
609       break;
610     case Type::StructTyID: {
611       // if the whole struct is 'undef' just reserve memory for the value.
612       if(StructType *STy = dyn_cast<StructType>(C->getType())) {
613         unsigned int elemNum = STy->getNumElements();
614         Result.AggregateVal.resize(elemNum);
615         for (unsigned int i = 0; i < elemNum; ++i) {
616           Type *ElemTy = STy->getElementType(i);
617           if (ElemTy->isIntegerTy())
618             Result.AggregateVal[i].IntVal =
619               APInt(ElemTy->getPrimitiveSizeInBits(), 0);
620           else if (ElemTy->isAggregateType()) {
621               const Constant *ElemUndef = UndefValue::get(ElemTy);
622               Result.AggregateVal[i] = getConstantValue(ElemUndef);
623             }
624           }
625         }
626       }
627       break;
628     case Type::VectorTyID:
629       // if the whole vector is 'undef' just reserve memory for the value.
630       auto* VTy = dyn_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(&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     if (isa<ConstantPointerNull>(C))
907       Result.PointerVal = nullptr;
908     else if (const Function *F = dyn_cast<Function>(C))
909       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
910     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
911       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
912     else
913       llvm_unreachable("Unknown constant pointer type!");
914     break;
915   case Type::VectorTyID: {
916     unsigned elemNum;
917     Type* ElemTy;
918     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
919     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
920     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
921 
922     if (CDV) {
923         elemNum = CDV->getNumElements();
924         ElemTy = CDV->getElementType();
925     } else if (CV || CAZ) {
926         VectorType* VTy = dyn_cast<VectorType>(C->getType());
927         elemNum = VTy->getNumElements();
928         ElemTy = VTy->getElementType();
929     } else {
930         llvm_unreachable("Unknown constant vector type!");
931     }
932 
933     Result.AggregateVal.resize(elemNum);
934     // Check if vector holds floats.
935     if(ElemTy->isFloatTy()) {
936       if (CAZ) {
937         GenericValue floatZero;
938         floatZero.FloatVal = 0.f;
939         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
940                   floatZero);
941         break;
942       }
943       if(CV) {
944         for (unsigned i = 0; i < elemNum; ++i)
945           if (!isa<UndefValue>(CV->getOperand(i)))
946             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
947               CV->getOperand(i))->getValueAPF().convertToFloat();
948         break;
949       }
950       if(CDV)
951         for (unsigned i = 0; i < elemNum; ++i)
952           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
953 
954       break;
955     }
956     // Check if vector holds doubles.
957     if (ElemTy->isDoubleTy()) {
958       if (CAZ) {
959         GenericValue doubleZero;
960         doubleZero.DoubleVal = 0.0;
961         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
962                   doubleZero);
963         break;
964       }
965       if(CV) {
966         for (unsigned i = 0; i < elemNum; ++i)
967           if (!isa<UndefValue>(CV->getOperand(i)))
968             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
969               CV->getOperand(i))->getValueAPF().convertToDouble();
970         break;
971       }
972       if(CDV)
973         for (unsigned i = 0; i < elemNum; ++i)
974           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
975 
976       break;
977     }
978     // Check if vector holds integers.
979     if (ElemTy->isIntegerTy()) {
980       if (CAZ) {
981         GenericValue intZero;
982         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
983         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
984                   intZero);
985         break;
986       }
987       if(CV) {
988         for (unsigned i = 0; i < elemNum; ++i)
989           if (!isa<UndefValue>(CV->getOperand(i)))
990             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
991                                             CV->getOperand(i))->getValue();
992           else {
993             Result.AggregateVal[i].IntVal =
994               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
995           }
996         break;
997       }
998       if(CDV)
999         for (unsigned i = 0; i < elemNum; ++i)
1000           Result.AggregateVal[i].IntVal = APInt(
1001             CDV->getElementType()->getPrimitiveSizeInBits(),
1002             CDV->getElementAsInteger(i));
1003 
1004       break;
1005     }
1006     llvm_unreachable("Unknown constant pointer type!");
1007   }
1008   break;
1009 
1010   default:
1011     SmallString<256> Msg;
1012     raw_svector_ostream OS(Msg);
1013     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1014     report_fatal_error(OS.str());
1015   }
1016 
1017   return Result;
1018 }
1019 
1020 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1021 /// with the integer held in IntVal.
1022 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1023                              unsigned StoreBytes) {
1024   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
1025   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
1026 
1027   if (sys::IsLittleEndianHost) {
1028     // Little-endian host - the source is ordered from LSB to MSB.  Order the
1029     // destination from LSB to MSB: Do a straight copy.
1030     memcpy(Dst, Src, StoreBytes);
1031   } else {
1032     // Big-endian host - the source is an array of 64 bit words ordered from
1033     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
1034     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1035     while (StoreBytes > sizeof(uint64_t)) {
1036       StoreBytes -= sizeof(uint64_t);
1037       // May not be aligned so use memcpy.
1038       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1039       Src += sizeof(uint64_t);
1040     }
1041 
1042     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1043   }
1044 }
1045 
1046 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
1047                                          GenericValue *Ptr, Type *Ty) {
1048   const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
1049 
1050   switch (Ty->getTypeID()) {
1051   default:
1052     dbgs() << "Cannot store value of type " << *Ty << "!\n";
1053     break;
1054   case Type::IntegerTyID:
1055     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
1056     break;
1057   case Type::FloatTyID:
1058     *((float*)Ptr) = Val.FloatVal;
1059     break;
1060   case Type::DoubleTyID:
1061     *((double*)Ptr) = Val.DoubleVal;
1062     break;
1063   case Type::X86_FP80TyID:
1064     memcpy(Ptr, Val.IntVal.getRawData(), 10);
1065     break;
1066   case Type::PointerTyID:
1067     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1068     if (StoreBytes != sizeof(PointerTy))
1069       memset(&(Ptr->PointerVal), 0, StoreBytes);
1070 
1071     *((PointerTy*)Ptr) = Val.PointerVal;
1072     break;
1073   case Type::VectorTyID:
1074     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1075       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1076         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1077       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1078         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1079       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1080         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1081         StoreIntToMemory(Val.AggregateVal[i].IntVal,
1082           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1083       }
1084     }
1085     break;
1086   }
1087 
1088   if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
1089     // Host and target are different endian - reverse the stored bytes.
1090     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1091 }
1092 
1093 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1094 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1095 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1096   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
1097   uint8_t *Dst = reinterpret_cast<uint8_t *>(
1098                    const_cast<uint64_t *>(IntVal.getRawData()));
1099 
1100   if (sys::IsLittleEndianHost)
1101     // Little-endian host - the destination must be ordered from LSB to MSB.
1102     // The source is ordered from LSB to MSB: Do a straight copy.
1103     memcpy(Dst, Src, LoadBytes);
1104   else {
1105     // Big-endian - the destination is an array of 64 bit words ordered from
1106     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
1107     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1108     // a word.
1109     while (LoadBytes > sizeof(uint64_t)) {
1110       LoadBytes -= sizeof(uint64_t);
1111       // May not be aligned so use memcpy.
1112       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1113       Dst += sizeof(uint64_t);
1114     }
1115 
1116     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1117   }
1118 }
1119 
1120 /// FIXME: document
1121 ///
1122 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
1123                                           GenericValue *Ptr,
1124                                           Type *Ty) {
1125   const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
1126 
1127   switch (Ty->getTypeID()) {
1128   case Type::IntegerTyID:
1129     // An APInt with all words initially zero.
1130     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1131     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1132     break;
1133   case Type::FloatTyID:
1134     Result.FloatVal = *((float*)Ptr);
1135     break;
1136   case Type::DoubleTyID:
1137     Result.DoubleVal = *((double*)Ptr);
1138     break;
1139   case Type::PointerTyID:
1140     Result.PointerVal = *((PointerTy*)Ptr);
1141     break;
1142   case Type::X86_FP80TyID: {
1143     // This is endian dependent, but it will only work on x86 anyway.
1144     // FIXME: Will not trap if loading a signaling NaN.
1145     uint64_t y[2];
1146     memcpy(y, Ptr, 10);
1147     Result.IntVal = APInt(80, y);
1148     break;
1149   }
1150   case Type::VectorTyID: {
1151     auto *VT = cast<VectorType>(Ty);
1152     Type *ElemT = VT->getElementType();
1153     const unsigned numElems = VT->getNumElements();
1154     if (ElemT->isFloatTy()) {
1155       Result.AggregateVal.resize(numElems);
1156       for (unsigned i = 0; i < numElems; ++i)
1157         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1158     }
1159     if (ElemT->isDoubleTy()) {
1160       Result.AggregateVal.resize(numElems);
1161       for (unsigned i = 0; i < numElems; ++i)
1162         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1163     }
1164     if (ElemT->isIntegerTy()) {
1165       GenericValue intZero;
1166       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1167       intZero.IntVal = APInt(elemBitWidth, 0);
1168       Result.AggregateVal.resize(numElems, intZero);
1169       for (unsigned i = 0; i < numElems; ++i)
1170         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1171           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1172     }
1173   break;
1174   }
1175   default:
1176     SmallString<256> Msg;
1177     raw_svector_ostream OS(Msg);
1178     OS << "Cannot load value of type " << *Ty << "!";
1179     report_fatal_error(OS.str());
1180   }
1181 }
1182 
1183 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
1184   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1185   DEBUG(Init->dump());
1186   if (isa<UndefValue>(Init))
1187     return;
1188 
1189   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
1190     unsigned ElementSize =
1191         getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
1192     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1193       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1194     return;
1195   }
1196 
1197   if (isa<ConstantAggregateZero>(Init)) {
1198     memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
1199     return;
1200   }
1201 
1202   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
1203     unsigned ElementSize =
1204         getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
1205     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1206       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1207     return;
1208   }
1209 
1210   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
1211     const StructLayout *SL =
1212         getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
1213     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1214       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1215     return;
1216   }
1217 
1218   if (const ConstantDataSequential *CDS =
1219                dyn_cast<ConstantDataSequential>(Init)) {
1220     // CDS is already laid out in host memory order.
1221     StringRef Data = CDS->getRawDataValues();
1222     memcpy(Addr, Data.data(), Data.size());
1223     return;
1224   }
1225 
1226   if (Init->getType()->isFirstClassType()) {
1227     GenericValue Val = getConstantValue(Init);
1228     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1229     return;
1230   }
1231 
1232   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1233   llvm_unreachable("Unknown constant type to initialize memory with!");
1234 }
1235 
1236 /// EmitGlobals - Emit all of the global variables to memory, storing their
1237 /// addresses into GlobalAddress.  This must make sure to copy the contents of
1238 /// their initializers into the memory.
1239 void ExecutionEngine::emitGlobals() {
1240   // Loop over all of the global variables in the program, allocating the memory
1241   // to hold them.  If there is more than one module, do a prepass over globals
1242   // to figure out how the different modules should link together.
1243   std::map<std::pair<std::string, Type*>,
1244            const GlobalValue*> LinkedGlobalsMap;
1245 
1246   if (Modules.size() != 1) {
1247     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1248       Module &M = *Modules[m];
1249       for (const auto &GV : M.globals()) {
1250         if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1251             GV.hasAppendingLinkage() || !GV.hasName())
1252           continue;// Ignore external globals and globals with internal linkage.
1253 
1254         const GlobalValue *&GVEntry =
1255           LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
1256 
1257         // If this is the first time we've seen this global, it is the canonical
1258         // version.
1259         if (!GVEntry) {
1260           GVEntry = &GV;
1261           continue;
1262         }
1263 
1264         // If the existing global is strong, never replace it.
1265         if (GVEntry->hasExternalLinkage())
1266           continue;
1267 
1268         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1269         // symbol.  FIXME is this right for common?
1270         if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1271           GVEntry = &GV;
1272       }
1273     }
1274   }
1275 
1276   std::vector<const GlobalValue*> NonCanonicalGlobals;
1277   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1278     Module &M = *Modules[m];
1279     for (const auto &GV : M.globals()) {
1280       // In the multi-module case, see what this global maps to.
1281       if (!LinkedGlobalsMap.empty()) {
1282         if (const GlobalValue *GVEntry =
1283               LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
1284           // If something else is the canonical global, ignore this one.
1285           if (GVEntry != &GV) {
1286             NonCanonicalGlobals.push_back(&GV);
1287             continue;
1288           }
1289         }
1290       }
1291 
1292       if (!GV.isDeclaration()) {
1293         addGlobalMapping(&GV, getMemoryForGV(&GV));
1294       } else {
1295         // External variable reference. Try to use the dynamic loader to
1296         // get a pointer to it.
1297         if (void *SymAddr =
1298             sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1299           addGlobalMapping(&GV, SymAddr);
1300         else {
1301           report_fatal_error("Could not resolve external global address: "
1302                             +GV.getName());
1303         }
1304       }
1305     }
1306 
1307     // If there are multiple modules, map the non-canonical globals to their
1308     // canonical location.
1309     if (!NonCanonicalGlobals.empty()) {
1310       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1311         const GlobalValue *GV = NonCanonicalGlobals[i];
1312         const GlobalValue *CGV =
1313           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1314         void *Ptr = getPointerToGlobalIfAvailable(CGV);
1315         assert(Ptr && "Canonical global wasn't codegen'd!");
1316         addGlobalMapping(GV, Ptr);
1317       }
1318     }
1319 
1320     // Now that all of the globals are set up in memory, loop through them all
1321     // and initialize their contents.
1322     for (const auto &GV : M.globals()) {
1323       if (!GV.isDeclaration()) {
1324         if (!LinkedGlobalsMap.empty()) {
1325           if (const GlobalValue *GVEntry =
1326                 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1327             if (GVEntry != &GV)  // Not the canonical variable.
1328               continue;
1329         }
1330         EmitGlobalVariable(&GV);
1331       }
1332     }
1333   }
1334 }
1335 
1336 // EmitGlobalVariable - This method emits the specified global variable to the
1337 // address specified in GlobalAddresses, or allocates new memory if it's not
1338 // already in the map.
1339 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1340   void *GA = getPointerToGlobalIfAvailable(GV);
1341 
1342   if (!GA) {
1343     // If it's not already specified, allocate memory for the global.
1344     GA = getMemoryForGV(GV);
1345 
1346     // If we failed to allocate memory for this global, return.
1347     if (!GA) return;
1348 
1349     addGlobalMapping(GV, GA);
1350   }
1351 
1352   // Don't initialize if it's thread local, let the client do it.
1353   if (!GV->isThreadLocal())
1354     InitializeMemory(GV->getInitializer(), GA);
1355 
1356   Type *ElTy = GV->getValueType();
1357   size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
1358   NumInitBytes += (unsigned)GVSize;
1359   ++NumGlobals;
1360 }
1361