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