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