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