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