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