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