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