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