1857c21b4SMisha Brukman //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2996fe010SChris Lattner //
3482202a6SJohn Criswell //                     The LLVM Compiler Infrastructure
4482202a6SJohn Criswell //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7482202a6SJohn Criswell //
8482202a6SJohn Criswell //===----------------------------------------------------------------------===//
9482202a6SJohn Criswell //
10996fe010SChris Lattner // This file defines the common interface used by the various execution engine
11996fe010SChris Lattner // subclasses.
12996fe010SChris Lattner //
13996fe010SChris Lattner //===----------------------------------------------------------------------===//
14996fe010SChris Lattner 
15ee937c80SChris Lattner #define DEBUG_TYPE "jit"
166bf87df5SJeffrey Yasskin #include "llvm/ExecutionEngine/ExecutionEngine.h"
17*9bc53e84SFilip Pizlo #include "llvm/ExecutionEngine/JITMemoryManager.h"
18868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h"
19390d78b3SChris Lattner #include "llvm/ADT/Statistic.h"
20ed0881b2SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h"
219fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
229fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
239fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
249fb823bbSChandler Carruth #include "llvm/IR/Module.h"
259fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
267c16caa3SReid Spencer #include "llvm/Support/Debug.h"
27ed0881b2SChandler Carruth #include "llvm/Support/DynamicLibrary.h"
286c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h"
29ed0881b2SChandler Carruth #include "llvm/Support/Host.h"
306d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h"
31ed0881b2SChandler Carruth #include "llvm/Support/TargetRegistry.h"
326bf87df5SJeffrey Yasskin #include "llvm/Support/ValueHandle.h"
33ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h"
348418fdcdSDylan Noblesmith #include "llvm/Target/TargetMachine.h"
35579f0713SAnton Korobeynikov #include <cmath>
36579f0713SAnton Korobeynikov #include <cstring>
3729681deeSChris Lattner using namespace llvm;
38996fe010SChris Lattner 
39c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
40c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
41996fe010SChris Lattner 
4231faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)(
4331faefffSJeffrey Yasskin   Module *M,
44fc8a2d5aSReid Kleckner   std::string *ErrorStr,
45fc8a2d5aSReid Kleckner   JITMemoryManager *JMM,
46700d08e1SEric Christopher   bool GVsWithCode,
478418fdcdSDylan Noblesmith   TargetMachine *TM) = 0;
4870ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
4970ff8b05SDaniel Dunbar   Module *M,
5070ff8b05SDaniel Dunbar   std::string *ErrorStr,
51*9bc53e84SFilip Pizlo   RTDyldMemoryManager *MCJMM,
5270ff8b05SDaniel Dunbar   bool GVsWithCode,
538418fdcdSDylan Noblesmith   TargetMachine *TM) = 0;
54091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
55fc8a2d5aSReid Kleckner                                                 std::string *ErrorStr) = 0;
562d52c1b8SChris Lattner 
57091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M)
58f98e981cSJeffrey Yasskin   : EEState(*this),
59abc7901eSDuncan Sands     LazyFunctionCreator(0),
60abc7901eSDuncan Sands     ExceptionTableRegister(0),
61abc7901eSDuncan Sands     ExceptionTableDeregister(0) {
624567db45SJeffrey Yasskin   CompilingLazily         = false;
63cdc0060eSEvan Cheng   GVCompilationDisabled   = false;
6484a9055eSEvan Cheng   SymbolSearchingDisabled = false;
65091217beSJeffrey Yasskin   Modules.push_back(M);
66091217beSJeffrey Yasskin   assert(M && "Module is null?");
67260b0c88SMisha Brukman }
68260b0c88SMisha Brukman 
6992f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() {
70603682adSReid Spencer   clearAllGlobalMappings();
710621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
720621caefSChris Lattner     delete Modules[i];
7392f8b30dSBrian Gaeke }
7492f8b30dSBrian Gaeke 
75abc7901eSDuncan Sands void ExecutionEngine::DeregisterAllTables() {
76abc7901eSDuncan Sands   if (ExceptionTableDeregister) {
77f045b7abSEric Christopher     DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
78f045b7abSEric Christopher     DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
79f045b7abSEric Christopher     for (; it != ite; ++it)
80f045b7abSEric Christopher       ExceptionTableDeregister(it->second);
81abc7901eSDuncan Sands     AllExceptionTables.clear();
82abc7901eSDuncan Sands   }
83abc7901eSDuncan Sands }
84abc7901eSDuncan Sands 
85a4044332SJeffrey Yasskin namespace {
86868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the
87868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed.
88a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH {
89a4044332SJeffrey Yasskin   GVMemoryBlock(const GlobalVariable *GV)
90a4044332SJeffrey Yasskin     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
91a4044332SJeffrey Yasskin 
92a4044332SJeffrey Yasskin public:
93868e3f09SDaniel Dunbar   /// \brief Returns the address the GlobalVariable should be written into.  The
94868e3f09SDaniel Dunbar   /// GVMemoryBlock object prefixes that.
95cdfe20b9SMicah Villmow   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
96229907cdSChris Lattner     Type *ElTy = GV->getType()->getElementType();
97a4044332SJeffrey Yasskin     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
98a4044332SJeffrey Yasskin     void *RawMemory = ::operator new(
99cdfe20b9SMicah Villmow       DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
100a4044332SJeffrey Yasskin                                    TD.getPreferredAlignment(GV))
101a4044332SJeffrey Yasskin       + GVSize);
102a4044332SJeffrey Yasskin     new(RawMemory) GVMemoryBlock(GV);
103a4044332SJeffrey Yasskin     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
104a4044332SJeffrey Yasskin   }
105a4044332SJeffrey Yasskin 
106a4044332SJeffrey Yasskin   virtual void deleted() {
107a4044332SJeffrey Yasskin     // We allocated with operator new and with some extra memory hanging off the
108a4044332SJeffrey Yasskin     // end, so don't just delete this.  I'm not sure if this is actually
109a4044332SJeffrey Yasskin     // required.
110a4044332SJeffrey Yasskin     this->~GVMemoryBlock();
111a4044332SJeffrey Yasskin     ::operator delete(this);
112a4044332SJeffrey Yasskin   }
113a4044332SJeffrey Yasskin };
114a4044332SJeffrey Yasskin }  // anonymous namespace
115a4044332SJeffrey Yasskin 
116a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
117cdfe20b9SMicah Villmow   return GVMemoryBlock::Create(GV, *getDataLayout());
1185457ce9aSNicolas Geoffray }
1195457ce9aSNicolas Geoffray 
120091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) {
121091217beSJeffrey Yasskin   for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
122324fe890SDevang Patel         E = Modules.end(); I != E; ++I) {
123091217beSJeffrey Yasskin     Module *Found = *I;
124091217beSJeffrey Yasskin     if (Found == M) {
125324fe890SDevang Patel       Modules.erase(I);
126091217beSJeffrey Yasskin       clearGlobalMappingsFromModule(M);
127091217beSJeffrey Yasskin       return true;
128324fe890SDevang Patel     }
129324fe890SDevang Patel   }
130091217beSJeffrey Yasskin   return false;
131617001d8SNate Begeman }
132617001d8SNate Begeman 
1330621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
1340621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
135091217beSJeffrey Yasskin     if (Function *F = Modules[i]->getFunction(FnName))
1360621caefSChris Lattner       return F;
1370621caefSChris Lattner   }
1380621caefSChris Lattner   return 0;
1390621caefSChris Lattner }
1400621caefSChris Lattner 
1410621caefSChris Lattner 
142868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
143868e3f09SDaniel Dunbar                                           const GlobalValue *ToUnmap) {
144d0fc8f80SJeffrey Yasskin   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
145307c053fSJeffrey Yasskin   void *OldVal;
146868e3f09SDaniel Dunbar 
147868e3f09SDaniel Dunbar   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
148868e3f09SDaniel Dunbar   // GlobalAddressMap.
149307c053fSJeffrey Yasskin   if (I == GlobalAddressMap.end())
150307c053fSJeffrey Yasskin     OldVal = 0;
151307c053fSJeffrey Yasskin   else {
152307c053fSJeffrey Yasskin     OldVal = I->second;
153307c053fSJeffrey Yasskin     GlobalAddressMap.erase(I);
154307c053fSJeffrey Yasskin   }
155307c053fSJeffrey Yasskin 
156307c053fSJeffrey Yasskin   GlobalAddressReverseMap.erase(OldVal);
157307c053fSJeffrey Yasskin   return OldVal;
158307c053fSJeffrey Yasskin }
159307c053fSJeffrey Yasskin 
1606d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
1616d8dd189SChris Lattner   MutexGuard locked(lock);
1626d8dd189SChris Lattner 
1630967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
1649813b0b0SDaniel Dunbar         << "\' to [" << Addr << "]\n";);
165d0fc8f80SJeffrey Yasskin   void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
1666d8dd189SChris Lattner   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
1676d8dd189SChris Lattner   CurVal = Addr;
1686d8dd189SChris Lattner 
169868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
170f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
1716bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
172f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
1736d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
1746d8dd189SChris Lattner     V = GV;
1756d8dd189SChris Lattner   }
1766d8dd189SChris Lattner }
1776d8dd189SChris Lattner 
1786d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
1796d8dd189SChris Lattner   MutexGuard locked(lock);
1806d8dd189SChris Lattner 
181f98e981cSJeffrey Yasskin   EEState.getGlobalAddressMap(locked).clear();
182f98e981cSJeffrey Yasskin   EEState.getGlobalAddressReverseMap(locked).clear();
1836d8dd189SChris Lattner }
1846d8dd189SChris Lattner 
1858f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
1868f83fc4dSNate Begeman   MutexGuard locked(lock);
1878f83fc4dSNate Begeman 
188868e3f09SDaniel Dunbar   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
189f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, FI);
1908f83fc4dSNate Begeman   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
191868e3f09SDaniel Dunbar        GI != GE; ++GI)
192f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, GI);
1938f83fc4dSNate Begeman }
1948f83fc4dSNate Begeman 
195ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
1966d8dd189SChris Lattner   MutexGuard locked(lock);
1976d8dd189SChris Lattner 
198d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy &Map =
199f98e981cSJeffrey Yasskin     EEState.getGlobalAddressMap(locked);
200ee181730SChris Lattner 
2016d8dd189SChris Lattner   // Deleting from the mapping?
202868e3f09SDaniel Dunbar   if (Addr == 0)
203f98e981cSJeffrey Yasskin     return EEState.RemoveMapping(locked, GV);
204ee181730SChris Lattner 
205d0fc8f80SJeffrey Yasskin   void *&CurVal = Map[GV];
206ee181730SChris Lattner   void *OldVal = CurVal;
207ee181730SChris Lattner 
208f98e981cSJeffrey Yasskin   if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
209f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
2106d8dd189SChris Lattner   CurVal = Addr;
2116d8dd189SChris Lattner 
212868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
213f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
2146bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
215f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
2166d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
2176d8dd189SChris Lattner     V = GV;
2186d8dd189SChris Lattner   }
219ee181730SChris Lattner   return OldVal;
2206d8dd189SChris Lattner }
2216d8dd189SChris Lattner 
2226d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
2236d8dd189SChris Lattner   MutexGuard locked(lock);
2246d8dd189SChris Lattner 
225d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy::iterator I =
226d0fc8f80SJeffrey Yasskin     EEState.getGlobalAddressMap(locked).find(GV);
227f98e981cSJeffrey Yasskin   return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
2286d8dd189SChris Lattner }
2296d8dd189SChris Lattner 
230748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
23179876f52SReid Spencer   MutexGuard locked(lock);
23279876f52SReid Spencer 
233748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
234f98e981cSJeffrey Yasskin   if (EEState.getGlobalAddressReverseMap(locked).empty()) {
235d0fc8f80SJeffrey Yasskin     for (ExecutionEngineState::GlobalAddressMapTy::iterator
236f98e981cSJeffrey Yasskin          I = EEState.getGlobalAddressMap(locked).begin(),
237f98e981cSJeffrey Yasskin          E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
238e4f47434SDaniel Dunbar       EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
239e4f47434SDaniel Dunbar                                                           I->second, I->first));
240748e8579SChris Lattner   }
241748e8579SChris Lattner 
2426bf87df5SJeffrey Yasskin   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
243f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).find(Addr);
244f98e981cSJeffrey Yasskin   return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
245748e8579SChris Lattner }
2465a0d4829SChris Lattner 
247bfd38abbSJeffrey Yasskin namespace {
248bfd38abbSJeffrey Yasskin class ArgvArray {
249bfd38abbSJeffrey Yasskin   char *Array;
250bfd38abbSJeffrey Yasskin   std::vector<char*> Values;
251bfd38abbSJeffrey Yasskin public:
252bfd38abbSJeffrey Yasskin   ArgvArray() : Array(NULL) {}
253bfd38abbSJeffrey Yasskin   ~ArgvArray() { clear(); }
254bfd38abbSJeffrey Yasskin   void clear() {
255bfd38abbSJeffrey Yasskin     delete[] Array;
256bfd38abbSJeffrey Yasskin     Array = NULL;
257bfd38abbSJeffrey Yasskin     for (size_t I = 0, E = Values.size(); I != E; ++I) {
258bfd38abbSJeffrey Yasskin       delete[] Values[I];
259bfd38abbSJeffrey Yasskin     }
260bfd38abbSJeffrey Yasskin     Values.clear();
261bfd38abbSJeffrey Yasskin   }
262bfd38abbSJeffrey Yasskin   /// Turn a vector of strings into a nice argv style array of pointers to null
263bfd38abbSJeffrey Yasskin   /// terminated strings.
264bfd38abbSJeffrey Yasskin   void *reset(LLVMContext &C, ExecutionEngine *EE,
265bfd38abbSJeffrey Yasskin               const std::vector<std::string> &InputArgv);
266bfd38abbSJeffrey Yasskin };
267bfd38abbSJeffrey Yasskin }  // anonymous namespace
268bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
2695a0d4829SChris Lattner                        const std::vector<std::string> &InputArgv) {
270bfd38abbSJeffrey Yasskin   clear();  // Free the old contents.
2715da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
272bfd38abbSJeffrey Yasskin   Array = new char[(InputArgv.size()+1)*PtrSize];
2735a0d4829SChris Lattner 
274bfd38abbSJeffrey Yasskin   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
275229907cdSChris Lattner   Type *SBytePtr = Type::getInt8PtrTy(C);
2765a0d4829SChris Lattner 
2775a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
2785a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
2795a0d4829SChris Lattner     char *Dest = new char[Size];
280bfd38abbSJeffrey Yasskin     Values.push_back(Dest);
2810967d2dfSDavid Greene     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
2825a0d4829SChris Lattner 
2835a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
2845a0d4829SChris Lattner     Dest[Size-1] = 0;
2855a0d4829SChris Lattner 
286bfd38abbSJeffrey Yasskin     // Endian safe: Array[i] = (PointerTy)Dest;
287bfd38abbSJeffrey Yasskin     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
2885a0d4829SChris Lattner                            SBytePtr);
2895a0d4829SChris Lattner   }
2905a0d4829SChris Lattner 
2915a0d4829SChris Lattner   // Null terminate it
2925a0d4829SChris Lattner   EE->StoreValueToMemory(PTOGV(0),
293bfd38abbSJeffrey Yasskin                          (GenericValue*)(Array+InputArgv.size()*PtrSize),
2945a0d4829SChris Lattner                          SBytePtr);
295bfd38abbSJeffrey Yasskin   return Array;
2965a0d4829SChris Lattner }
2975a0d4829SChris Lattner 
29841fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
29941fa2bd1SChris Lattner                                                        bool isDtors) {
300faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
3011a9a0b7bSEvan Cheng   GlobalVariable *GV = module->getNamedGlobal(Name);
302fe36eaebSChris Lattner 
303fe36eaebSChris Lattner   // If this global has internal linkage, or if it has a use, then it must be
304fe36eaebSChris Lattner   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
3050621caefSChris Lattner   // this is the case, don't execute any of the global ctors, __main will do
3060621caefSChris Lattner   // it.
3076de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
308faae50b6SChris Lattner 
3090cbfcb2bSNick Lewycky   // Should be an array of '{ i32, void ()* }' structs.  The first value is
3100621caefSChris Lattner   // the init priority, which we ignore.
31100245f42SChris Lattner   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
31200245f42SChris Lattner   if (InitList == 0)
3130f857898SNick Lewycky     return;
314868e3f09SDaniel Dunbar   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
31500245f42SChris Lattner     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
31600245f42SChris Lattner     if (CS == 0) continue;
317faae50b6SChris Lattner 
318faae50b6SChris Lattner     Constant *FP = CS->getOperand(1);
319faae50b6SChris Lattner     if (FP->isNullValue())
3200f857898SNick Lewycky       continue;  // Found a sentinal value, ignore.
321faae50b6SChris Lattner 
322868e3f09SDaniel Dunbar     // Strip off constant expression casts.
323faae50b6SChris Lattner     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
3246c38f0bbSReid Spencer       if (CE->isCast())
325faae50b6SChris Lattner         FP = CE->getOperand(0);
326868e3f09SDaniel Dunbar 
327faae50b6SChris Lattner     // Execute the ctor/dtor function!
328868e3f09SDaniel Dunbar     if (Function *F = dyn_cast<Function>(FP))
329faae50b6SChris Lattner       runFunction(F, std::vector<GenericValue>());
330868e3f09SDaniel Dunbar 
331868e3f09SDaniel Dunbar     // FIXME: It is marginally lame that we just do nothing here if we see an
332868e3f09SDaniel Dunbar     // entry we don't recognize. It might not be unreasonable for the verifier
333868e3f09SDaniel Dunbar     // to not even allow this and just assert here.
334faae50b6SChris Lattner   }
335faae50b6SChris Lattner }
3361a9a0b7bSEvan Cheng 
3371a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
3381a9a0b7bSEvan Cheng   // Execute global ctors/dtors for each module in the program.
339868e3f09SDaniel Dunbar   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
340868e3f09SDaniel Dunbar     runStaticConstructorsDestructors(Modules[i], isDtors);
3410621caefSChris Lattner }
342faae50b6SChris Lattner 
343cf3e3017SDan Gohman #ifndef NDEBUG
3441202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
3451202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
3465da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
3471202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
3481202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
3491202d1b1SDuncan Sands       return false;
3501202d1b1SDuncan Sands   return true;
3511202d1b1SDuncan Sands }
352cf3e3017SDan Gohman #endif
3531202d1b1SDuncan Sands 
3545a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
3555a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
3565a0d4829SChris Lattner                                        const char * const * envp) {
3575a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
3585a0d4829SChris Lattner   GenericValue GVArgc;
35987aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
3608c32c111SAnton Korobeynikov 
3618c32c111SAnton Korobeynikov   // Check main() type
362b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
363229907cdSChris Lattner   FunctionType *FTy = Fn->getFunctionType();
364229907cdSChris Lattner   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
365868e3f09SDaniel Dunbar 
366868e3f09SDaniel Dunbar   // Check the argument types.
367868e3f09SDaniel Dunbar   if (NumArgs > 3)
3682104b8d3SChris Lattner     report_fatal_error("Invalid number of arguments of main() supplied");
369868e3f09SDaniel Dunbar   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
370868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for third argument of main() supplied");
371868e3f09SDaniel Dunbar   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
372868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for second argument of main() supplied");
373868e3f09SDaniel Dunbar   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
374868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for first argument of main() supplied");
375868e3f09SDaniel Dunbar   if (!FTy->getReturnType()->isIntegerTy() &&
376868e3f09SDaniel Dunbar       !FTy->getReturnType()->isVoidTy())
377868e3f09SDaniel Dunbar     report_fatal_error("Invalid return type of main() supplied");
3788c32c111SAnton Korobeynikov 
379bfd38abbSJeffrey Yasskin   ArgvArray CArgv;
380bfd38abbSJeffrey Yasskin   ArgvArray CEnv;
381b1cad0b3SChris Lattner   if (NumArgs) {
3825a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
383b1cad0b3SChris Lattner     if (NumArgs > 1) {
38455f1c09eSOwen Anderson       // Arg #1 = argv.
385bfd38abbSJeffrey Yasskin       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
3861202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
387b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
388b1cad0b3SChris Lattner       if (NumArgs > 2) {
3895a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3905a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
3915a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
39255f1c09eSOwen Anderson         // Arg #2 = envp.
393bfd38abbSJeffrey Yasskin         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
394b1cad0b3SChris Lattner       }
395b1cad0b3SChris Lattner     }
396b1cad0b3SChris Lattner   }
397868e3f09SDaniel Dunbar 
39887aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
3995a0d4829SChris Lattner }
4005a0d4829SChris Lattner 
401091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M,
402603682adSReid Spencer                                          bool ForceInterpreter,
4037ff05bf5SEvan Cheng                                          std::string *ErrorStr,
40470415d97SJeffrey Yasskin                                          CodeGenOpt::Level OptLevel,
40570415d97SJeffrey Yasskin                                          bool GVsWithCode) {
406add6f1d2SOwen Anderson   EngineBuilder EB =  EngineBuilder(M)
407fc8a2d5aSReid Kleckner       .setEngineKind(ForceInterpreter
408fc8a2d5aSReid Kleckner                      ? EngineKind::Interpreter
409fc8a2d5aSReid Kleckner                      : EngineKind::JIT)
410fc8a2d5aSReid Kleckner       .setErrorStr(ErrorStr)
411fc8a2d5aSReid Kleckner       .setOptLevel(OptLevel)
412add6f1d2SOwen Anderson       .setAllocateGVsWithCode(GVsWithCode);
413add6f1d2SOwen Anderson 
414add6f1d2SOwen Anderson   return EB.create();
415fc8a2d5aSReid Kleckner }
4164bd3bd5bSBrian Gaeke 
4170bd34fbdSDylan Noblesmith /// createJIT - This is the factory method for creating a JIT for the current
4180bd34fbdSDylan Noblesmith /// machine, it does not fall back to the interpreter.  This takes ownership
4190bd34fbdSDylan Noblesmith /// of the module.
4200bd34fbdSDylan Noblesmith ExecutionEngine *ExecutionEngine::createJIT(Module *M,
4210bd34fbdSDylan Noblesmith                                             std::string *ErrorStr,
4220bd34fbdSDylan Noblesmith                                             JITMemoryManager *JMM,
42319a58df9SDylan Noblesmith                                             CodeGenOpt::Level OL,
4240bd34fbdSDylan Noblesmith                                             bool GVsWithCode,
4252129f596SEvan Cheng                                             Reloc::Model RM,
4260bd34fbdSDylan Noblesmith                                             CodeModel::Model CMM) {
4270bd34fbdSDylan Noblesmith   if (ExecutionEngine::JITCtor == 0) {
4280bd34fbdSDylan Noblesmith     if (ErrorStr)
4290bd34fbdSDylan Noblesmith       *ErrorStr = "JIT has not been linked in.";
4300bd34fbdSDylan Noblesmith     return 0;
4310bd34fbdSDylan Noblesmith   }
4320bd34fbdSDylan Noblesmith 
4330bd34fbdSDylan Noblesmith   // Use the defaults for extra parameters.  Users can use EngineBuilder to
4340bd34fbdSDylan Noblesmith   // set them.
435add6f1d2SOwen Anderson   EngineBuilder EB(M);
436add6f1d2SOwen Anderson   EB.setEngineKind(EngineKind::JIT);
437add6f1d2SOwen Anderson   EB.setErrorStr(ErrorStr);
438add6f1d2SOwen Anderson   EB.setRelocationModel(RM);
439add6f1d2SOwen Anderson   EB.setCodeModel(CMM);
440add6f1d2SOwen Anderson   EB.setAllocateGVsWithCode(GVsWithCode);
441add6f1d2SOwen Anderson   EB.setOptLevel(OL);
442add6f1d2SOwen Anderson   EB.setJITMemoryManager(JMM);
4430bd34fbdSDylan Noblesmith 
444dff24786SPeter Collingbourne   // TODO: permit custom TargetOptions here
445add6f1d2SOwen Anderson   TargetMachine *TM = EB.selectTarget();
4460bd34fbdSDylan Noblesmith   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
4470bd34fbdSDylan Noblesmith 
4487f26246aSDylan Noblesmith   return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
4490bd34fbdSDylan Noblesmith }
4500bd34fbdSDylan Noblesmith 
451add6f1d2SOwen Anderson ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
45225a3d816SBenjamin Kramer   OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
45325a3d816SBenjamin Kramer 
454a53414fdSNick Lewycky   // Make sure we can resolve symbols in the program as well. The zero arg
455a53414fdSNick Lewycky   // to the function tells DynamicLibrary to load the program, not a library.
456a53414fdSNick Lewycky   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
457a53414fdSNick Lewycky     return 0;
458a53414fdSNick Lewycky 
459*9bc53e84SFilip Pizlo   assert(!(JMM && MCJMM));
460*9bc53e84SFilip Pizlo 
461fc8a2d5aSReid Kleckner   // If the user specified a memory manager but didn't specify which engine to
462fc8a2d5aSReid Kleckner   // create, we assume they only want the JIT, and we fail if they only want
463fc8a2d5aSReid Kleckner   // the interpreter.
464*9bc53e84SFilip Pizlo   if (JMM || MCJMM) {
46541fa2bd1SChris Lattner     if (WhichEngine & EngineKind::JIT)
466fc8a2d5aSReid Kleckner       WhichEngine = EngineKind::JIT;
46741fa2bd1SChris Lattner     else {
4688bcc6445SChris Lattner       if (ErrorStr)
469fc8a2d5aSReid Kleckner         *ErrorStr = "Cannot create an interpreter with a memory manager.";
47041fa2bd1SChris Lattner       return 0;
471fc8a2d5aSReid Kleckner     }
4724bd3bd5bSBrian Gaeke   }
4734bd3bd5bSBrian Gaeke 
474*9bc53e84SFilip Pizlo   if (MCJMM && ! UseMCJIT) {
475*9bc53e84SFilip Pizlo     if (ErrorStr)
476*9bc53e84SFilip Pizlo       *ErrorStr =
477*9bc53e84SFilip Pizlo         "Cannot create a legacy JIT with a runtime dyld memory "
478*9bc53e84SFilip Pizlo         "manager.";
479*9bc53e84SFilip Pizlo     return 0;
480*9bc53e84SFilip Pizlo   }
481*9bc53e84SFilip Pizlo 
482fc8a2d5aSReid Kleckner   // Unless the interpreter was explicitly selected or the JIT is not linked,
483fc8a2d5aSReid Kleckner   // try making a JIT.
48425a3d816SBenjamin Kramer   if ((WhichEngine & EngineKind::JIT) && TheTM) {
4857f26246aSDylan Noblesmith     Triple TT(M->getTargetTriple());
4867f26246aSDylan Noblesmith     if (!TM->getTarget().hasJIT()) {
4877f26246aSDylan Noblesmith       errs() << "WARNING: This target JIT is not designed for the host"
4887f26246aSDylan Noblesmith              << " you are running.  If bad things happen, please choose"
4897f26246aSDylan Noblesmith              << " a different -march switch.\n";
4907f26246aSDylan Noblesmith     }
4917f26246aSDylan Noblesmith 
49270ff8b05SDaniel Dunbar     if (UseMCJIT && ExecutionEngine::MCJITCtor) {
49370ff8b05SDaniel Dunbar       ExecutionEngine *EE =
494*9bc53e84SFilip Pizlo         ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
49525a3d816SBenjamin Kramer                                    AllocateGVsWithCode, TheTM.take());
49670ff8b05SDaniel Dunbar       if (EE) return EE;
49770ff8b05SDaniel Dunbar     } else if (ExecutionEngine::JITCtor) {
49841fa2bd1SChris Lattner       ExecutionEngine *EE =
4997f26246aSDylan Noblesmith         ExecutionEngine::JITCtor(M, ErrorStr, JMM,
50025a3d816SBenjamin Kramer                                  AllocateGVsWithCode, TheTM.take());
50141fa2bd1SChris Lattner       if (EE) return EE;
50241fa2bd1SChris Lattner     }
503fc8a2d5aSReid Kleckner   }
504fc8a2d5aSReid Kleckner 
505fc8a2d5aSReid Kleckner   // If we can't make a JIT and we didn't request one specifically, try making
506fc8a2d5aSReid Kleckner   // an interpreter instead.
50741fa2bd1SChris Lattner   if (WhichEngine & EngineKind::Interpreter) {
50841fa2bd1SChris Lattner     if (ExecutionEngine::InterpCtor)
509091217beSJeffrey Yasskin       return ExecutionEngine::InterpCtor(M, ErrorStr);
5108bcc6445SChris Lattner     if (ErrorStr)
51141fa2bd1SChris Lattner       *ErrorStr = "Interpreter has not been linked in.";
51241fa2bd1SChris Lattner     return 0;
513fc8a2d5aSReid Kleckner   }
514fc8a2d5aSReid Kleckner 
515bea6753fSJim Grosbach   if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
516bea6753fSJim Grosbach       ExecutionEngine::MCJITCtor == 0) {
5178bcc6445SChris Lattner     if (ErrorStr)
5188bcc6445SChris Lattner       *ErrorStr = "JIT has not been linked in.";
5198bcc6445SChris Lattner   }
520868e3f09SDaniel Dunbar 
52141fa2bd1SChris Lattner   return 0;
522b5163bb9SChris Lattner }
523b5163bb9SChris Lattner 
524996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
5251678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
526996fe010SChris Lattner     return getPointerToFunction(F);
527996fe010SChris Lattner 
52879876f52SReid Spencer   MutexGuard locked(lock);
529868e3f09SDaniel Dunbar   if (void *P = EEState.getGlobalAddressMap(locked)[GV])
530868e3f09SDaniel Dunbar     return P;
53169e84901SJeff Cohen 
53269e84901SJeff Cohen   // Global variable might have been added since interpreter started.
53369e84901SJeff Cohen   if (GlobalVariable *GVar =
53469e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
53569e84901SJeff Cohen     EmitGlobalVariable(GVar);
53669e84901SJeff Cohen   else
537fbcc663cSTorok Edwin     llvm_unreachable("Global hasn't had an address allocated yet!");
538868e3f09SDaniel Dunbar 
539d0fc8f80SJeffrey Yasskin   return EEState.getGlobalAddressMap(locked)[GV];
540996fe010SChris Lattner }
541996fe010SChris Lattner 
542868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of
543868e3f09SDaniel Dunbar /// ConstantExpr values.
544996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
5456c38f0bbSReid Spencer   // If its undefined, return the garbage.
546bcbdbfb3SJay Foad   if (isa<UndefValue>(C)) {
547bcbdbfb3SJay Foad     GenericValue Result;
548bcbdbfb3SJay Foad     switch (C->getType()->getTypeID()) {
549be79a7acSNadav Rotem     default:
550be79a7acSNadav Rotem       break;
551bcbdbfb3SJay Foad     case Type::IntegerTyID:
552bcbdbfb3SJay Foad     case Type::X86_FP80TyID:
553bcbdbfb3SJay Foad     case Type::FP128TyID:
554bcbdbfb3SJay Foad     case Type::PPC_FP128TyID:
555bcbdbfb3SJay Foad       // Although the value is undefined, we still have to construct an APInt
556bcbdbfb3SJay Foad       // with the correct bit width.
557bcbdbfb3SJay Foad       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
558bcbdbfb3SJay Foad       break;
559be79a7acSNadav Rotem     case Type::VectorTyID:
560be79a7acSNadav Rotem       // if the whole vector is 'undef' just reserve memory for the value.
561be79a7acSNadav Rotem       const VectorType* VTy = dyn_cast<VectorType>(C->getType());
562be79a7acSNadav Rotem       const Type *ElemTy = VTy->getElementType();
563be79a7acSNadav Rotem       unsigned int elemNum = VTy->getNumElements();
564be79a7acSNadav Rotem       Result.AggregateVal.resize(elemNum);
565be79a7acSNadav Rotem       if (ElemTy->isIntegerTy())
566be79a7acSNadav Rotem         for (unsigned int i = 0; i < elemNum; ++i)
567be79a7acSNadav Rotem           Result.AggregateVal[i].IntVal =
568be79a7acSNadav Rotem             APInt(ElemTy->getPrimitiveSizeInBits(), 0);
569bcbdbfb3SJay Foad       break;
570bcbdbfb3SJay Foad     }
571bcbdbfb3SJay Foad     return Result;
572bcbdbfb3SJay Foad   }
5739de0d14dSChris Lattner 
574868e3f09SDaniel Dunbar   // Otherwise, if the value is a ConstantExpr...
5756c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5764fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
5779de0d14dSChris Lattner     switch (CE->getOpcode()) {
5789de0d14dSChris Lattner     case Instruction::GetElementPtr: {
5796c38f0bbSReid Spencer       // Compute the index
5804fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
581b6ad9822SNuno Lopes       APInt Offset(TD->getPointerSizeInBits(), 0);
582b6ad9822SNuno Lopes       cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
5839de0d14dSChris Lattner 
58487aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
585b6ad9822SNuno Lopes       Result = PTOGV(tmp + Offset.getSExtValue());
5869de0d14dSChris Lattner       return Result;
5879de0d14dSChris Lattner     }
5884fd528f2SReid Spencer     case Instruction::Trunc: {
5894fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5904fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5914fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
5924fd528f2SReid Spencer       return GV;
5934fd528f2SReid Spencer     }
5944fd528f2SReid Spencer     case Instruction::ZExt: {
5954fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5964fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5974fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
5984fd528f2SReid Spencer       return GV;
5994fd528f2SReid Spencer     }
6004fd528f2SReid Spencer     case Instruction::SExt: {
6014fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6024fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
6034fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
6044fd528f2SReid Spencer       return GV;
6054fd528f2SReid Spencer     }
6064fd528f2SReid Spencer     case Instruction::FPTrunc: {
607a1336cf5SDale Johannesen       // FIXME long double
6084fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6094fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
6104fd528f2SReid Spencer       return GV;
6114fd528f2SReid Spencer     }
6124fd528f2SReid Spencer     case Instruction::FPExt:{
613a1336cf5SDale Johannesen       // FIXME long double
6144fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6154fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
6164fd528f2SReid Spencer       return GV;
6174fd528f2SReid Spencer     }
6184fd528f2SReid Spencer     case Instruction::UIToFP: {
6194fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
620fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6214fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
622fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6234fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
624fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
62531920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
626ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
627ca24fd90SDan Gohman                                    false,
6289150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
62954306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
630a1336cf5SDale Johannesen       }
6314fd528f2SReid Spencer       return GV;
6324fd528f2SReid Spencer     }
6334fd528f2SReid Spencer     case Instruction::SIToFP: {
6344fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
635fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6364fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
637fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6384fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
639fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
64031920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
641ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
642ca24fd90SDan Gohman                                    true,
6439150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
64454306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
645a1336cf5SDale Johannesen       }
6464fd528f2SReid Spencer       return GV;
6474fd528f2SReid Spencer     }
6484fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
6494fd528f2SReid Spencer     case Instruction::FPToSI: {
6504fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6514fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
652fdd87907SChris Lattner       if (Op0->getType()->isFloatTy())
6534fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
654fdd87907SChris Lattner       else if (Op0->getType()->isDoubleTy())
6554fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
656fdd87907SChris Lattner       else if (Op0->getType()->isX86_FP80Ty()) {
65729178a34STim Northover         APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
658a1336cf5SDale Johannesen         uint64_t v;
6594f0bd68cSDale Johannesen         bool ignored;
660a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
661a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
6624f0bd68cSDale Johannesen                                    APFloat::rmTowardZero, &ignored);
663a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
664a1336cf5SDale Johannesen       }
6654fd528f2SReid Spencer       return GV;
6664fd528f2SReid Spencer     }
6676c38f0bbSReid Spencer     case Instruction::PtrToInt: {
6684fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
669fc1f2cd3SEli Friedman       uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
670fc1f2cd3SEli Friedman       assert(PtrWidth <= 64 && "Bad pointer width");
6714fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
672fc1f2cd3SEli Friedman       uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
673fc1f2cd3SEli Friedman       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
6744fd528f2SReid Spencer       return GV;
6754fd528f2SReid Spencer     }
6764fd528f2SReid Spencer     case Instruction::IntToPtr: {
6774fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
678bf3eeb2dSMicah Villmow       uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
6794fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
6804fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
6814fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
6826c38f0bbSReid Spencer       return GV;
6836c38f0bbSReid Spencer     }
6846c38f0bbSReid Spencer     case Instruction::BitCast: {
6854fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
686229907cdSChris Lattner       Type* DestTy = CE->getType();
6874fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
688fbcc663cSTorok Edwin         default: llvm_unreachable("Invalid bitcast operand");
6894fd528f2SReid Spencer         case Type::IntegerTyID:
6909dff9becSDuncan Sands           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
691fdd87907SChris Lattner           if (DestTy->isFloatTy())
6924fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
693fdd87907SChris Lattner           else if (DestTy->isDoubleTy())
6944fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
6956c38f0bbSReid Spencer           break;
6964fd528f2SReid Spencer         case Type::FloatTyID:
6979dff9becSDuncan Sands           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
6983447fb01SJay Foad           GV.IntVal = APInt::floatToBits(GV.FloatVal);
6994fd528f2SReid Spencer           break;
7004fd528f2SReid Spencer         case Type::DoubleTyID:
7019dff9becSDuncan Sands           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
7023447fb01SJay Foad           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
7034fd528f2SReid Spencer           break;
7044fd528f2SReid Spencer         case Type::PointerTyID:
70519d0b47bSDuncan Sands           assert(DestTy->isPointerTy() && "Invalid bitcast");
7064fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
7076c38f0bbSReid Spencer       }
7084fd528f2SReid Spencer       return GV;
70968cbcc3eSChris Lattner     }
71068cbcc3eSChris Lattner     case Instruction::Add:
711a5b9645cSDan Gohman     case Instruction::FAdd:
7124fd528f2SReid Spencer     case Instruction::Sub:
713a5b9645cSDan Gohman     case Instruction::FSub:
7144fd528f2SReid Spencer     case Instruction::Mul:
715a5b9645cSDan Gohman     case Instruction::FMul:
7164fd528f2SReid Spencer     case Instruction::UDiv:
7174fd528f2SReid Spencer     case Instruction::SDiv:
7184fd528f2SReid Spencer     case Instruction::URem:
7194fd528f2SReid Spencer     case Instruction::SRem:
7204fd528f2SReid Spencer     case Instruction::And:
7214fd528f2SReid Spencer     case Instruction::Or:
7224fd528f2SReid Spencer     case Instruction::Xor: {
7234fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
7244fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
7254fd528f2SReid Spencer       GenericValue GV;
726c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
727fbcc663cSTorok Edwin       default: llvm_unreachable("Bad add type!");
7287a9c62baSReid Spencer       case Type::IntegerTyID:
7294fd528f2SReid Spencer         switch (CE->getOpcode()) {
730fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid integer opcode");
7314fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
7324fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
7334fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
7344fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
7354fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
7364fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
7374fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
7384fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
7394fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
7404fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
7414fd528f2SReid Spencer         }
742c4e6bb5fSChris Lattner         break;
743c4e6bb5fSChris Lattner       case Type::FloatTyID:
7444fd528f2SReid Spencer         switch (CE->getOpcode()) {
745fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid float opcode");
746a5b9645cSDan Gohman           case Instruction::FAdd:
7474fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
748a5b9645cSDan Gohman           case Instruction::FSub:
7494fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
750a5b9645cSDan Gohman           case Instruction::FMul:
7514fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
7524fd528f2SReid Spencer           case Instruction::FDiv:
7534fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
7544fd528f2SReid Spencer           case Instruction::FRem:
75593cd0f1cSChris Lattner             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
7564fd528f2SReid Spencer         }
757c4e6bb5fSChris Lattner         break;
758c4e6bb5fSChris Lattner       case Type::DoubleTyID:
7594fd528f2SReid Spencer         switch (CE->getOpcode()) {
760fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid double opcode");
761a5b9645cSDan Gohman           case Instruction::FAdd:
7624fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
763a5b9645cSDan Gohman           case Instruction::FSub:
7644fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
765a5b9645cSDan Gohman           case Instruction::FMul:
7664fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
7674fd528f2SReid Spencer           case Instruction::FDiv:
7684fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
7694fd528f2SReid Spencer           case Instruction::FRem:
77093cd0f1cSChris Lattner             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
7714fd528f2SReid Spencer         }
772c4e6bb5fSChris Lattner         break;
773a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
774a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
775a1336cf5SDale Johannesen       case Type::FP128TyID: {
77629178a34STim Northover         const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
77729178a34STim Northover         APFloat apfLHS = APFloat(Sem, LHS.IntVal);
778a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
779e4f47434SDaniel Dunbar           default: llvm_unreachable("Invalid long double opcode");
780a5b9645cSDan Gohman           case Instruction::FAdd:
78129178a34STim Northover             apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
78254306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
783a1336cf5SDale Johannesen             break;
784a5b9645cSDan Gohman           case Instruction::FSub:
78529178a34STim Northover             apfLHS.subtract(APFloat(Sem, RHS.IntVal),
78629178a34STim Northover                             APFloat::rmNearestTiesToEven);
78754306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
788a1336cf5SDale Johannesen             break;
789a5b9645cSDan Gohman           case Instruction::FMul:
79029178a34STim Northover             apfLHS.multiply(APFloat(Sem, RHS.IntVal),
79129178a34STim Northover                             APFloat::rmNearestTiesToEven);
79254306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
793a1336cf5SDale Johannesen             break;
794a1336cf5SDale Johannesen           case Instruction::FDiv:
79529178a34STim Northover             apfLHS.divide(APFloat(Sem, RHS.IntVal),
79629178a34STim Northover                           APFloat::rmNearestTiesToEven);
79754306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
798a1336cf5SDale Johannesen             break;
799a1336cf5SDale Johannesen           case Instruction::FRem:
80029178a34STim Northover             apfLHS.mod(APFloat(Sem, RHS.IntVal),
80129178a34STim Northover                        APFloat::rmNearestTiesToEven);
80254306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
803a1336cf5SDale Johannesen             break;
804a1336cf5SDale Johannesen           }
805a1336cf5SDale Johannesen         }
806a1336cf5SDale Johannesen         break;
807c4e6bb5fSChris Lattner       }
8084fd528f2SReid Spencer       return GV;
8094fd528f2SReid Spencer     }
8109de0d14dSChris Lattner     default:
81168cbcc3eSChris Lattner       break;
81268cbcc3eSChris Lattner     }
813868e3f09SDaniel Dunbar 
814868e3f09SDaniel Dunbar     SmallString<256> Msg;
815868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
816868e3f09SDaniel Dunbar     OS << "ConstantExpr not handled: " << *CE;
817868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
8189de0d14dSChris Lattner   }
819996fe010SChris Lattner 
820868e3f09SDaniel Dunbar   // Otherwise, we have a simple constant.
8214fd528f2SReid Spencer   GenericValue Result;
8226b727599SChris Lattner   switch (C->getType()->getTypeID()) {
82387aa65f4SReid Spencer   case Type::FloatTyID:
824bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
8257a9c62baSReid Spencer     break;
82687aa65f4SReid Spencer   case Type::DoubleTyID:
827bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
82887aa65f4SReid Spencer     break;
829a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
830a1336cf5SDale Johannesen   case Type::FP128TyID:
831a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
83254306fe4SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
833a1336cf5SDale Johannesen     break;
83487aa65f4SReid Spencer   case Type::IntegerTyID:
83587aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
83687aa65f4SReid Spencer     break;
837996fe010SChris Lattner   case Type::PointerTyID:
8386a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
839996fe010SChris Lattner       Result.PointerVal = 0;
8406a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
8416a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
8426a0fd73bSReid Spencer     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
8436a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
8440c778f70SChris Lattner     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
8450c778f70SChris Lattner       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
8460c778f70SChris Lattner                                                         BA->getBasicBlock())));
847e6492f10SChris Lattner     else
848fbcc663cSTorok Edwin       llvm_unreachable("Unknown constant pointer type!");
849996fe010SChris Lattner     break;
850be79a7acSNadav Rotem   case Type::VectorTyID: {
851be79a7acSNadav Rotem     unsigned elemNum;
852be79a7acSNadav Rotem     Type* ElemTy;
853be79a7acSNadav Rotem     const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
854be79a7acSNadav Rotem     const ConstantVector *CV = dyn_cast<ConstantVector>(C);
855be79a7acSNadav Rotem     const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
856be79a7acSNadav Rotem 
857be79a7acSNadav Rotem     if (CDV) {
858be79a7acSNadav Rotem         elemNum = CDV->getNumElements();
859be79a7acSNadav Rotem         ElemTy = CDV->getElementType();
860be79a7acSNadav Rotem     } else if (CV || CAZ) {
861be79a7acSNadav Rotem         VectorType* VTy = dyn_cast<VectorType>(C->getType());
862be79a7acSNadav Rotem         elemNum = VTy->getNumElements();
863be79a7acSNadav Rotem         ElemTy = VTy->getElementType();
864be79a7acSNadav Rotem     } else {
865be79a7acSNadav Rotem         llvm_unreachable("Unknown constant vector type!");
866be79a7acSNadav Rotem     }
867be79a7acSNadav Rotem 
868be79a7acSNadav Rotem     Result.AggregateVal.resize(elemNum);
869be79a7acSNadav Rotem     // Check if vector holds floats.
870be79a7acSNadav Rotem     if(ElemTy->isFloatTy()) {
871be79a7acSNadav Rotem       if (CAZ) {
872be79a7acSNadav Rotem         GenericValue floatZero;
873be79a7acSNadav Rotem         floatZero.FloatVal = 0.f;
874be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
875be79a7acSNadav Rotem                   floatZero);
876be79a7acSNadav Rotem         break;
877be79a7acSNadav Rotem       }
878be79a7acSNadav Rotem       if(CV) {
879be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
880be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
881be79a7acSNadav Rotem             Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
882be79a7acSNadav Rotem               CV->getOperand(i))->getValueAPF().convertToFloat();
883be79a7acSNadav Rotem         break;
884be79a7acSNadav Rotem       }
885be79a7acSNadav Rotem       if(CDV)
886be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
887be79a7acSNadav Rotem           Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
888be79a7acSNadav Rotem 
889be79a7acSNadav Rotem       break;
890be79a7acSNadav Rotem     }
891be79a7acSNadav Rotem     // Check if vector holds doubles.
892be79a7acSNadav Rotem     if (ElemTy->isDoubleTy()) {
893be79a7acSNadav Rotem       if (CAZ) {
894be79a7acSNadav Rotem         GenericValue doubleZero;
895be79a7acSNadav Rotem         doubleZero.DoubleVal = 0.0;
896be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
897be79a7acSNadav Rotem                   doubleZero);
898be79a7acSNadav Rotem         break;
899be79a7acSNadav Rotem       }
900be79a7acSNadav Rotem       if(CV) {
901be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
902be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
903be79a7acSNadav Rotem             Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
904be79a7acSNadav Rotem               CV->getOperand(i))->getValueAPF().convertToDouble();
905be79a7acSNadav Rotem         break;
906be79a7acSNadav Rotem       }
907be79a7acSNadav Rotem       if(CDV)
908be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
909be79a7acSNadav Rotem           Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
910be79a7acSNadav Rotem 
911be79a7acSNadav Rotem       break;
912be79a7acSNadav Rotem     }
913be79a7acSNadav Rotem     // Check if vector holds integers.
914be79a7acSNadav Rotem     if (ElemTy->isIntegerTy()) {
915be79a7acSNadav Rotem       if (CAZ) {
916be79a7acSNadav Rotem         GenericValue intZero;
917be79a7acSNadav Rotem         intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
918be79a7acSNadav Rotem         std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
919be79a7acSNadav Rotem                   intZero);
920be79a7acSNadav Rotem         break;
921be79a7acSNadav Rotem       }
922be79a7acSNadav Rotem       if(CV) {
923be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
924be79a7acSNadav Rotem           if (!isa<UndefValue>(CV->getOperand(i)))
925be79a7acSNadav Rotem             Result.AggregateVal[i].IntVal = cast<ConstantInt>(
926be79a7acSNadav Rotem                                             CV->getOperand(i))->getValue();
927be79a7acSNadav Rotem           else {
928be79a7acSNadav Rotem             Result.AggregateVal[i].IntVal =
929be79a7acSNadav Rotem               APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
930be79a7acSNadav Rotem           }
931be79a7acSNadav Rotem         break;
932be79a7acSNadav Rotem       }
933be79a7acSNadav Rotem       if(CDV)
934be79a7acSNadav Rotem         for (unsigned i = 0; i < elemNum; ++i)
935be79a7acSNadav Rotem           Result.AggregateVal[i].IntVal = APInt(
936be79a7acSNadav Rotem             CDV->getElementType()->getPrimitiveSizeInBits(),
937be79a7acSNadav Rotem             CDV->getElementAsInteger(i));
938be79a7acSNadav Rotem 
939be79a7acSNadav Rotem       break;
940be79a7acSNadav Rotem     }
941be79a7acSNadav Rotem     llvm_unreachable("Unknown constant pointer type!");
942be79a7acSNadav Rotem   }
943be79a7acSNadav Rotem   break;
944be79a7acSNadav Rotem 
945996fe010SChris Lattner   default:
946868e3f09SDaniel Dunbar     SmallString<256> Msg;
947868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
948868e3f09SDaniel Dunbar     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
949868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
950996fe010SChris Lattner   }
951868e3f09SDaniel Dunbar 
952996fe010SChris Lattner   return Result;
953996fe010SChris Lattner }
954996fe010SChris Lattner 
9551202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
9561202d1b1SDuncan Sands /// with the integer held in IntVal.
9571202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
9581202d1b1SDuncan Sands                              unsigned StoreBytes) {
9591202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
960ad06cee2SRoman Divacky   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
9615c65cb46SDuncan Sands 
96241cb64f4SRafael Espindola   if (sys::IsLittleEndianHost) {
9631202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
9641202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
9655c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
966868e3f09SDaniel Dunbar   } else {
9675c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
9681202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
9691202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
9705c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
9715c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
9725c65cb46SDuncan Sands       // May not be aligned so use memcpy.
9735c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
9745c65cb46SDuncan Sands       Src += sizeof(uint64_t);
9755c65cb46SDuncan Sands     }
9765c65cb46SDuncan Sands 
9775c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
978815f8dd2SReid Spencer   }
9797a9c62baSReid Spencer }
9801202d1b1SDuncan Sands 
98109053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
982229907cdSChris Lattner                                          GenericValue *Ptr, Type *Ty) {
983cdfe20b9SMicah Villmow   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
9841202d1b1SDuncan Sands 
9851202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
986be79a7acSNadav Rotem   default:
987be79a7acSNadav Rotem     dbgs() << "Cannot store value of type " << *Ty << "!\n";
988be79a7acSNadav Rotem     break;
9891202d1b1SDuncan Sands   case Type::IntegerTyID:
9901202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
9911202d1b1SDuncan Sands     break;
992996fe010SChris Lattner   case Type::FloatTyID:
99387aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
99487aa65f4SReid Spencer     break;
99587aa65f4SReid Spencer   case Type::DoubleTyID:
99687aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
997996fe010SChris Lattner     break;
9984d7e4ee7SDale Johannesen   case Type::X86_FP80TyID:
9994d7e4ee7SDale Johannesen     memcpy(Ptr, Val.IntVal.getRawData(), 10);
1000a1336cf5SDale Johannesen     break;
10017a9c62baSReid Spencer   case Type::PointerTyID:
10021202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
10031202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
100493da3c82SChandler Carruth       memset(&(Ptr->PointerVal), 0, StoreBytes);
10051202d1b1SDuncan Sands 
100687aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
1007996fe010SChris Lattner     break;
1008be79a7acSNadav Rotem   case Type::VectorTyID:
1009be79a7acSNadav Rotem     for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1010be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1011be79a7acSNadav Rotem         *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1012be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1013be79a7acSNadav Rotem         *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1014be79a7acSNadav Rotem       if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1015be79a7acSNadav Rotem         unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1016be79a7acSNadav Rotem         StoreIntToMemory(Val.AggregateVal[i].IntVal,
1017be79a7acSNadav Rotem           (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1018be79a7acSNadav Rotem       }
1019be79a7acSNadav Rotem     }
1020be79a7acSNadav Rotem     break;
1021996fe010SChris Lattner   }
10221202d1b1SDuncan Sands 
102341cb64f4SRafael Espindola   if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
10241202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
10251202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1026996fe010SChris Lattner }
1027996fe010SChris Lattner 
10281202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
10291202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
10301202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
10311202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
103282b63578SDavid Greene   uint8_t *Dst = reinterpret_cast<uint8_t *>(
103382b63578SDavid Greene                    const_cast<uint64_t *>(IntVal.getRawData()));
10345c65cb46SDuncan Sands 
103541cb64f4SRafael Espindola   if (sys::IsLittleEndianHost)
10365c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
10375c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
10385c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
10395c65cb46SDuncan Sands   else {
10405c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
10415c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
10425c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
10435c65cb46SDuncan Sands     // a word.
10445c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
10455c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
10465c65cb46SDuncan Sands       // May not be aligned so use memcpy.
10475c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
10485c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
10495c65cb46SDuncan Sands     }
10505c65cb46SDuncan Sands 
10515c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
10525c65cb46SDuncan Sands   }
10537a9c62baSReid Spencer }
10541202d1b1SDuncan Sands 
10551202d1b1SDuncan Sands /// FIXME: document
10561202d1b1SDuncan Sands ///
10571202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
10581202d1b1SDuncan Sands                                           GenericValue *Ptr,
1059229907cdSChris Lattner                                           Type *Ty) {
1060cdfe20b9SMicah Villmow   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
10611202d1b1SDuncan Sands 
10621202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
10631202d1b1SDuncan Sands   case Type::IntegerTyID:
10641202d1b1SDuncan Sands     // An APInt with all words initially zero.
10651202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
10661202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
10671202d1b1SDuncan Sands     break;
10687f389e8cSChris Lattner   case Type::FloatTyID:
106987aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
107087aa65f4SReid Spencer     break;
107187aa65f4SReid Spencer   case Type::DoubleTyID:
107287aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
10737f389e8cSChris Lattner     break;
10747a9c62baSReid Spencer   case Type::PointerTyID:
107587aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
10767f389e8cSChris Lattner     break;
1077a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
1078a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
107926d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
1080ff306287SDuncan Sands     uint64_t y[2];
10814d7e4ee7SDale Johannesen     memcpy(y, Ptr, 10);
10827a162881SJeffrey Yasskin     Result.IntVal = APInt(80, y);
1083a1336cf5SDale Johannesen     break;
1084a1336cf5SDale Johannesen   }
1085be79a7acSNadav Rotem   case Type::VectorTyID: {
1086be79a7acSNadav Rotem     const VectorType *VT = cast<VectorType>(Ty);
1087be79a7acSNadav Rotem     const Type *ElemT = VT->getElementType();
1088be79a7acSNadav Rotem     const unsigned numElems = VT->getNumElements();
1089be79a7acSNadav Rotem     if (ElemT->isFloatTy()) {
1090be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems);
1091be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1092be79a7acSNadav Rotem         Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1093be79a7acSNadav Rotem     }
1094be79a7acSNadav Rotem     if (ElemT->isDoubleTy()) {
1095be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems);
1096be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1097be79a7acSNadav Rotem         Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1098be79a7acSNadav Rotem     }
1099be79a7acSNadav Rotem     if (ElemT->isIntegerTy()) {
1100be79a7acSNadav Rotem       GenericValue intZero;
1101be79a7acSNadav Rotem       const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1102be79a7acSNadav Rotem       intZero.IntVal = APInt(elemBitWidth, 0);
1103be79a7acSNadav Rotem       Result.AggregateVal.resize(numElems, intZero);
1104be79a7acSNadav Rotem       for (unsigned i = 0; i < numElems; ++i)
1105be79a7acSNadav Rotem         LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1106be79a7acSNadav Rotem           (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1107be79a7acSNadav Rotem     }
1108be79a7acSNadav Rotem   break;
1109be79a7acSNadav Rotem   }
11107f389e8cSChris Lattner   default:
1111868e3f09SDaniel Dunbar     SmallString<256> Msg;
1112868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
1113868e3f09SDaniel Dunbar     OS << "Cannot load value of type " << *Ty << "!";
1114868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
11157f389e8cSChris Lattner   }
11167f389e8cSChris Lattner }
11177f389e8cSChris Lattner 
1118996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
11190967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
1120b086d382SDale Johannesen   DEBUG(Init->dump());
112100245f42SChris Lattner   if (isa<UndefValue>(Init))
112261753bf8SChris Lattner     return;
112300245f42SChris Lattner 
112400245f42SChris Lattner   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
112569d62138SRobert Bocchino     unsigned ElementSize =
1126cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
112769d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
112869d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
112969d62138SRobert Bocchino     return;
113000245f42SChris Lattner   }
113100245f42SChris Lattner 
113200245f42SChris Lattner   if (isa<ConstantAggregateZero>(Init)) {
1133cdfe20b9SMicah Villmow     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
11341dd86b11SChris Lattner     return;
113500245f42SChris Lattner   }
113600245f42SChris Lattner 
113700245f42SChris Lattner   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
113869ddfbfeSDan Gohman     unsigned ElementSize =
1139cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
114069ddfbfeSDan Gohman     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
114169ddfbfeSDan Gohman       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
114269ddfbfeSDan Gohman     return;
114300245f42SChris Lattner   }
114400245f42SChris Lattner 
114500245f42SChris Lattner   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
114669ddfbfeSDan Gohman     const StructLayout *SL =
1147cdfe20b9SMicah Villmow       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
114869ddfbfeSDan Gohman     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
114969ddfbfeSDan Gohman       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
115069ddfbfeSDan Gohman     return;
115100245f42SChris Lattner   }
115200245f42SChris Lattner 
115300245f42SChris Lattner   if (const ConstantDataSequential *CDS =
115400245f42SChris Lattner                dyn_cast<ConstantDataSequential>(Init)) {
115500245f42SChris Lattner     // CDS is already laid out in host memory order.
115600245f42SChris Lattner     StringRef Data = CDS->getRawDataValues();
115700245f42SChris Lattner     memcpy(Addr, Data.data(), Data.size());
115800245f42SChris Lattner     return;
115900245f42SChris Lattner   }
116000245f42SChris Lattner 
116100245f42SChris Lattner   if (Init->getType()->isFirstClassType()) {
1162996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
1163996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1164996fe010SChris Lattner     return;
1165996fe010SChris Lattner   }
1166996fe010SChris Lattner 
1167868e3f09SDaniel Dunbar   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1168fbcc663cSTorok Edwin   llvm_unreachable("Unknown constant type to initialize memory with!");
1169996fe010SChris Lattner }
1170996fe010SChris Lattner 
1171996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
1172996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
1173996fe010SChris Lattner /// their initializers into the memory.
1174996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
1175996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
11760621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
11770621caefSChris Lattner   // to figure out how the different modules should link together.
1178229907cdSChris Lattner   std::map<std::pair<std::string, Type*>,
11790621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
11800621caefSChris Lattner 
11810621caefSChris Lattner   if (Modules.size() != 1) {
11820621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1183091217beSJeffrey Yasskin       Module &M = *Modules[m];
11840621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
11850621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
11860621caefSChris Lattner         const GlobalValue *GV = I;
11876de96a1bSRafael Espindola         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
11880621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
11890621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
11900621caefSChris Lattner 
11910621caefSChris Lattner         const GlobalValue *&GVEntry =
11920621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
11930621caefSChris Lattner 
11940621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
11950621caefSChris Lattner         // version.
11960621caefSChris Lattner         if (!GVEntry) {
11970621caefSChris Lattner           GVEntry = GV;
11980621caefSChris Lattner           continue;
11990621caefSChris Lattner         }
12000621caefSChris Lattner 
12010621caefSChris Lattner         // If the existing global is strong, never replace it.
1202d61d39ecSAnton Korobeynikov         if (GVEntry->hasExternalLinkage() ||
1203d61d39ecSAnton Korobeynikov             GVEntry->hasDLLImportLinkage() ||
1204d61d39ecSAnton Korobeynikov             GVEntry->hasDLLExportLinkage())
12050621caefSChris Lattner           continue;
12060621caefSChris Lattner 
12070621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1208ce4396bcSDale Johannesen         // symbol.  FIXME is this right for common?
120912c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
12100621caefSChris Lattner           GVEntry = GV;
12110621caefSChris Lattner       }
12120621caefSChris Lattner     }
12130621caefSChris Lattner   }
12140621caefSChris Lattner 
12150621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
12160621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1217091217beSJeffrey Yasskin     Module &M = *Modules[m];
12188ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
12190621caefSChris Lattner          I != E; ++I) {
12200621caefSChris Lattner       // In the multi-module case, see what this global maps to.
12210621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
12220621caefSChris Lattner         if (const GlobalValue *GVEntry =
12230621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
12240621caefSChris Lattner           // If something else is the canonical global, ignore this one.
12250621caefSChris Lattner           if (GVEntry != &*I) {
12260621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
12270621caefSChris Lattner             continue;
12280621caefSChris Lattner           }
12290621caefSChris Lattner         }
12300621caefSChris Lattner       }
12310621caefSChris Lattner 
12325301e7c6SReid Spencer       if (!I->isDeclaration()) {
12335457ce9aSNicolas Geoffray         addGlobalMapping(I, getMemoryForGV(I));
1234996fe010SChris Lattner       } else {
1235e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
1236e8bbcfc2SBrian Gaeke         // get a pointer to it.
12370621caefSChris Lattner         if (void *SymAddr =
12385899e340SDaniel Dunbar             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1239748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
12409de0d14dSChris Lattner         else {
12412104b8d3SChris Lattner           report_fatal_error("Could not resolve external global address: "
12426c2d233eSTorok Edwin                             +I->getName());
12439de0d14dSChris Lattner         }
1244996fe010SChris Lattner       }
12450621caefSChris Lattner     }
12460621caefSChris Lattner 
12470621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
12480621caefSChris Lattner     // canonical location.
12490621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
12500621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
12510621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
12520621caefSChris Lattner         const GlobalValue *CGV =
12530621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
12540621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
12550621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
1256a67f06b9SNuno Lopes         addGlobalMapping(GV, Ptr);
12570621caefSChris Lattner       }
12580621caefSChris Lattner     }
1259996fe010SChris Lattner 
12607a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
12617a9c62baSReid Spencer     // and initialize their contents.
12628ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
12630621caefSChris Lattner          I != E; ++I) {
12645301e7c6SReid Spencer       if (!I->isDeclaration()) {
12650621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
12660621caefSChris Lattner           if (const GlobalValue *GVEntry =
12670621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
12680621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
12690621caefSChris Lattner               continue;
12700621caefSChris Lattner         }
12716bbe3eceSChris Lattner         EmitGlobalVariable(I);
12726bbe3eceSChris Lattner       }
12730621caefSChris Lattner     }
12740621caefSChris Lattner   }
12750621caefSChris Lattner }
12766bbe3eceSChris Lattner 
12776bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
12786bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
12796bbe3eceSChris Lattner // already in the map.
1280fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1281748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
1282dc631735SChris Lattner 
12836bbe3eceSChris Lattner   if (GA == 0) {
12846bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
12855457ce9aSNicolas Geoffray     GA = getMemoryForGV(GV);
1286748e8579SChris Lattner     addGlobalMapping(GV, GA);
12876bbe3eceSChris Lattner   }
1288fbcc0aa1SChris Lattner 
12895457ce9aSNicolas Geoffray   // Don't initialize if it's thread local, let the client do it.
12905457ce9aSNicolas Geoffray   if (!GV->isThreadLocal())
12916bbe3eceSChris Lattner     InitializeMemory(GV->getInitializer(), GA);
12925457ce9aSNicolas Geoffray 
1293229907cdSChris Lattner   Type *ElTy = GV->getType()->getElementType();
1294cdfe20b9SMicah Villmow   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1295df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
12966bbe3eceSChris Lattner   ++NumGlobals;
1297996fe010SChris Lattner }
1298f98e981cSJeffrey Yasskin 
1299d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1300d0fc8f80SJeffrey Yasskin   : EE(EE), GlobalAddressMap(this) {
1301f98e981cSJeffrey Yasskin }
1302f98e981cSJeffrey Yasskin 
1303868e3f09SDaniel Dunbar sys::Mutex *
1304868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1305d0fc8f80SJeffrey Yasskin   return &EES->EE.lock;
1306d0fc8f80SJeffrey Yasskin }
1307868e3f09SDaniel Dunbar 
1308868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1309868e3f09SDaniel Dunbar                                                       const GlobalValue *Old) {
1310d0fc8f80SJeffrey Yasskin   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1311d0fc8f80SJeffrey Yasskin   EES->GlobalAddressReverseMap.erase(OldVal);
1312d0fc8f80SJeffrey Yasskin }
1313d0fc8f80SJeffrey Yasskin 
1314868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1315868e3f09SDaniel Dunbar                                                     const GlobalValue *,
1316868e3f09SDaniel Dunbar                                                     const GlobalValue *) {
1317a2886c21SCraig Topper   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1318f98e981cSJeffrey Yasskin                    " RAUW on a value it has a global mapping for.");
1319f98e981cSJeffrey Yasskin }
1320