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"
17868e3f09SDaniel Dunbar #include "llvm/ADT/SmallString.h"
18390d78b3SChris Lattner #include "llvm/ADT/Statistic.h"
19ed0881b2SChandler Carruth #include "llvm/ExecutionEngine/GenericValue.h"
209fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
219fb823bbSChandler Carruth #include "llvm/IR/DataLayout.h"
229fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
239fb823bbSChandler Carruth #include "llvm/IR/Module.h"
249fb823bbSChandler Carruth #include "llvm/IR/Operator.h"
257c16caa3SReid Spencer #include "llvm/Support/Debug.h"
26ed0881b2SChandler Carruth #include "llvm/Support/DynamicLibrary.h"
276c2d233eSTorok Edwin #include "llvm/Support/ErrorHandling.h"
28ed0881b2SChandler Carruth #include "llvm/Support/Host.h"
296d8dd189SChris Lattner #include "llvm/Support/MutexGuard.h"
30ed0881b2SChandler Carruth #include "llvm/Support/TargetRegistry.h"
316bf87df5SJeffrey Yasskin #include "llvm/Support/ValueHandle.h"
32ccb29cd2STorok Edwin #include "llvm/Support/raw_ostream.h"
338418fdcdSDylan Noblesmith #include "llvm/Target/TargetMachine.h"
34579f0713SAnton Korobeynikov #include <cmath>
35579f0713SAnton Korobeynikov #include <cstring>
3629681deeSChris Lattner using namespace llvm;
37996fe010SChris Lattner 
38c346ecd7SChris Lattner STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
39c346ecd7SChris Lattner STATISTIC(NumGlobals  , "Number of global vars initialized");
40996fe010SChris Lattner 
4131faefffSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::JITCtor)(
4231faefffSJeffrey Yasskin   Module *M,
43fc8a2d5aSReid Kleckner   std::string *ErrorStr,
44fc8a2d5aSReid Kleckner   JITMemoryManager *JMM,
45700d08e1SEric Christopher   bool GVsWithCode,
468418fdcdSDylan Noblesmith   TargetMachine *TM) = 0;
4770ff8b05SDaniel Dunbar ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
4870ff8b05SDaniel Dunbar   Module *M,
4970ff8b05SDaniel Dunbar   std::string *ErrorStr,
5070ff8b05SDaniel Dunbar   JITMemoryManager *JMM,
5170ff8b05SDaniel Dunbar   bool GVsWithCode,
528418fdcdSDylan Noblesmith   TargetMachine *TM) = 0;
53091217beSJeffrey Yasskin ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
54fc8a2d5aSReid Kleckner                                                 std::string *ErrorStr) = 0;
552d52c1b8SChris Lattner 
56091217beSJeffrey Yasskin ExecutionEngine::ExecutionEngine(Module *M)
57f98e981cSJeffrey Yasskin   : EEState(*this),
58abc7901eSDuncan Sands     LazyFunctionCreator(0),
59abc7901eSDuncan Sands     ExceptionTableRegister(0),
60abc7901eSDuncan Sands     ExceptionTableDeregister(0) {
614567db45SJeffrey Yasskin   CompilingLazily         = false;
62cdc0060eSEvan Cheng   GVCompilationDisabled   = false;
6384a9055eSEvan Cheng   SymbolSearchingDisabled = false;
64091217beSJeffrey Yasskin   Modules.push_back(M);
65091217beSJeffrey Yasskin   assert(M && "Module is null?");
66260b0c88SMisha Brukman }
67260b0c88SMisha Brukman 
6892f8b30dSBrian Gaeke ExecutionEngine::~ExecutionEngine() {
69603682adSReid Spencer   clearAllGlobalMappings();
700621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
710621caefSChris Lattner     delete Modules[i];
7292f8b30dSBrian Gaeke }
7392f8b30dSBrian Gaeke 
74abc7901eSDuncan Sands void ExecutionEngine::DeregisterAllTables() {
75abc7901eSDuncan Sands   if (ExceptionTableDeregister) {
76f045b7abSEric Christopher     DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
77f045b7abSEric Christopher     DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
78f045b7abSEric Christopher     for (; it != ite; ++it)
79f045b7abSEric Christopher       ExceptionTableDeregister(it->second);
80abc7901eSDuncan Sands     AllExceptionTables.clear();
81abc7901eSDuncan Sands   }
82abc7901eSDuncan Sands }
83abc7901eSDuncan Sands 
84a4044332SJeffrey Yasskin namespace {
85868e3f09SDaniel Dunbar /// \brief Helper class which uses a value handler to automatically deletes the
86868e3f09SDaniel Dunbar /// memory block when the GlobalVariable is destroyed.
87a4044332SJeffrey Yasskin class GVMemoryBlock : public CallbackVH {
88a4044332SJeffrey Yasskin   GVMemoryBlock(const GlobalVariable *GV)
89a4044332SJeffrey Yasskin     : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
90a4044332SJeffrey Yasskin 
91a4044332SJeffrey Yasskin public:
92868e3f09SDaniel Dunbar   /// \brief Returns the address the GlobalVariable should be written into.  The
93868e3f09SDaniel Dunbar   /// GVMemoryBlock object prefixes that.
94cdfe20b9SMicah Villmow   static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
95229907cdSChris Lattner     Type *ElTy = GV->getType()->getElementType();
96a4044332SJeffrey Yasskin     size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
97a4044332SJeffrey Yasskin     void *RawMemory = ::operator new(
98cdfe20b9SMicah Villmow       DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
99a4044332SJeffrey Yasskin                                    TD.getPreferredAlignment(GV))
100a4044332SJeffrey Yasskin       + GVSize);
101a4044332SJeffrey Yasskin     new(RawMemory) GVMemoryBlock(GV);
102a4044332SJeffrey Yasskin     return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
103a4044332SJeffrey Yasskin   }
104a4044332SJeffrey Yasskin 
105a4044332SJeffrey Yasskin   virtual void deleted() {
106a4044332SJeffrey Yasskin     // We allocated with operator new and with some extra memory hanging off the
107a4044332SJeffrey Yasskin     // end, so don't just delete this.  I'm not sure if this is actually
108a4044332SJeffrey Yasskin     // required.
109a4044332SJeffrey Yasskin     this->~GVMemoryBlock();
110a4044332SJeffrey Yasskin     ::operator delete(this);
111a4044332SJeffrey Yasskin   }
112a4044332SJeffrey Yasskin };
113a4044332SJeffrey Yasskin }  // anonymous namespace
114a4044332SJeffrey Yasskin 
115a4044332SJeffrey Yasskin char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
116cdfe20b9SMicah Villmow   return GVMemoryBlock::Create(GV, *getDataLayout());
1175457ce9aSNicolas Geoffray }
1185457ce9aSNicolas Geoffray 
119091217beSJeffrey Yasskin bool ExecutionEngine::removeModule(Module *M) {
120091217beSJeffrey Yasskin   for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
121324fe890SDevang Patel         E = Modules.end(); I != E; ++I) {
122091217beSJeffrey Yasskin     Module *Found = *I;
123091217beSJeffrey Yasskin     if (Found == M) {
124324fe890SDevang Patel       Modules.erase(I);
125091217beSJeffrey Yasskin       clearGlobalMappingsFromModule(M);
126091217beSJeffrey Yasskin       return true;
127324fe890SDevang Patel     }
128324fe890SDevang Patel   }
129091217beSJeffrey Yasskin   return false;
130617001d8SNate Begeman }
131617001d8SNate Begeman 
1320621caefSChris Lattner Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
1330621caefSChris Lattner   for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
134091217beSJeffrey Yasskin     if (Function *F = Modules[i]->getFunction(FnName))
1350621caefSChris Lattner       return F;
1360621caefSChris Lattner   }
1370621caefSChris Lattner   return 0;
1380621caefSChris Lattner }
1390621caefSChris Lattner 
1400621caefSChris Lattner 
141868e3f09SDaniel Dunbar void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
142868e3f09SDaniel Dunbar                                           const GlobalValue *ToUnmap) {
143d0fc8f80SJeffrey Yasskin   GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
144307c053fSJeffrey Yasskin   void *OldVal;
145868e3f09SDaniel Dunbar 
146868e3f09SDaniel Dunbar   // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
147868e3f09SDaniel Dunbar   // GlobalAddressMap.
148307c053fSJeffrey Yasskin   if (I == GlobalAddressMap.end())
149307c053fSJeffrey Yasskin     OldVal = 0;
150307c053fSJeffrey Yasskin   else {
151307c053fSJeffrey Yasskin     OldVal = I->second;
152307c053fSJeffrey Yasskin     GlobalAddressMap.erase(I);
153307c053fSJeffrey Yasskin   }
154307c053fSJeffrey Yasskin 
155307c053fSJeffrey Yasskin   GlobalAddressReverseMap.erase(OldVal);
156307c053fSJeffrey Yasskin   return OldVal;
157307c053fSJeffrey Yasskin }
158307c053fSJeffrey Yasskin 
1596d8dd189SChris Lattner void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
1606d8dd189SChris Lattner   MutexGuard locked(lock);
1616d8dd189SChris Lattner 
1620967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
1639813b0b0SDaniel Dunbar         << "\' to [" << Addr << "]\n";);
164d0fc8f80SJeffrey Yasskin   void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
1656d8dd189SChris Lattner   assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
1666d8dd189SChris Lattner   CurVal = Addr;
1676d8dd189SChris Lattner 
168868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
169f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
1706bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
171f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
1726d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
1736d8dd189SChris Lattner     V = GV;
1746d8dd189SChris Lattner   }
1756d8dd189SChris Lattner }
1766d8dd189SChris Lattner 
1776d8dd189SChris Lattner void ExecutionEngine::clearAllGlobalMappings() {
1786d8dd189SChris Lattner   MutexGuard locked(lock);
1796d8dd189SChris Lattner 
180f98e981cSJeffrey Yasskin   EEState.getGlobalAddressMap(locked).clear();
181f98e981cSJeffrey Yasskin   EEState.getGlobalAddressReverseMap(locked).clear();
1826d8dd189SChris Lattner }
1836d8dd189SChris Lattner 
1848f83fc4dSNate Begeman void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
1858f83fc4dSNate Begeman   MutexGuard locked(lock);
1868f83fc4dSNate Begeman 
187868e3f09SDaniel Dunbar   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
188f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, FI);
1898f83fc4dSNate Begeman   for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
190868e3f09SDaniel Dunbar        GI != GE; ++GI)
191f98e981cSJeffrey Yasskin     EEState.RemoveMapping(locked, GI);
1928f83fc4dSNate Begeman }
1938f83fc4dSNate Begeman 
194ee181730SChris Lattner void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
1956d8dd189SChris Lattner   MutexGuard locked(lock);
1966d8dd189SChris Lattner 
197d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy &Map =
198f98e981cSJeffrey Yasskin     EEState.getGlobalAddressMap(locked);
199ee181730SChris Lattner 
2006d8dd189SChris Lattner   // Deleting from the mapping?
201868e3f09SDaniel Dunbar   if (Addr == 0)
202f98e981cSJeffrey Yasskin     return EEState.RemoveMapping(locked, GV);
203ee181730SChris Lattner 
204d0fc8f80SJeffrey Yasskin   void *&CurVal = Map[GV];
205ee181730SChris Lattner   void *OldVal = CurVal;
206ee181730SChris Lattner 
207f98e981cSJeffrey Yasskin   if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
208f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
2096d8dd189SChris Lattner   CurVal = Addr;
2106d8dd189SChris Lattner 
211868e3f09SDaniel Dunbar   // If we are using the reverse mapping, add it too.
212f98e981cSJeffrey Yasskin   if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
2136bf87df5SJeffrey Yasskin     AssertingVH<const GlobalValue> &V =
214f98e981cSJeffrey Yasskin       EEState.getGlobalAddressReverseMap(locked)[Addr];
2156d8dd189SChris Lattner     assert((V == 0 || GV == 0) && "GlobalMapping already established!");
2166d8dd189SChris Lattner     V = GV;
2176d8dd189SChris Lattner   }
218ee181730SChris Lattner   return OldVal;
2196d8dd189SChris Lattner }
2206d8dd189SChris Lattner 
2216d8dd189SChris Lattner void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
2226d8dd189SChris Lattner   MutexGuard locked(lock);
2236d8dd189SChris Lattner 
224d0fc8f80SJeffrey Yasskin   ExecutionEngineState::GlobalAddressMapTy::iterator I =
225d0fc8f80SJeffrey Yasskin     EEState.getGlobalAddressMap(locked).find(GV);
226f98e981cSJeffrey Yasskin   return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
2276d8dd189SChris Lattner }
2286d8dd189SChris Lattner 
229748e8579SChris Lattner const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
23079876f52SReid Spencer   MutexGuard locked(lock);
23179876f52SReid Spencer 
232748e8579SChris Lattner   // If we haven't computed the reverse mapping yet, do so first.
233f98e981cSJeffrey Yasskin   if (EEState.getGlobalAddressReverseMap(locked).empty()) {
234d0fc8f80SJeffrey Yasskin     for (ExecutionEngineState::GlobalAddressMapTy::iterator
235f98e981cSJeffrey Yasskin          I = EEState.getGlobalAddressMap(locked).begin(),
236f98e981cSJeffrey Yasskin          E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
237e4f47434SDaniel Dunbar       EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
238e4f47434SDaniel Dunbar                                                           I->second, I->first));
239748e8579SChris Lattner   }
240748e8579SChris Lattner 
2416bf87df5SJeffrey Yasskin   std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
242f98e981cSJeffrey Yasskin     EEState.getGlobalAddressReverseMap(locked).find(Addr);
243f98e981cSJeffrey Yasskin   return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
244748e8579SChris Lattner }
2455a0d4829SChris Lattner 
246bfd38abbSJeffrey Yasskin namespace {
247bfd38abbSJeffrey Yasskin class ArgvArray {
248bfd38abbSJeffrey Yasskin   char *Array;
249bfd38abbSJeffrey Yasskin   std::vector<char*> Values;
250bfd38abbSJeffrey Yasskin public:
251bfd38abbSJeffrey Yasskin   ArgvArray() : Array(NULL) {}
252bfd38abbSJeffrey Yasskin   ~ArgvArray() { clear(); }
253bfd38abbSJeffrey Yasskin   void clear() {
254bfd38abbSJeffrey Yasskin     delete[] Array;
255bfd38abbSJeffrey Yasskin     Array = NULL;
256bfd38abbSJeffrey Yasskin     for (size_t I = 0, E = Values.size(); I != E; ++I) {
257bfd38abbSJeffrey Yasskin       delete[] Values[I];
258bfd38abbSJeffrey Yasskin     }
259bfd38abbSJeffrey Yasskin     Values.clear();
260bfd38abbSJeffrey Yasskin   }
261bfd38abbSJeffrey Yasskin   /// Turn a vector of strings into a nice argv style array of pointers to null
262bfd38abbSJeffrey Yasskin   /// terminated strings.
263bfd38abbSJeffrey Yasskin   void *reset(LLVMContext &C, ExecutionEngine *EE,
264bfd38abbSJeffrey Yasskin               const std::vector<std::string> &InputArgv);
265bfd38abbSJeffrey Yasskin };
266bfd38abbSJeffrey Yasskin }  // anonymous namespace
267bfd38abbSJeffrey Yasskin void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
2685a0d4829SChris Lattner                        const std::vector<std::string> &InputArgv) {
269bfd38abbSJeffrey Yasskin   clear();  // Free the old contents.
2705da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
271bfd38abbSJeffrey Yasskin   Array = new char[(InputArgv.size()+1)*PtrSize];
2725a0d4829SChris Lattner 
273bfd38abbSJeffrey Yasskin   DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
274229907cdSChris Lattner   Type *SBytePtr = Type::getInt8PtrTy(C);
2755a0d4829SChris Lattner 
2765a0d4829SChris Lattner   for (unsigned i = 0; i != InputArgv.size(); ++i) {
2775a0d4829SChris Lattner     unsigned Size = InputArgv[i].size()+1;
2785a0d4829SChris Lattner     char *Dest = new char[Size];
279bfd38abbSJeffrey Yasskin     Values.push_back(Dest);
2800967d2dfSDavid Greene     DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
2815a0d4829SChris Lattner 
2825a0d4829SChris Lattner     std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
2835a0d4829SChris Lattner     Dest[Size-1] = 0;
2845a0d4829SChris Lattner 
285bfd38abbSJeffrey Yasskin     // Endian safe: Array[i] = (PointerTy)Dest;
286bfd38abbSJeffrey Yasskin     EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
2875a0d4829SChris Lattner                            SBytePtr);
2885a0d4829SChris Lattner   }
2895a0d4829SChris Lattner 
2905a0d4829SChris Lattner   // Null terminate it
2915a0d4829SChris Lattner   EE->StoreValueToMemory(PTOGV(0),
292bfd38abbSJeffrey Yasskin                          (GenericValue*)(Array+InputArgv.size()*PtrSize),
2935a0d4829SChris Lattner                          SBytePtr);
294bfd38abbSJeffrey Yasskin   return Array;
2955a0d4829SChris Lattner }
2965a0d4829SChris Lattner 
29741fa2bd1SChris Lattner void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
29841fa2bd1SChris Lattner                                                        bool isDtors) {
299faae50b6SChris Lattner   const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
3001a9a0b7bSEvan Cheng   GlobalVariable *GV = module->getNamedGlobal(Name);
301fe36eaebSChris Lattner 
302fe36eaebSChris Lattner   // If this global has internal linkage, or if it has a use, then it must be
303fe36eaebSChris Lattner   // an old-style (llvmgcc3) static ctor with __main linked in and in use.  If
3040621caefSChris Lattner   // this is the case, don't execute any of the global ctors, __main will do
3050621caefSChris Lattner   // it.
3066de96a1bSRafael Espindola   if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
307faae50b6SChris Lattner 
3080cbfcb2bSNick Lewycky   // Should be an array of '{ i32, void ()* }' structs.  The first value is
3090621caefSChris Lattner   // the init priority, which we ignore.
31000245f42SChris Lattner   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
31100245f42SChris Lattner   if (InitList == 0)
3120f857898SNick Lewycky     return;
313868e3f09SDaniel Dunbar   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
31400245f42SChris Lattner     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
31500245f42SChris Lattner     if (CS == 0) continue;
316faae50b6SChris Lattner 
317faae50b6SChris Lattner     Constant *FP = CS->getOperand(1);
318faae50b6SChris Lattner     if (FP->isNullValue())
3190f857898SNick Lewycky       continue;  // Found a sentinal value, ignore.
320faae50b6SChris Lattner 
321868e3f09SDaniel Dunbar     // Strip off constant expression casts.
322faae50b6SChris Lattner     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
3236c38f0bbSReid Spencer       if (CE->isCast())
324faae50b6SChris Lattner         FP = CE->getOperand(0);
325868e3f09SDaniel Dunbar 
326faae50b6SChris Lattner     // Execute the ctor/dtor function!
327868e3f09SDaniel Dunbar     if (Function *F = dyn_cast<Function>(FP))
328faae50b6SChris Lattner       runFunction(F, std::vector<GenericValue>());
329868e3f09SDaniel Dunbar 
330868e3f09SDaniel Dunbar     // FIXME: It is marginally lame that we just do nothing here if we see an
331868e3f09SDaniel Dunbar     // entry we don't recognize. It might not be unreasonable for the verifier
332868e3f09SDaniel Dunbar     // to not even allow this and just assert here.
333faae50b6SChris Lattner   }
334faae50b6SChris Lattner }
3351a9a0b7bSEvan Cheng 
3361a9a0b7bSEvan Cheng void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
3371a9a0b7bSEvan Cheng   // Execute global ctors/dtors for each module in the program.
338868e3f09SDaniel Dunbar   for (unsigned i = 0, e = Modules.size(); i != e; ++i)
339868e3f09SDaniel Dunbar     runStaticConstructorsDestructors(Modules[i], isDtors);
3400621caefSChris Lattner }
341faae50b6SChris Lattner 
342cf3e3017SDan Gohman #ifndef NDEBUG
3431202d1b1SDuncan Sands /// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
3441202d1b1SDuncan Sands static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
3455da3f051SChandler Carruth   unsigned PtrSize = EE->getDataLayout()->getPointerSize();
3461202d1b1SDuncan Sands   for (unsigned i = 0; i < PtrSize; ++i)
3471202d1b1SDuncan Sands     if (*(i + (uint8_t*)Loc))
3481202d1b1SDuncan Sands       return false;
3491202d1b1SDuncan Sands   return true;
3501202d1b1SDuncan Sands }
351cf3e3017SDan Gohman #endif
3521202d1b1SDuncan Sands 
3535a0d4829SChris Lattner int ExecutionEngine::runFunctionAsMain(Function *Fn,
3545a0d4829SChris Lattner                                        const std::vector<std::string> &argv,
3555a0d4829SChris Lattner                                        const char * const * envp) {
3565a0d4829SChris Lattner   std::vector<GenericValue> GVArgs;
3575a0d4829SChris Lattner   GenericValue GVArgc;
35887aa65f4SReid Spencer   GVArgc.IntVal = APInt(32, argv.size());
3598c32c111SAnton Korobeynikov 
3608c32c111SAnton Korobeynikov   // Check main() type
361b1cad0b3SChris Lattner   unsigned NumArgs = Fn->getFunctionType()->getNumParams();
362229907cdSChris Lattner   FunctionType *FTy = Fn->getFunctionType();
363229907cdSChris Lattner   Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
364868e3f09SDaniel Dunbar 
365868e3f09SDaniel Dunbar   // Check the argument types.
366868e3f09SDaniel Dunbar   if (NumArgs > 3)
3672104b8d3SChris Lattner     report_fatal_error("Invalid number of arguments of main() supplied");
368868e3f09SDaniel Dunbar   if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
369868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for third argument of main() supplied");
370868e3f09SDaniel Dunbar   if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
371868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for second argument of main() supplied");
372868e3f09SDaniel Dunbar   if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
373868e3f09SDaniel Dunbar     report_fatal_error("Invalid type for first argument of main() supplied");
374868e3f09SDaniel Dunbar   if (!FTy->getReturnType()->isIntegerTy() &&
375868e3f09SDaniel Dunbar       !FTy->getReturnType()->isVoidTy())
376868e3f09SDaniel Dunbar     report_fatal_error("Invalid return type of main() supplied");
3778c32c111SAnton Korobeynikov 
378bfd38abbSJeffrey Yasskin   ArgvArray CArgv;
379bfd38abbSJeffrey Yasskin   ArgvArray CEnv;
380b1cad0b3SChris Lattner   if (NumArgs) {
3815a0d4829SChris Lattner     GVArgs.push_back(GVArgc); // Arg #0 = argc.
382b1cad0b3SChris Lattner     if (NumArgs > 1) {
38355f1c09eSOwen Anderson       // Arg #1 = argv.
384bfd38abbSJeffrey Yasskin       GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
3851202d1b1SDuncan Sands       assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
386b1cad0b3SChris Lattner              "argv[0] was null after CreateArgv");
387b1cad0b3SChris Lattner       if (NumArgs > 2) {
3885a0d4829SChris Lattner         std::vector<std::string> EnvVars;
3895a0d4829SChris Lattner         for (unsigned i = 0; envp[i]; ++i)
3905a0d4829SChris Lattner           EnvVars.push_back(envp[i]);
39155f1c09eSOwen Anderson         // Arg #2 = envp.
392bfd38abbSJeffrey Yasskin         GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
393b1cad0b3SChris Lattner       }
394b1cad0b3SChris Lattner     }
395b1cad0b3SChris Lattner   }
396868e3f09SDaniel Dunbar 
39787aa65f4SReid Spencer   return runFunction(Fn, GVArgs).IntVal.getZExtValue();
3985a0d4829SChris Lattner }
3995a0d4829SChris Lattner 
400091217beSJeffrey Yasskin ExecutionEngine *ExecutionEngine::create(Module *M,
401603682adSReid Spencer                                          bool ForceInterpreter,
4027ff05bf5SEvan Cheng                                          std::string *ErrorStr,
40370415d97SJeffrey Yasskin                                          CodeGenOpt::Level OptLevel,
40470415d97SJeffrey Yasskin                                          bool GVsWithCode) {
405add6f1d2SOwen Anderson   EngineBuilder EB =  EngineBuilder(M)
406fc8a2d5aSReid Kleckner       .setEngineKind(ForceInterpreter
407fc8a2d5aSReid Kleckner                      ? EngineKind::Interpreter
408fc8a2d5aSReid Kleckner                      : EngineKind::JIT)
409fc8a2d5aSReid Kleckner       .setErrorStr(ErrorStr)
410fc8a2d5aSReid Kleckner       .setOptLevel(OptLevel)
411add6f1d2SOwen Anderson       .setAllocateGVsWithCode(GVsWithCode);
412add6f1d2SOwen Anderson 
413add6f1d2SOwen Anderson   return EB.create();
414fc8a2d5aSReid Kleckner }
4154bd3bd5bSBrian Gaeke 
4160bd34fbdSDylan Noblesmith /// createJIT - This is the factory method for creating a JIT for the current
4170bd34fbdSDylan Noblesmith /// machine, it does not fall back to the interpreter.  This takes ownership
4180bd34fbdSDylan Noblesmith /// of the module.
4190bd34fbdSDylan Noblesmith ExecutionEngine *ExecutionEngine::createJIT(Module *M,
4200bd34fbdSDylan Noblesmith                                             std::string *ErrorStr,
4210bd34fbdSDylan Noblesmith                                             JITMemoryManager *JMM,
42219a58df9SDylan Noblesmith                                             CodeGenOpt::Level OL,
4230bd34fbdSDylan Noblesmith                                             bool GVsWithCode,
4242129f596SEvan Cheng                                             Reloc::Model RM,
4250bd34fbdSDylan Noblesmith                                             CodeModel::Model CMM) {
4260bd34fbdSDylan Noblesmith   if (ExecutionEngine::JITCtor == 0) {
4270bd34fbdSDylan Noblesmith     if (ErrorStr)
4280bd34fbdSDylan Noblesmith       *ErrorStr = "JIT has not been linked in.";
4290bd34fbdSDylan Noblesmith     return 0;
4300bd34fbdSDylan Noblesmith   }
4310bd34fbdSDylan Noblesmith 
4320bd34fbdSDylan Noblesmith   // Use the defaults for extra parameters.  Users can use EngineBuilder to
4330bd34fbdSDylan Noblesmith   // set them.
434add6f1d2SOwen Anderson   EngineBuilder EB(M);
435add6f1d2SOwen Anderson   EB.setEngineKind(EngineKind::JIT);
436add6f1d2SOwen Anderson   EB.setErrorStr(ErrorStr);
437add6f1d2SOwen Anderson   EB.setRelocationModel(RM);
438add6f1d2SOwen Anderson   EB.setCodeModel(CMM);
439add6f1d2SOwen Anderson   EB.setAllocateGVsWithCode(GVsWithCode);
440add6f1d2SOwen Anderson   EB.setOptLevel(OL);
441add6f1d2SOwen Anderson   EB.setJITMemoryManager(JMM);
4420bd34fbdSDylan Noblesmith 
443dff24786SPeter Collingbourne   // TODO: permit custom TargetOptions here
444add6f1d2SOwen Anderson   TargetMachine *TM = EB.selectTarget();
4450bd34fbdSDylan Noblesmith   if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
4460bd34fbdSDylan Noblesmith 
4477f26246aSDylan Noblesmith   return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
4480bd34fbdSDylan Noblesmith }
4490bd34fbdSDylan Noblesmith 
450add6f1d2SOwen Anderson ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
45125a3d816SBenjamin Kramer   OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
45225a3d816SBenjamin Kramer 
453a53414fdSNick Lewycky   // Make sure we can resolve symbols in the program as well. The zero arg
454a53414fdSNick Lewycky   // to the function tells DynamicLibrary to load the program, not a library.
455a53414fdSNick Lewycky   if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
456a53414fdSNick Lewycky     return 0;
457a53414fdSNick Lewycky 
458fc8a2d5aSReid Kleckner   // If the user specified a memory manager but didn't specify which engine to
459fc8a2d5aSReid Kleckner   // create, we assume they only want the JIT, and we fail if they only want
460fc8a2d5aSReid Kleckner   // the interpreter.
461fc8a2d5aSReid Kleckner   if (JMM) {
46241fa2bd1SChris Lattner     if (WhichEngine & EngineKind::JIT)
463fc8a2d5aSReid Kleckner       WhichEngine = EngineKind::JIT;
46441fa2bd1SChris Lattner     else {
4658bcc6445SChris Lattner       if (ErrorStr)
466fc8a2d5aSReid Kleckner         *ErrorStr = "Cannot create an interpreter with a memory manager.";
46741fa2bd1SChris Lattner       return 0;
468fc8a2d5aSReid Kleckner     }
4694bd3bd5bSBrian Gaeke   }
4704bd3bd5bSBrian Gaeke 
471fc8a2d5aSReid Kleckner   // Unless the interpreter was explicitly selected or the JIT is not linked,
472fc8a2d5aSReid Kleckner   // try making a JIT.
47325a3d816SBenjamin Kramer   if ((WhichEngine & EngineKind::JIT) && TheTM) {
4747f26246aSDylan Noblesmith     Triple TT(M->getTargetTriple());
4757f26246aSDylan Noblesmith     if (!TM->getTarget().hasJIT()) {
4767f26246aSDylan Noblesmith       errs() << "WARNING: This target JIT is not designed for the host"
4777f26246aSDylan Noblesmith              << " you are running.  If bad things happen, please choose"
4787f26246aSDylan Noblesmith              << " a different -march switch.\n";
4797f26246aSDylan Noblesmith     }
4807f26246aSDylan Noblesmith 
48170ff8b05SDaniel Dunbar     if (UseMCJIT && ExecutionEngine::MCJITCtor) {
48270ff8b05SDaniel Dunbar       ExecutionEngine *EE =
4837f26246aSDylan Noblesmith         ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
48425a3d816SBenjamin Kramer                                    AllocateGVsWithCode, TheTM.take());
48570ff8b05SDaniel Dunbar       if (EE) return EE;
48670ff8b05SDaniel Dunbar     } else if (ExecutionEngine::JITCtor) {
48741fa2bd1SChris Lattner       ExecutionEngine *EE =
4887f26246aSDylan Noblesmith         ExecutionEngine::JITCtor(M, ErrorStr, JMM,
48925a3d816SBenjamin Kramer                                  AllocateGVsWithCode, TheTM.take());
49041fa2bd1SChris Lattner       if (EE) return EE;
49141fa2bd1SChris Lattner     }
492fc8a2d5aSReid Kleckner   }
493fc8a2d5aSReid Kleckner 
494fc8a2d5aSReid Kleckner   // If we can't make a JIT and we didn't request one specifically, try making
495fc8a2d5aSReid Kleckner   // an interpreter instead.
49641fa2bd1SChris Lattner   if (WhichEngine & EngineKind::Interpreter) {
49741fa2bd1SChris Lattner     if (ExecutionEngine::InterpCtor)
498091217beSJeffrey Yasskin       return ExecutionEngine::InterpCtor(M, ErrorStr);
4998bcc6445SChris Lattner     if (ErrorStr)
50041fa2bd1SChris Lattner       *ErrorStr = "Interpreter has not been linked in.";
50141fa2bd1SChris Lattner     return 0;
502fc8a2d5aSReid Kleckner   }
503fc8a2d5aSReid Kleckner 
504bea6753fSJim Grosbach   if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
505bea6753fSJim Grosbach       ExecutionEngine::MCJITCtor == 0) {
5068bcc6445SChris Lattner     if (ErrorStr)
5078bcc6445SChris Lattner       *ErrorStr = "JIT has not been linked in.";
5088bcc6445SChris Lattner   }
509868e3f09SDaniel Dunbar 
51041fa2bd1SChris Lattner   return 0;
511b5163bb9SChris Lattner }
512b5163bb9SChris Lattner 
513996fe010SChris Lattner void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
5141678e859SBrian Gaeke   if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
515996fe010SChris Lattner     return getPointerToFunction(F);
516996fe010SChris Lattner 
51779876f52SReid Spencer   MutexGuard locked(lock);
518868e3f09SDaniel Dunbar   if (void *P = EEState.getGlobalAddressMap(locked)[GV])
519868e3f09SDaniel Dunbar     return P;
52069e84901SJeff Cohen 
52169e84901SJeff Cohen   // Global variable might have been added since interpreter started.
52269e84901SJeff Cohen   if (GlobalVariable *GVar =
52369e84901SJeff Cohen           const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
52469e84901SJeff Cohen     EmitGlobalVariable(GVar);
52569e84901SJeff Cohen   else
526fbcc663cSTorok Edwin     llvm_unreachable("Global hasn't had an address allocated yet!");
527868e3f09SDaniel Dunbar 
528d0fc8f80SJeffrey Yasskin   return EEState.getGlobalAddressMap(locked)[GV];
529996fe010SChris Lattner }
530996fe010SChris Lattner 
531868e3f09SDaniel Dunbar /// \brief Converts a Constant* into a GenericValue, including handling of
532868e3f09SDaniel Dunbar /// ConstantExpr values.
533996fe010SChris Lattner GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
5346c38f0bbSReid Spencer   // If its undefined, return the garbage.
535bcbdbfb3SJay Foad   if (isa<UndefValue>(C)) {
536bcbdbfb3SJay Foad     GenericValue Result;
537bcbdbfb3SJay Foad     switch (C->getType()->getTypeID()) {
538bcbdbfb3SJay Foad     case Type::IntegerTyID:
539bcbdbfb3SJay Foad     case Type::X86_FP80TyID:
540bcbdbfb3SJay Foad     case Type::FP128TyID:
541bcbdbfb3SJay Foad     case Type::PPC_FP128TyID:
542bcbdbfb3SJay Foad       // Although the value is undefined, we still have to construct an APInt
543bcbdbfb3SJay Foad       // with the correct bit width.
544bcbdbfb3SJay Foad       Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
545bcbdbfb3SJay Foad       break;
546bcbdbfb3SJay Foad     default:
547bcbdbfb3SJay Foad       break;
548bcbdbfb3SJay Foad     }
549bcbdbfb3SJay Foad     return Result;
550bcbdbfb3SJay Foad   }
5519de0d14dSChris Lattner 
552868e3f09SDaniel Dunbar   // Otherwise, if the value is a ConstantExpr...
5536c38f0bbSReid Spencer   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
5544fd528f2SReid Spencer     Constant *Op0 = CE->getOperand(0);
5559de0d14dSChris Lattner     switch (CE->getOpcode()) {
5569de0d14dSChris Lattner     case Instruction::GetElementPtr: {
5576c38f0bbSReid Spencer       // Compute the index
5584fd528f2SReid Spencer       GenericValue Result = getConstantValue(Op0);
559b6ad9822SNuno Lopes       APInt Offset(TD->getPointerSizeInBits(), 0);
560b6ad9822SNuno Lopes       cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
5619de0d14dSChris Lattner 
56287aa65f4SReid Spencer       char* tmp = (char*) Result.PointerVal;
563b6ad9822SNuno Lopes       Result = PTOGV(tmp + Offset.getSExtValue());
5649de0d14dSChris Lattner       return Result;
5659de0d14dSChris Lattner     }
5664fd528f2SReid Spencer     case Instruction::Trunc: {
5674fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5684fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5694fd528f2SReid Spencer       GV.IntVal = GV.IntVal.trunc(BitWidth);
5704fd528f2SReid Spencer       return GV;
5714fd528f2SReid Spencer     }
5724fd528f2SReid Spencer     case Instruction::ZExt: {
5734fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5744fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5754fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zext(BitWidth);
5764fd528f2SReid Spencer       return GV;
5774fd528f2SReid Spencer     }
5784fd528f2SReid Spencer     case Instruction::SExt: {
5794fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5804fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
5814fd528f2SReid Spencer       GV.IntVal = GV.IntVal.sext(BitWidth);
5824fd528f2SReid Spencer       return GV;
5834fd528f2SReid Spencer     }
5844fd528f2SReid Spencer     case Instruction::FPTrunc: {
585a1336cf5SDale Johannesen       // FIXME long double
5864fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5874fd528f2SReid Spencer       GV.FloatVal = float(GV.DoubleVal);
5884fd528f2SReid Spencer       return GV;
5894fd528f2SReid Spencer     }
5904fd528f2SReid Spencer     case Instruction::FPExt:{
591a1336cf5SDale Johannesen       // FIXME long double
5924fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
5934fd528f2SReid Spencer       GV.DoubleVal = double(GV.FloatVal);
5944fd528f2SReid Spencer       return GV;
5954fd528f2SReid Spencer     }
5964fd528f2SReid Spencer     case Instruction::UIToFP: {
5974fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
598fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
5994fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.roundToDouble());
600fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6014fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.roundToDouble();
602fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
60331920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
604ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
605ca24fd90SDan Gohman                                    false,
6069150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
60754306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
608a1336cf5SDale Johannesen       }
6094fd528f2SReid Spencer       return GV;
6104fd528f2SReid Spencer     }
6114fd528f2SReid Spencer     case Instruction::SIToFP: {
6124fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
613fdd87907SChris Lattner       if (CE->getType()->isFloatTy())
6144fd528f2SReid Spencer         GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
615fdd87907SChris Lattner       else if (CE->getType()->isDoubleTy())
6164fd528f2SReid Spencer         GV.DoubleVal = GV.IntVal.signedRoundToDouble();
617fdd87907SChris Lattner       else if (CE->getType()->isX86_FP80Ty()) {
61831920b0aSBenjamin Kramer         APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
619ca24fd90SDan Gohman         (void)apf.convertFromAPInt(GV.IntVal,
620ca24fd90SDan Gohman                                    true,
6219150652bSDale Johannesen                                    APFloat::rmNearestTiesToEven);
62254306fe4SDale Johannesen         GV.IntVal = apf.bitcastToAPInt();
623a1336cf5SDale Johannesen       }
6244fd528f2SReid Spencer       return GV;
6254fd528f2SReid Spencer     }
6264fd528f2SReid Spencer     case Instruction::FPToUI: // double->APInt conversion handles sign
6274fd528f2SReid Spencer     case Instruction::FPToSI: {
6284fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
6294fd528f2SReid Spencer       uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
630fdd87907SChris Lattner       if (Op0->getType()->isFloatTy())
6314fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
632fdd87907SChris Lattner       else if (Op0->getType()->isDoubleTy())
6334fd528f2SReid Spencer         GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
634fdd87907SChris Lattner       else if (Op0->getType()->isX86_FP80Ty()) {
635a1336cf5SDale Johannesen         APFloat apf = APFloat(GV.IntVal);
636a1336cf5SDale Johannesen         uint64_t v;
6374f0bd68cSDale Johannesen         bool ignored;
638a1336cf5SDale Johannesen         (void)apf.convertToInteger(&v, BitWidth,
639a1336cf5SDale Johannesen                                    CE->getOpcode()==Instruction::FPToSI,
6404f0bd68cSDale Johannesen                                    APFloat::rmTowardZero, &ignored);
641a1336cf5SDale Johannesen         GV.IntVal = v; // endian?
642a1336cf5SDale Johannesen       }
6434fd528f2SReid Spencer       return GV;
6444fd528f2SReid Spencer     }
6456c38f0bbSReid Spencer     case Instruction::PtrToInt: {
6464fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
647fc1f2cd3SEli Friedman       uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
648fc1f2cd3SEli Friedman       assert(PtrWidth <= 64 && "Bad pointer width");
6494fd528f2SReid Spencer       GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
650fc1f2cd3SEli Friedman       uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
651fc1f2cd3SEli Friedman       GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
6524fd528f2SReid Spencer       return GV;
6534fd528f2SReid Spencer     }
6544fd528f2SReid Spencer     case Instruction::IntToPtr: {
6554fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
656bf3eeb2dSMicah Villmow       uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
6574fd528f2SReid Spencer       GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
6584fd528f2SReid Spencer       assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
6594fd528f2SReid Spencer       GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
6606c38f0bbSReid Spencer       return GV;
6616c38f0bbSReid Spencer     }
6626c38f0bbSReid Spencer     case Instruction::BitCast: {
6634fd528f2SReid Spencer       GenericValue GV = getConstantValue(Op0);
664229907cdSChris Lattner       Type* DestTy = CE->getType();
6654fd528f2SReid Spencer       switch (Op0->getType()->getTypeID()) {
666fbcc663cSTorok Edwin         default: llvm_unreachable("Invalid bitcast operand");
6674fd528f2SReid Spencer         case Type::IntegerTyID:
6689dff9becSDuncan Sands           assert(DestTy->isFloatingPointTy() && "invalid bitcast");
669fdd87907SChris Lattner           if (DestTy->isFloatTy())
6704fd528f2SReid Spencer             GV.FloatVal = GV.IntVal.bitsToFloat();
671fdd87907SChris Lattner           else if (DestTy->isDoubleTy())
6724fd528f2SReid Spencer             GV.DoubleVal = GV.IntVal.bitsToDouble();
6736c38f0bbSReid Spencer           break;
6744fd528f2SReid Spencer         case Type::FloatTyID:
6759dff9becSDuncan Sands           assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
6763447fb01SJay Foad           GV.IntVal = APInt::floatToBits(GV.FloatVal);
6774fd528f2SReid Spencer           break;
6784fd528f2SReid Spencer         case Type::DoubleTyID:
6799dff9becSDuncan Sands           assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
6803447fb01SJay Foad           GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
6814fd528f2SReid Spencer           break;
6824fd528f2SReid Spencer         case Type::PointerTyID:
68319d0b47bSDuncan Sands           assert(DestTy->isPointerTy() && "Invalid bitcast");
6844fd528f2SReid Spencer           break; // getConstantValue(Op0)  above already converted it
6856c38f0bbSReid Spencer       }
6864fd528f2SReid Spencer       return GV;
68768cbcc3eSChris Lattner     }
68868cbcc3eSChris Lattner     case Instruction::Add:
689a5b9645cSDan Gohman     case Instruction::FAdd:
6904fd528f2SReid Spencer     case Instruction::Sub:
691a5b9645cSDan Gohman     case Instruction::FSub:
6924fd528f2SReid Spencer     case Instruction::Mul:
693a5b9645cSDan Gohman     case Instruction::FMul:
6944fd528f2SReid Spencer     case Instruction::UDiv:
6954fd528f2SReid Spencer     case Instruction::SDiv:
6964fd528f2SReid Spencer     case Instruction::URem:
6974fd528f2SReid Spencer     case Instruction::SRem:
6984fd528f2SReid Spencer     case Instruction::And:
6994fd528f2SReid Spencer     case Instruction::Or:
7004fd528f2SReid Spencer     case Instruction::Xor: {
7014fd528f2SReid Spencer       GenericValue LHS = getConstantValue(Op0);
7024fd528f2SReid Spencer       GenericValue RHS = getConstantValue(CE->getOperand(1));
7034fd528f2SReid Spencer       GenericValue GV;
704c4e6bb5fSChris Lattner       switch (CE->getOperand(0)->getType()->getTypeID()) {
705fbcc663cSTorok Edwin       default: llvm_unreachable("Bad add type!");
7067a9c62baSReid Spencer       case Type::IntegerTyID:
7074fd528f2SReid Spencer         switch (CE->getOpcode()) {
708fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid integer opcode");
7094fd528f2SReid Spencer           case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
7104fd528f2SReid Spencer           case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
7114fd528f2SReid Spencer           case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
7124fd528f2SReid Spencer           case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
7134fd528f2SReid Spencer           case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
7144fd528f2SReid Spencer           case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
7154fd528f2SReid Spencer           case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
7164fd528f2SReid Spencer           case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
7174fd528f2SReid Spencer           case Instruction::Or:  GV.IntVal = LHS.IntVal | RHS.IntVal; break;
7184fd528f2SReid Spencer           case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
7194fd528f2SReid Spencer         }
720c4e6bb5fSChris Lattner         break;
721c4e6bb5fSChris Lattner       case Type::FloatTyID:
7224fd528f2SReid Spencer         switch (CE->getOpcode()) {
723fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid float opcode");
724a5b9645cSDan Gohman           case Instruction::FAdd:
7254fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
726a5b9645cSDan Gohman           case Instruction::FSub:
7274fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
728a5b9645cSDan Gohman           case Instruction::FMul:
7294fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
7304fd528f2SReid Spencer           case Instruction::FDiv:
7314fd528f2SReid Spencer             GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
7324fd528f2SReid Spencer           case Instruction::FRem:
73393cd0f1cSChris Lattner             GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
7344fd528f2SReid Spencer         }
735c4e6bb5fSChris Lattner         break;
736c4e6bb5fSChris Lattner       case Type::DoubleTyID:
7374fd528f2SReid Spencer         switch (CE->getOpcode()) {
738fbcc663cSTorok Edwin           default: llvm_unreachable("Invalid double opcode");
739a5b9645cSDan Gohman           case Instruction::FAdd:
7404fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
741a5b9645cSDan Gohman           case Instruction::FSub:
7424fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
743a5b9645cSDan Gohman           case Instruction::FMul:
7444fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
7454fd528f2SReid Spencer           case Instruction::FDiv:
7464fd528f2SReid Spencer             GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
7474fd528f2SReid Spencer           case Instruction::FRem:
74893cd0f1cSChris Lattner             GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
7494fd528f2SReid Spencer         }
750c4e6bb5fSChris Lattner         break;
751a1336cf5SDale Johannesen       case Type::X86_FP80TyID:
752a1336cf5SDale Johannesen       case Type::PPC_FP128TyID:
753a1336cf5SDale Johannesen       case Type::FP128TyID: {
754a1336cf5SDale Johannesen         APFloat apfLHS = APFloat(LHS.IntVal);
755a1336cf5SDale Johannesen         switch (CE->getOpcode()) {
756e4f47434SDaniel Dunbar           default: llvm_unreachable("Invalid long double opcode");
757a5b9645cSDan Gohman           case Instruction::FAdd:
758a1336cf5SDale Johannesen             apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
75954306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
760a1336cf5SDale Johannesen             break;
761a5b9645cSDan Gohman           case Instruction::FSub:
762a1336cf5SDale Johannesen             apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
76354306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
764a1336cf5SDale Johannesen             break;
765a5b9645cSDan Gohman           case Instruction::FMul:
766a1336cf5SDale Johannesen             apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
76754306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
768a1336cf5SDale Johannesen             break;
769a1336cf5SDale Johannesen           case Instruction::FDiv:
770a1336cf5SDale Johannesen             apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
77154306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
772a1336cf5SDale Johannesen             break;
773a1336cf5SDale Johannesen           case Instruction::FRem:
774a1336cf5SDale Johannesen             apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
77554306fe4SDale Johannesen             GV.IntVal = apfLHS.bitcastToAPInt();
776a1336cf5SDale Johannesen             break;
777a1336cf5SDale Johannesen           }
778a1336cf5SDale Johannesen         }
779a1336cf5SDale Johannesen         break;
780c4e6bb5fSChris Lattner       }
7814fd528f2SReid Spencer       return GV;
7824fd528f2SReid Spencer     }
7839de0d14dSChris Lattner     default:
78468cbcc3eSChris Lattner       break;
78568cbcc3eSChris Lattner     }
786868e3f09SDaniel Dunbar 
787868e3f09SDaniel Dunbar     SmallString<256> Msg;
788868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
789868e3f09SDaniel Dunbar     OS << "ConstantExpr not handled: " << *CE;
790868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
7919de0d14dSChris Lattner   }
792996fe010SChris Lattner 
793868e3f09SDaniel Dunbar   // Otherwise, we have a simple constant.
7944fd528f2SReid Spencer   GenericValue Result;
7956b727599SChris Lattner   switch (C->getType()->getTypeID()) {
79687aa65f4SReid Spencer   case Type::FloatTyID:
797bed9dc42SDale Johannesen     Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
7987a9c62baSReid Spencer     break;
79987aa65f4SReid Spencer   case Type::DoubleTyID:
800bed9dc42SDale Johannesen     Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
80187aa65f4SReid Spencer     break;
802a1336cf5SDale Johannesen   case Type::X86_FP80TyID:
803a1336cf5SDale Johannesen   case Type::FP128TyID:
804a1336cf5SDale Johannesen   case Type::PPC_FP128TyID:
80554306fe4SDale Johannesen     Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
806a1336cf5SDale Johannesen     break;
80787aa65f4SReid Spencer   case Type::IntegerTyID:
80887aa65f4SReid Spencer     Result.IntVal = cast<ConstantInt>(C)->getValue();
80987aa65f4SReid Spencer     break;
810996fe010SChris Lattner   case Type::PointerTyID:
8116a0fd73bSReid Spencer     if (isa<ConstantPointerNull>(C))
812996fe010SChris Lattner       Result.PointerVal = 0;
8136a0fd73bSReid Spencer     else if (const Function *F = dyn_cast<Function>(C))
8146a0fd73bSReid Spencer       Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
8156a0fd73bSReid Spencer     else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
8166a0fd73bSReid Spencer       Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
8170c778f70SChris Lattner     else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
8180c778f70SChris Lattner       Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
8190c778f70SChris Lattner                                                         BA->getBasicBlock())));
820e6492f10SChris Lattner     else
821fbcc663cSTorok Edwin       llvm_unreachable("Unknown constant pointer type!");
822996fe010SChris Lattner     break;
823996fe010SChris Lattner   default:
824868e3f09SDaniel Dunbar     SmallString<256> Msg;
825868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
826868e3f09SDaniel Dunbar     OS << "ERROR: Constant unimplemented for type: " << *C->getType();
827868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
828996fe010SChris Lattner   }
829868e3f09SDaniel Dunbar 
830996fe010SChris Lattner   return Result;
831996fe010SChris Lattner }
832996fe010SChris Lattner 
8331202d1b1SDuncan Sands /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
8341202d1b1SDuncan Sands /// with the integer held in IntVal.
8351202d1b1SDuncan Sands static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
8361202d1b1SDuncan Sands                              unsigned StoreBytes) {
8371202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
838ad06cee2SRoman Divacky   const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
8395c65cb46SDuncan Sands 
840868e3f09SDaniel Dunbar   if (sys::isLittleEndianHost()) {
8411202d1b1SDuncan Sands     // Little-endian host - the source is ordered from LSB to MSB.  Order the
8421202d1b1SDuncan Sands     // destination from LSB to MSB: Do a straight copy.
8435c65cb46SDuncan Sands     memcpy(Dst, Src, StoreBytes);
844868e3f09SDaniel Dunbar   } else {
8455c65cb46SDuncan Sands     // Big-endian host - the source is an array of 64 bit words ordered from
8461202d1b1SDuncan Sands     // LSW to MSW.  Each word is ordered from MSB to LSB.  Order the destination
8471202d1b1SDuncan Sands     // from MSB to LSB: Reverse the word order, but not the bytes in a word.
8485c65cb46SDuncan Sands     while (StoreBytes > sizeof(uint64_t)) {
8495c65cb46SDuncan Sands       StoreBytes -= sizeof(uint64_t);
8505c65cb46SDuncan Sands       // May not be aligned so use memcpy.
8515c65cb46SDuncan Sands       memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
8525c65cb46SDuncan Sands       Src += sizeof(uint64_t);
8535c65cb46SDuncan Sands     }
8545c65cb46SDuncan Sands 
8555c65cb46SDuncan Sands     memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
856815f8dd2SReid Spencer   }
8577a9c62baSReid Spencer }
8581202d1b1SDuncan Sands 
85909053e62SEvan Cheng void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
860229907cdSChris Lattner                                          GenericValue *Ptr, Type *Ty) {
861cdfe20b9SMicah Villmow   const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
8621202d1b1SDuncan Sands 
8631202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
8641202d1b1SDuncan Sands   case Type::IntegerTyID:
8651202d1b1SDuncan Sands     StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
8661202d1b1SDuncan Sands     break;
867996fe010SChris Lattner   case Type::FloatTyID:
86887aa65f4SReid Spencer     *((float*)Ptr) = Val.FloatVal;
86987aa65f4SReid Spencer     break;
87087aa65f4SReid Spencer   case Type::DoubleTyID:
87187aa65f4SReid Spencer     *((double*)Ptr) = Val.DoubleVal;
872996fe010SChris Lattner     break;
8734d7e4ee7SDale Johannesen   case Type::X86_FP80TyID:
8744d7e4ee7SDale Johannesen     memcpy(Ptr, Val.IntVal.getRawData(), 10);
875a1336cf5SDale Johannesen     break;
8767a9c62baSReid Spencer   case Type::PointerTyID:
8771202d1b1SDuncan Sands     // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
8781202d1b1SDuncan Sands     if (StoreBytes != sizeof(PointerTy))
87993da3c82SChandler Carruth       memset(&(Ptr->PointerVal), 0, StoreBytes);
8801202d1b1SDuncan Sands 
88187aa65f4SReid Spencer     *((PointerTy*)Ptr) = Val.PointerVal;
882996fe010SChris Lattner     break;
883996fe010SChris Lattner   default:
8840967d2dfSDavid Greene     dbgs() << "Cannot store value of type " << *Ty << "!\n";
885996fe010SChris Lattner   }
8861202d1b1SDuncan Sands 
887cdfe20b9SMicah Villmow   if (sys::isLittleEndianHost() != getDataLayout()->isLittleEndian())
8881202d1b1SDuncan Sands     // Host and target are different endian - reverse the stored bytes.
8891202d1b1SDuncan Sands     std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
890996fe010SChris Lattner }
891996fe010SChris Lattner 
8921202d1b1SDuncan Sands /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
8931202d1b1SDuncan Sands /// from Src into IntVal, which is assumed to be wide enough and to hold zero.
8941202d1b1SDuncan Sands static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
8951202d1b1SDuncan Sands   assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
896*82b63578SDavid Greene   uint8_t *Dst = reinterpret_cast<uint8_t *>(
897*82b63578SDavid Greene                    const_cast<uint64_t *>(IntVal.getRawData()));
8985c65cb46SDuncan Sands 
899aa121227SChris Lattner   if (sys::isLittleEndianHost())
9005c65cb46SDuncan Sands     // Little-endian host - the destination must be ordered from LSB to MSB.
9015c65cb46SDuncan Sands     // The source is ordered from LSB to MSB: Do a straight copy.
9025c65cb46SDuncan Sands     memcpy(Dst, Src, LoadBytes);
9035c65cb46SDuncan Sands   else {
9045c65cb46SDuncan Sands     // Big-endian - the destination is an array of 64 bit words ordered from
9055c65cb46SDuncan Sands     // LSW to MSW.  Each word must be ordered from MSB to LSB.  The source is
9065c65cb46SDuncan Sands     // ordered from MSB to LSB: Reverse the word order, but not the bytes in
9075c65cb46SDuncan Sands     // a word.
9085c65cb46SDuncan Sands     while (LoadBytes > sizeof(uint64_t)) {
9095c65cb46SDuncan Sands       LoadBytes -= sizeof(uint64_t);
9105c65cb46SDuncan Sands       // May not be aligned so use memcpy.
9115c65cb46SDuncan Sands       memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
9125c65cb46SDuncan Sands       Dst += sizeof(uint64_t);
9135c65cb46SDuncan Sands     }
9145c65cb46SDuncan Sands 
9155c65cb46SDuncan Sands     memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
9165c65cb46SDuncan Sands   }
9177a9c62baSReid Spencer }
9181202d1b1SDuncan Sands 
9191202d1b1SDuncan Sands /// FIXME: document
9201202d1b1SDuncan Sands ///
9211202d1b1SDuncan Sands void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
9221202d1b1SDuncan Sands                                           GenericValue *Ptr,
923229907cdSChris Lattner                                           Type *Ty) {
924cdfe20b9SMicah Villmow   const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
9251202d1b1SDuncan Sands 
9261202d1b1SDuncan Sands   switch (Ty->getTypeID()) {
9271202d1b1SDuncan Sands   case Type::IntegerTyID:
9281202d1b1SDuncan Sands     // An APInt with all words initially zero.
9291202d1b1SDuncan Sands     Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
9301202d1b1SDuncan Sands     LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
9311202d1b1SDuncan Sands     break;
9327f389e8cSChris Lattner   case Type::FloatTyID:
93387aa65f4SReid Spencer     Result.FloatVal = *((float*)Ptr);
93487aa65f4SReid Spencer     break;
93587aa65f4SReid Spencer   case Type::DoubleTyID:
93687aa65f4SReid Spencer     Result.DoubleVal = *((double*)Ptr);
9377f389e8cSChris Lattner     break;
9387a9c62baSReid Spencer   case Type::PointerTyID:
93987aa65f4SReid Spencer     Result.PointerVal = *((PointerTy*)Ptr);
9407f389e8cSChris Lattner     break;
941a1336cf5SDale Johannesen   case Type::X86_FP80TyID: {
942a1336cf5SDale Johannesen     // This is endian dependent, but it will only work on x86 anyway.
94326d6539eSDuncan Sands     // FIXME: Will not trap if loading a signaling NaN.
944ff306287SDuncan Sands     uint64_t y[2];
9454d7e4ee7SDale Johannesen     memcpy(y, Ptr, 10);
9467a162881SJeffrey Yasskin     Result.IntVal = APInt(80, y);
947a1336cf5SDale Johannesen     break;
948a1336cf5SDale Johannesen   }
9497f389e8cSChris Lattner   default:
950868e3f09SDaniel Dunbar     SmallString<256> Msg;
951868e3f09SDaniel Dunbar     raw_svector_ostream OS(Msg);
952868e3f09SDaniel Dunbar     OS << "Cannot load value of type " << *Ty << "!";
953868e3f09SDaniel Dunbar     report_fatal_error(OS.str());
9547f389e8cSChris Lattner   }
9557f389e8cSChris Lattner }
9567f389e8cSChris Lattner 
957996fe010SChris Lattner void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
9580967d2dfSDavid Greene   DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
959b086d382SDale Johannesen   DEBUG(Init->dump());
96000245f42SChris Lattner   if (isa<UndefValue>(Init))
96161753bf8SChris Lattner     return;
96200245f42SChris Lattner 
96300245f42SChris Lattner   if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
96469d62138SRobert Bocchino     unsigned ElementSize =
965cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
96669d62138SRobert Bocchino     for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
96769d62138SRobert Bocchino       InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
96869d62138SRobert Bocchino     return;
96900245f42SChris Lattner   }
97000245f42SChris Lattner 
97100245f42SChris Lattner   if (isa<ConstantAggregateZero>(Init)) {
972cdfe20b9SMicah Villmow     memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
9731dd86b11SChris Lattner     return;
97400245f42SChris Lattner   }
97500245f42SChris Lattner 
97600245f42SChris Lattner   if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
97769ddfbfeSDan Gohman     unsigned ElementSize =
978cdfe20b9SMicah Villmow       getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
97969ddfbfeSDan Gohman     for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
98069ddfbfeSDan Gohman       InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
98169ddfbfeSDan Gohman     return;
98200245f42SChris Lattner   }
98300245f42SChris Lattner 
98400245f42SChris Lattner   if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
98569ddfbfeSDan Gohman     const StructLayout *SL =
986cdfe20b9SMicah Villmow       getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
98769ddfbfeSDan Gohman     for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
98869ddfbfeSDan Gohman       InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
98969ddfbfeSDan Gohman     return;
99000245f42SChris Lattner   }
99100245f42SChris Lattner 
99200245f42SChris Lattner   if (const ConstantDataSequential *CDS =
99300245f42SChris Lattner                dyn_cast<ConstantDataSequential>(Init)) {
99400245f42SChris Lattner     // CDS is already laid out in host memory order.
99500245f42SChris Lattner     StringRef Data = CDS->getRawDataValues();
99600245f42SChris Lattner     memcpy(Addr, Data.data(), Data.size());
99700245f42SChris Lattner     return;
99800245f42SChris Lattner   }
99900245f42SChris Lattner 
100000245f42SChris Lattner   if (Init->getType()->isFirstClassType()) {
1001996fe010SChris Lattner     GenericValue Val = getConstantValue(Init);
1002996fe010SChris Lattner     StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1003996fe010SChris Lattner     return;
1004996fe010SChris Lattner   }
1005996fe010SChris Lattner 
1006868e3f09SDaniel Dunbar   DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
1007fbcc663cSTorok Edwin   llvm_unreachable("Unknown constant type to initialize memory with!");
1008996fe010SChris Lattner }
1009996fe010SChris Lattner 
1010996fe010SChris Lattner /// EmitGlobals - Emit all of the global variables to memory, storing their
1011996fe010SChris Lattner /// addresses into GlobalAddress.  This must make sure to copy the contents of
1012996fe010SChris Lattner /// their initializers into the memory.
1013996fe010SChris Lattner void ExecutionEngine::emitGlobals() {
1014996fe010SChris Lattner   // Loop over all of the global variables in the program, allocating the memory
10150621caefSChris Lattner   // to hold them.  If there is more than one module, do a prepass over globals
10160621caefSChris Lattner   // to figure out how the different modules should link together.
1017229907cdSChris Lattner   std::map<std::pair<std::string, Type*>,
10180621caefSChris Lattner            const GlobalValue*> LinkedGlobalsMap;
10190621caefSChris Lattner 
10200621caefSChris Lattner   if (Modules.size() != 1) {
10210621caefSChris Lattner     for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1022091217beSJeffrey Yasskin       Module &M = *Modules[m];
10230621caefSChris Lattner       for (Module::const_global_iterator I = M.global_begin(),
10240621caefSChris Lattner            E = M.global_end(); I != E; ++I) {
10250621caefSChris Lattner         const GlobalValue *GV = I;
10266de96a1bSRafael Espindola         if (GV->hasLocalLinkage() || GV->isDeclaration() ||
10270621caefSChris Lattner             GV->hasAppendingLinkage() || !GV->hasName())
10280621caefSChris Lattner           continue;// Ignore external globals and globals with internal linkage.
10290621caefSChris Lattner 
10300621caefSChris Lattner         const GlobalValue *&GVEntry =
10310621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
10320621caefSChris Lattner 
10330621caefSChris Lattner         // If this is the first time we've seen this global, it is the canonical
10340621caefSChris Lattner         // version.
10350621caefSChris Lattner         if (!GVEntry) {
10360621caefSChris Lattner           GVEntry = GV;
10370621caefSChris Lattner           continue;
10380621caefSChris Lattner         }
10390621caefSChris Lattner 
10400621caefSChris Lattner         // If the existing global is strong, never replace it.
1041d61d39ecSAnton Korobeynikov         if (GVEntry->hasExternalLinkage() ||
1042d61d39ecSAnton Korobeynikov             GVEntry->hasDLLImportLinkage() ||
1043d61d39ecSAnton Korobeynikov             GVEntry->hasDLLExportLinkage())
10440621caefSChris Lattner           continue;
10450621caefSChris Lattner 
10460621caefSChris Lattner         // Otherwise, we know it's linkonce/weak, replace it if this is a strong
1047ce4396bcSDale Johannesen         // symbol.  FIXME is this right for common?
104812c94949SAnton Korobeynikov         if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
10490621caefSChris Lattner           GVEntry = GV;
10500621caefSChris Lattner       }
10510621caefSChris Lattner     }
10520621caefSChris Lattner   }
10530621caefSChris Lattner 
10540621caefSChris Lattner   std::vector<const GlobalValue*> NonCanonicalGlobals;
10550621caefSChris Lattner   for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
1056091217beSJeffrey Yasskin     Module &M = *Modules[m];
10578ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
10580621caefSChris Lattner          I != E; ++I) {
10590621caefSChris Lattner       // In the multi-module case, see what this global maps to.
10600621caefSChris Lattner       if (!LinkedGlobalsMap.empty()) {
10610621caefSChris Lattner         if (const GlobalValue *GVEntry =
10620621caefSChris Lattner               LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
10630621caefSChris Lattner           // If something else is the canonical global, ignore this one.
10640621caefSChris Lattner           if (GVEntry != &*I) {
10650621caefSChris Lattner             NonCanonicalGlobals.push_back(I);
10660621caefSChris Lattner             continue;
10670621caefSChris Lattner           }
10680621caefSChris Lattner         }
10690621caefSChris Lattner       }
10700621caefSChris Lattner 
10715301e7c6SReid Spencer       if (!I->isDeclaration()) {
10725457ce9aSNicolas Geoffray         addGlobalMapping(I, getMemoryForGV(I));
1073996fe010SChris Lattner       } else {
1074e8bbcfc2SBrian Gaeke         // External variable reference. Try to use the dynamic loader to
1075e8bbcfc2SBrian Gaeke         // get a pointer to it.
10760621caefSChris Lattner         if (void *SymAddr =
10775899e340SDaniel Dunbar             sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
1078748e8579SChris Lattner           addGlobalMapping(I, SymAddr);
10799de0d14dSChris Lattner         else {
10802104b8d3SChris Lattner           report_fatal_error("Could not resolve external global address: "
10816c2d233eSTorok Edwin                             +I->getName());
10829de0d14dSChris Lattner         }
1083996fe010SChris Lattner       }
10840621caefSChris Lattner     }
10850621caefSChris Lattner 
10860621caefSChris Lattner     // If there are multiple modules, map the non-canonical globals to their
10870621caefSChris Lattner     // canonical location.
10880621caefSChris Lattner     if (!NonCanonicalGlobals.empty()) {
10890621caefSChris Lattner       for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
10900621caefSChris Lattner         const GlobalValue *GV = NonCanonicalGlobals[i];
10910621caefSChris Lattner         const GlobalValue *CGV =
10920621caefSChris Lattner           LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
10930621caefSChris Lattner         void *Ptr = getPointerToGlobalIfAvailable(CGV);
10940621caefSChris Lattner         assert(Ptr && "Canonical global wasn't codegen'd!");
1095a67f06b9SNuno Lopes         addGlobalMapping(GV, Ptr);
10960621caefSChris Lattner       }
10970621caefSChris Lattner     }
1098996fe010SChris Lattner 
10997a9c62baSReid Spencer     // Now that all of the globals are set up in memory, loop through them all
11007a9c62baSReid Spencer     // and initialize their contents.
11018ffb6611SChris Lattner     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
11020621caefSChris Lattner          I != E; ++I) {
11035301e7c6SReid Spencer       if (!I->isDeclaration()) {
11040621caefSChris Lattner         if (!LinkedGlobalsMap.empty()) {
11050621caefSChris Lattner           if (const GlobalValue *GVEntry =
11060621caefSChris Lattner                 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
11070621caefSChris Lattner             if (GVEntry != &*I)  // Not the canonical variable.
11080621caefSChris Lattner               continue;
11090621caefSChris Lattner         }
11106bbe3eceSChris Lattner         EmitGlobalVariable(I);
11116bbe3eceSChris Lattner       }
11120621caefSChris Lattner     }
11130621caefSChris Lattner   }
11140621caefSChris Lattner }
11156bbe3eceSChris Lattner 
11166bbe3eceSChris Lattner // EmitGlobalVariable - This method emits the specified global variable to the
11176bbe3eceSChris Lattner // address specified in GlobalAddresses, or allocates new memory if it's not
11186bbe3eceSChris Lattner // already in the map.
1119fbcc0aa1SChris Lattner void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1120748e8579SChris Lattner   void *GA = getPointerToGlobalIfAvailable(GV);
1121dc631735SChris Lattner 
11226bbe3eceSChris Lattner   if (GA == 0) {
11236bbe3eceSChris Lattner     // If it's not already specified, allocate memory for the global.
11245457ce9aSNicolas Geoffray     GA = getMemoryForGV(GV);
1125748e8579SChris Lattner     addGlobalMapping(GV, GA);
11266bbe3eceSChris Lattner   }
1127fbcc0aa1SChris Lattner 
11285457ce9aSNicolas Geoffray   // Don't initialize if it's thread local, let the client do it.
11295457ce9aSNicolas Geoffray   if (!GV->isThreadLocal())
11306bbe3eceSChris Lattner     InitializeMemory(GV->getInitializer(), GA);
11315457ce9aSNicolas Geoffray 
1132229907cdSChris Lattner   Type *ElTy = GV->getType()->getElementType();
1133cdfe20b9SMicah Villmow   size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
1134df1f1524SChris Lattner   NumInitBytes += (unsigned)GVSize;
11356bbe3eceSChris Lattner   ++NumGlobals;
1136996fe010SChris Lattner }
1137f98e981cSJeffrey Yasskin 
1138d0fc8f80SJeffrey Yasskin ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1139d0fc8f80SJeffrey Yasskin   : EE(EE), GlobalAddressMap(this) {
1140f98e981cSJeffrey Yasskin }
1141f98e981cSJeffrey Yasskin 
1142868e3f09SDaniel Dunbar sys::Mutex *
1143868e3f09SDaniel Dunbar ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
1144d0fc8f80SJeffrey Yasskin   return &EES->EE.lock;
1145d0fc8f80SJeffrey Yasskin }
1146868e3f09SDaniel Dunbar 
1147868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1148868e3f09SDaniel Dunbar                                                       const GlobalValue *Old) {
1149d0fc8f80SJeffrey Yasskin   void *OldVal = EES->GlobalAddressMap.lookup(Old);
1150d0fc8f80SJeffrey Yasskin   EES->GlobalAddressReverseMap.erase(OldVal);
1151d0fc8f80SJeffrey Yasskin }
1152d0fc8f80SJeffrey Yasskin 
1153868e3f09SDaniel Dunbar void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1154868e3f09SDaniel Dunbar                                                     const GlobalValue *,
1155868e3f09SDaniel Dunbar                                                     const GlobalValue *) {
1156a2886c21SCraig Topper   llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1157f98e981cSJeffrey Yasskin                    " RAUW on a value it has a global mapping for.");
1158f98e981cSJeffrey Yasskin }
1159