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