94a2542e7ad6b5a0d4c318a6459f2a27da82629b
[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 #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       unsigned AS = cast<PointerType>(CE->getOperand(1)->getType())
649         ->getAddressSpace();
650       uint32_t PtrWidth = TD->getPointerSizeInBits(AS);
651       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
652       return GV;
653     }
654     case Instruction::IntToPtr: {
655       GenericValue GV = getConstantValue(Op0);
656       unsigned AS = cast<PointerType>(CE->getType())->getAddressSpace();
657       uint32_t PtrWidth = TD->getPointerSizeInBits(AS);
658       if (PtrWidth != GV.IntVal.getBitWidth())
659         GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
660       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
661       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
662       return GV;
663     }
664     case Instruction::BitCast: {
665       GenericValue GV = getConstantValue(Op0);
666       Type* DestTy = CE->getType();
667       switch (Op0->getType()->getTypeID()) {
668         default: llvm_unreachable("Invalid bitcast operand");
669         case Type::IntegerTyID:
670           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
671           if (DestTy->isFloatTy())
672             GV.FloatVal = GV.IntVal.bitsToFloat();
673           else if (DestTy->isDoubleTy())
674             GV.DoubleVal = GV.IntVal.bitsToDouble();
675           break;
676         case Type::FloatTyID:
677           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
678           GV.IntVal = APInt::floatToBits(GV.FloatVal);
679           break;
680         case Type::DoubleTyID:
681           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
682           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
683           break;
684         case Type::PointerTyID:
685           assert(DestTy->isPointerTy() && "Invalid bitcast");
686           break; // getConstantValue(Op0)  above already converted it
687       }
688       return GV;
689     }
690     case Instruction::Add:
691     case Instruction::FAdd:
692     case Instruction::Sub:
693     case Instruction::FSub:
694     case Instruction::Mul:
695     case Instruction::FMul:
696     case Instruction::UDiv:
697     case Instruction::SDiv:
698     case Instruction::URem:
699     case Instruction::SRem:
700     case Instruction::And:
701     case Instruction::Or:
702     case Instruction::Xor: {
703       GenericValue LHS = getConstantValue(Op0);
704       GenericValue RHS = getConstantValue(CE->getOperand(1));
705       GenericValue GV;
706       switch (CE->getOperand(0)->getType()->getTypeID()) {
707       default: llvm_unreachable("Bad add type!");
708       case Type::IntegerTyID:
709         switch (CE->getOpcode()) {
710           default: llvm_unreachable("Invalid integer opcode");
711           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
712           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
713           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
714           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
715           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
716           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
717           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
718           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
719           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
720           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
721         }
722         break;
723       case Type::FloatTyID:
724         switch (CE->getOpcode()) {
725           default: llvm_unreachable("Invalid float opcode");
726           case Instruction::FAdd:
727             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
728           case Instruction::FSub:
729             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
730           case Instruction::FMul:
731             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
732           case Instruction::FDiv:
733             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
734           case Instruction::FRem:
735             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
736         }
737         break;
738       case Type::DoubleTyID:
739         switch (CE->getOpcode()) {
740           default: llvm_unreachable("Invalid double opcode");
741           case Instruction::FAdd:
742             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
743           case Instruction::FSub:
744             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
745           case Instruction::FMul:
746             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
747           case Instruction::FDiv:
748             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
749           case Instruction::FRem:
750             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
751         }
752         break;
753       case Type::X86_FP80TyID:
754       case Type::PPC_FP128TyID:
755       case Type::FP128TyID: {
756         APFloat apfLHS = APFloat(LHS.IntVal);
757         switch (CE->getOpcode()) {
758           default: llvm_unreachable("Invalid long double opcode");
759           case Instruction::FAdd:
760             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
761             GV.IntVal = apfLHS.bitcastToAPInt();
762             break;
763           case Instruction::FSub:
764             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
765             GV.IntVal = apfLHS.bitcastToAPInt();
766             break;
767           case Instruction::FMul:
768             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
769             GV.IntVal = apfLHS.bitcastToAPInt();
770             break;
771           case Instruction::FDiv:
772             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
773             GV.IntVal = apfLHS.bitcastToAPInt();
774             break;
775           case Instruction::FRem:
776             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
777             GV.IntVal = apfLHS.bitcastToAPInt();
778             break;
779           }
780         }
781         break;
782       }
783       return GV;
784     }
785     default:
786       break;
787     }
788
789     SmallString<256> Msg;
790     raw_svector_ostream OS(Msg);
791     OS << "ConstantExpr not handled: " << *CE;
792     report_fatal_error(OS.str());
793   }
794
795   // Otherwise, we have a simple constant.
796   GenericValue Result;
797   switch (C->getType()->getTypeID()) {
798   case Type::FloatTyID:
799     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
800     break;
801   case Type::DoubleTyID:
802     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
803     break;
804   case Type::X86_FP80TyID:
805   case Type::FP128TyID:
806   case Type::PPC_FP128TyID:
807     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
808     break;
809   case Type::IntegerTyID:
810     Result.IntVal = cast<ConstantInt>(C)->getValue();
811     break;
812   case Type::PointerTyID:
813     if (isa<ConstantPointerNull>(C))
814       Result.PointerVal = 0;
815     else if (const Function *F = dyn_cast<Function>(C))
816       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
817     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
818       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
819     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
820       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
821                                                         BA->getBasicBlock())));
822     else
823       llvm_unreachable("Unknown constant pointer type!");
824     break;
825   default:
826     SmallString<256> Msg;
827     raw_svector_ostream OS(Msg);
828     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
829     report_fatal_error(OS.str());
830   }
831
832   return Result;
833 }
834
835 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
836 /// with the integer held in IntVal.
837 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
838                              unsigned StoreBytes) {
839   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
840   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
841
842   if (sys::isLittleEndianHost()) {
843     // Little-endian host - the source is ordered from LSB to MSB.  Order the
844     // destination from LSB to MSB: Do a straight copy.
845     memcpy(Dst, Src, StoreBytes);
846   } else {
847     // Big-endian host - the source is an array of 64 bit words ordered from
848     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
849     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
850     while (StoreBytes > sizeof(uint64_t)) {
851       StoreBytes -= sizeof(uint64_t);
852       // May not be aligned so use memcpy.
853       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
854       Src += sizeof(uint64_t);
855     }
856
857     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
858   }
859 }
860
861 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
862                                          GenericValue *Ptr, Type *Ty) {
863   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
864
865   switch (Ty->getTypeID()) {
866   case Type::IntegerTyID:
867     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
868     break;
869   case Type::FloatTyID:
870     *((float*)Ptr) = Val.FloatVal;
871     break;
872   case Type::DoubleTyID:
873     *((double*)Ptr) = Val.DoubleVal;
874     break;
875   case Type::X86_FP80TyID:
876     memcpy(Ptr, Val.IntVal.getRawData(), 10);
877     break;
878   case Type::PointerTyID:
879     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
880     if (StoreBytes != sizeof(PointerTy))
881       memset(&(Ptr->PointerVal), 0, StoreBytes);
882
883     *((PointerTy*)Ptr) = Val.PointerVal;
884     break;
885   default:
886     dbgs() << "Cannot store value of type " << *Ty << "!\n";
887   }
888
889   if (sys::isLittleEndianHost() != getDataLayout()->isLittleEndian())
890     // Host and target are different endian - reverse the stored bytes.
891     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
892 }
893
894 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
895 /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
896 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
897   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
898   uint8_t *Dst = (uint8_t *)IntVal.getRawData();
899
900   if (sys::isLittleEndianHost())
901     // Little-endian host - the destination must be ordered from LSB to MSB.
902     // The source is ordered from LSB to MSB: Do a straight copy.
903     memcpy(Dst, Src, LoadBytes);
904   else {
905     // Big-endian - the destination is an array of 64 bit words ordered from
906     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
907     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
908     // a word.
909     while (LoadBytes > sizeof(uint64_t)) {
910       LoadBytes -= sizeof(uint64_t);
911       // May not be aligned so use memcpy.
912       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
913       Dst += sizeof(uint64_t);
914     }
915
916     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
917   }
918 }
919
920 /// FIXME: document
921 ///
922 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
923                                           GenericValue *Ptr,
924                                           Type *Ty) {
925   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
926
927   switch (Ty->getTypeID()) {
928   case Type::IntegerTyID:
929     // An APInt with all words initially zero.
930     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
931     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
932     break;
933   case Type::FloatTyID:
934     Result.FloatVal = *((float*)Ptr);
935     break;
936   case Type::DoubleTyID:
937     Result.DoubleVal = *((double*)Ptr);
938     break;
939   case Type::PointerTyID:
940     Result.PointerVal = *((PointerTy*)Ptr);
941     break;
942   case Type::X86_FP80TyID: {
943     // This is endian dependent, but it will only work on x86 anyway.
944     // FIXME: Will not trap if loading a signaling NaN.
945     uint64_t y[2];
946     memcpy(y, Ptr, 10);
947     Result.IntVal = APInt(80, y);
948     break;
949   }
950   default:
951     SmallString<256> Msg;
952     raw_svector_ostream OS(Msg);
953     OS << "Cannot load value of type " << *Ty << "!";
954     report_fatal_error(OS.str());
955   }
956 }
957
958 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
959   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
960   DEBUG(Init->dump());
961   if (isa<UndefValue>(Init))
962     return;
963   
964   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
965     unsigned ElementSize =
966       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
967     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
968       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
969     return;
970   }
971   
972   if (isa<ConstantAggregateZero>(Init)) {
973     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
974     return;
975   }
976   
977   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
978     unsigned ElementSize =
979       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
980     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
981       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
982     return;
983   }
984   
985   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
986     const StructLayout *SL =
987       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
988     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
989       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
990     return;
991   }
992
993   if (const ConstantDataSequential *CDS =
994                dyn_cast<ConstantDataSequential>(Init)) {
995     // CDS is already laid out in host memory order.
996     StringRef Data = CDS->getRawDataValues();
997     memcpy(Addr, Data.data(), Data.size());
998     return;
999   }
1000
1001   if (Init->getType()->isFirstClassType()) {
1002     GenericValue Val = getConstantValue(Init);
1003     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1004     return;
1005   }
1006
1007   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1008   llvm_unreachable("Unknown constant type to initialize memory with!");
1009 }
1010
1011 /// EmitGlobals - Emit all of the global variables to memory, storing their
1012 /// addresses into GlobalAddress.  This must make sure to copy the contents of
1013 /// their initializers into the memory.
1014 void ExecutionEngine::emitGlobals() {
1015   // Loop over all of the global variables in the program, allocating the memory
1016   // to hold them.  If there is more than one module, do a prepass over globals
1017   // to figure out how the different modules should link together.
1018   std::map<std::pair<std::string, Type*>,
1019            const GlobalValue*> LinkedGlobalsMap;
1020
1021   if (Modules.size() != 1) {
1022     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1023       Module &M = *Modules[m];
1024       for (Module::const_global_iterator I = M.global_begin(),
1025            E = M.global_end(); I != E; ++I) {
1026         const GlobalValue *GV = I;
1027         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
1028             GV->hasAppendingLinkage() || !GV->hasName())
1029           continue;// Ignore external globals and globals with internal linkage.
1030
1031         const GlobalValue *&GVEntry =
1032           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1033
1034         // If this is the first time we've seen this global, it is the canonical
1035         // version.
1036         if (!GVEntry) {
1037           GVEntry = GV;
1038           continue;
1039         }
1040
1041         // If the existing global is strong, never replace it.
1042         if (GVEntry->hasExternalLinkage() ||
1043             GVEntry->hasDLLImportLinkage() ||
1044             GVEntry->hasDLLExportLinkage())
1045           continue;
1046
1047         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1048         // symbol.  FIXME is this right for common?
1049         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1050           GVEntry = GV;
1051       }
1052     }
1053   }
1054
1055   std::vector<const GlobalValue*> NonCanonicalGlobals;
1056   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1057     Module &M = *Modules[m];
1058     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1059          I != E; ++I) {
1060       // In the multi-module case, see what this global maps to.
1061       if (!LinkedGlobalsMap.empty()) {
1062         if (const GlobalValue *GVEntry =
1063               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1064           // If something else is the canonical global, ignore this one.
1065           if (GVEntry != &*I) {
1066             NonCanonicalGlobals.push_back(I);
1067             continue;
1068           }
1069         }
1070       }
1071
1072       if (!I->isDeclaration()) {
1073         addGlobalMapping(I, getMemoryForGV(I));
1074       } else {
1075         // External variable reference. Try to use the dynamic loader to
1076         // get a pointer to it.
1077         if (void *SymAddr =
1078             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1079           addGlobalMapping(I, SymAddr);
1080         else {
1081           report_fatal_error("Could not resolve external global address: "
1082                             +I->getName());
1083         }
1084       }
1085     }
1086
1087     // If there are multiple modules, map the non-canonical globals to their
1088     // canonical location.
1089     if (!NonCanonicalGlobals.empty()) {
1090       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1091         const GlobalValue *GV = NonCanonicalGlobals[i];
1092         const GlobalValue *CGV =
1093           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1094         void *Ptr = getPointerToGlobalIfAvailable(CGV);
1095         assert(Ptr && "Canonical global wasn't codegen'd!");
1096         addGlobalMapping(GV, Ptr);
1097       }
1098     }
1099
1100     // Now that all of the globals are set up in memory, loop through them all
1101     // and initialize their contents.
1102     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1103          I != E; ++I) {
1104       if (!I->isDeclaration()) {
1105         if (!LinkedGlobalsMap.empty()) {
1106           if (const GlobalValue *GVEntry =
1107                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1108             if (GVEntry != &*I)  // Not the canonical variable.
1109               continue;
1110         }
1111         EmitGlobalVariable(I);
1112       }
1113     }
1114   }
1115 }
1116
1117 // EmitGlobalVariable - This method emits the specified global variable to the
1118 // address specified in GlobalAddresses, or allocates new memory if it's not
1119 // already in the map.
1120 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1121   void *GA = getPointerToGlobalIfAvailable(GV);
1122
1123   if (GA == 0) {
1124     // If it's not already specified, allocate memory for the global.
1125     GA = getMemoryForGV(GV);
1126     addGlobalMapping(GV, GA);
1127   }
1128
1129   // Don't initialize if it's thread local, let the client do it.
1130   if (!GV->isThreadLocal())
1131     InitializeMemory(GV->getInitializer(), GA);
1132
1133   Type *ElTy = GV->getType()->getElementType();
1134   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1135   NumInitBytes += (unsigned)GVSize;
1136   ++NumGlobals;
1137 }
1138
1139 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1140   : EE(EE), GlobalAddressMap(this) {
1141 }
1142
1143 sys::Mutex *
1144 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1145   return &EES->EE.lock;
1146 }
1147
1148 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1149                                                       const GlobalValue *Old) {
1150   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1151   EES->GlobalAddressReverseMap.erase(OldVal);
1152 }
1153
1154 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1155                                                     const GlobalValue *,
1156                                                     const GlobalValue *) {
1157   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1158                    " RAUW on a value it has a global mapping for.");
1159 }