blob: 7829a2986bbf2d00437a51b22636d2a806de3caa [file] [log] [blame]
Misha Brukman4afac182003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00009//
Chris Lattnerbd199fb2002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/Module.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000023#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Torok Edwin31e24662009-07-07 17:32:34 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000026#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000027#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/raw_ostream.h"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000029#include "llvm/Support/DynamicLibrary.h"
30#include "llvm/Support/Host.h"
Dylan Noblesmith9ea47172011-12-12 04:20:36 +000031#include "llvm/Support/TargetRegistry.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000032#include "llvm/Target/TargetData.h"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000033#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000034#include <cmath>
35#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000036using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000037
Chris Lattner36343732006-12-19 22:43:32 +000038STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
39STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000040
Jeffrey Yasskin46882612010-02-05 16:19:36 +000041ExecutionEngine *(*ExecutionEngine::JITCtor)(
42 Module *M,
43 std::string *ErrorStr,
44 JITMemoryManager *JMM,
Jeffrey Yasskin46882612010-02-05 16:19:36 +000045 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000046 TargetMachine *TM) = 0;
Daniel Dunbar6d135972010-11-17 16:06:37 +000047ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
48 Module *M,
49 std::string *ErrorStr,
50 JITMemoryManager *JMM,
Daniel Dunbar6d135972010-11-17 16:06:37 +000051 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000052 TargetMachine *TM) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000053ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000054 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000055
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000056ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000057 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000058 LazyFunctionCreator(0),
Daniel Dunbar48dd8752010-11-13 02:48:57 +000059 ExceptionTableRegister(0),
Duncan Sandsb35fd442010-10-21 08:57:29 +000060 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000061 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000062 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000063 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000064 Modules.push_back(M);
65 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000066}
67
Brian Gaeke8e539482003-09-04 22:57:27 +000068ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000069 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000070 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
71 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000072}
73
Duncan Sandsb35fd442010-10-21 08:57:29 +000074void ExecutionEngine::DeregisterAllTables() {
75 if (ExceptionTableDeregister) {
Eric Christopher515c67e2011-03-04 23:37:39 +000076 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
77 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
78 for (; it != ite; ++it)
79 ExceptionTableDeregister(it->second);
Duncan Sandsb35fd442010-10-21 08:57:29 +000080 AllExceptionTables.clear();
81 }
82}
83
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000084namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000085/// \brief Helper class which uses a value handler to automatically deletes the
86/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000087class GVMemoryBlock : public CallbackVH {
88 GVMemoryBlock(const GlobalVariable *GV)
89 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
90
91public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000092 /// \brief Returns the address the GlobalVariable should be written into. The
93 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000094 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000095 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000096 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
97 void *RawMemory = ::operator new(
98 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
99 TD.getPreferredAlignment(GV))
100 + GVSize);
101 new(RawMemory) GVMemoryBlock(GV);
102 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
103 }
104
105 virtual void deleted() {
106 // We allocated with operator new and with some extra memory hanging off the
107 // end, so don't just delete this. I'm not sure if this is actually
108 // required.
109 this->~GVMemoryBlock();
110 ::operator delete(this);
111 }
112};
113} // anonymous namespace
114
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000115char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000116 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000117}
118
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000119bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000120 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000121 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000122 Module *Found = *I;
123 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000124 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000125 clearGlobalMappingsFromModule(M);
126 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000127 }
128 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000129 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000130}
131
Chris Lattnerfe854032006-08-16 01:24:12 +0000132Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
133 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000134 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000135 return F;
136 }
137 return 0;
138}
139
140
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000141void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
142 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000143 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000144 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000145
146 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
147 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000148 if (I == GlobalAddressMap.end())
149 OldVal = 0;
150 else {
151 OldVal = I->second;
152 GlobalAddressMap.erase(I);
153 }
154
155 GlobalAddressReverseMap.erase(OldVal);
156 return OldVal;
157}
158
Chris Lattnere7fd5532006-05-08 22:00:52 +0000159void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
160 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000161
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000162 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000163 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000164 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000165 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
166 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000167
168 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000169 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000170 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000171 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000172 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
173 V = GV;
174 }
175}
176
Chris Lattnere7fd5532006-05-08 22:00:52 +0000177void ExecutionEngine::clearAllGlobalMappings() {
178 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000179
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000180 EEState.getGlobalAddressMap(locked).clear();
181 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000182}
183
Nate Begemanf049e072008-05-21 16:34:48 +0000184void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
185 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000186
187 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000188 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000189 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
190 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000191 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000192}
193
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000194void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000195 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000196
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000197 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000198 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000199
Chris Lattnere7fd5532006-05-08 22:00:52 +0000200 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000201 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000202 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000203
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000204 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000205 void *OldVal = CurVal;
206
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000207 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
208 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000209 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000210
211 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000212 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000213 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000214 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000215 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
216 V = GV;
217 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000218 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000219}
220
Chris Lattnere7fd5532006-05-08 22:00:52 +0000221void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
222 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000223
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000224 ExecutionEngineState::GlobalAddressMapTy::iterator I =
225 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000226 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000227}
228
Chris Lattner55d86482003-12-31 20:21:04 +0000229const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000230 MutexGuard locked(lock);
231
Chris Lattner55d86482003-12-31 20:21:04 +0000232 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000233 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000234 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000235 I = EEState.getGlobalAddressMap(locked).begin(),
236 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000237 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
238 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000239 }
240
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000241 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000242 EEState.getGlobalAddressReverseMap(locked).find(Addr);
243 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000244}
Chris Lattner87f03102003-12-26 06:50:30 +0000245
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000246namespace {
247class ArgvArray {
248 char *Array;
249 std::vector<char*> Values;
250public:
251 ArgvArray() : Array(NULL) {}
252 ~ArgvArray() { clear(); }
253 void clear() {
254 delete[] Array;
255 Array = NULL;
256 for (size_t I = 0, E = Values.size(); I != E; ++I) {
257 delete[] Values[I];
258 }
259 Values.clear();
260 }
261 /// Turn a vector of strings into a nice argv style array of pointers to null
262 /// terminated strings.
263 void *reset(LLVMContext &C, ExecutionEngine *EE,
264 const std::vector<std::string> &InputArgv);
265};
266} // anonymous namespace
267void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
268 const std::vector<std::string> &InputArgv) {
269 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000270 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000271 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000272
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000273 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000274 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000275
276 for (unsigned i = 0; i != InputArgv.size(); ++i) {
277 unsigned Size = InputArgv[i].size()+1;
278 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000279 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000280 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000281
Chris Lattner87f03102003-12-26 06:50:30 +0000282 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
283 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000284
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000285 // Endian safe: Array[i] = (PointerTy)Dest;
286 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000287 SBytePtr);
288 }
289
290 // Null terminate it
291 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000292 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000293 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000294 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000295}
296
Chris Lattnerfbd39762009-09-23 01:46:04 +0000297void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
298 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000299 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000300 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000301
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000302 // If this global has internal linkage, or if it has a use, then it must be
303 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
304 // this is the case, don't execute any of the global ctors, __main will do
305 // it.
306 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
307
Nick Lewyckya040d472011-04-06 20:38:44 +0000308 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000309 // the init priority, which we ignore.
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000310 if (isa<ConstantAggregateZero>(GV->getInitializer()))
311 return;
Nick Lewycky2c44a802011-04-08 07:30:21 +0000312 ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000313 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000314 if (isa<ConstantAggregateZero>(InitList->getOperand(i)))
315 continue;
Nick Lewycky2c44a802011-04-08 07:30:21 +0000316 ConstantStruct *CS = cast<ConstantStruct>(InitList->getOperand(i));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000317
318 Constant *FP = CS->getOperand(1);
319 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000320 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000321
322 // Strip off constant expression casts.
323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
324 if (CE->isCast())
325 FP = CE->getOperand(0);
326
327 // Execute the ctor/dtor function!
328 if (Function *F = dyn_cast<Function>(FP))
329 runFunction(F, std::vector<GenericValue>());
330
331 // FIXME: It is marginally lame that we just do nothing here if we see an
332 // entry we don't recognize. It might not be unreasonable for the verifier
333 // to not even allow this and just assert here.
334 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000335}
336
Evan Cheng18314dc2008-09-30 15:51:21 +0000337void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
338 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000339 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
340 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000341}
342
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000343#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000344/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
345static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
346 unsigned PtrSize = EE->getTargetData()->getPointerSize();
347 for (unsigned i = 0; i < PtrSize; ++i)
348 if (*(i + (uint8_t*)Loc))
349 return false;
350 return true;
351}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000352#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000353
Chris Lattner87f03102003-12-26 06:50:30 +0000354int ExecutionEngine::runFunctionAsMain(Function *Fn,
355 const std::vector<std::string> &argv,
356 const char * const * envp) {
357 std::vector<GenericValue> GVArgs;
358 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000359 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000360
361 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000362 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000363 FunctionType *FTy = Fn->getFunctionType();
364 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000365
366 // Check the argument types.
367 if (NumArgs > 3)
368 report_fatal_error("Invalid number of arguments of main() supplied");
369 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
370 report_fatal_error("Invalid type for third argument of main() supplied");
371 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
372 report_fatal_error("Invalid type for second argument of main() supplied");
373 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
374 report_fatal_error("Invalid type for first argument of main() supplied");
375 if (!FTy->getReturnType()->isIntegerTy() &&
376 !FTy->getReturnType()->isVoidTy())
377 report_fatal_error("Invalid return type of main() supplied");
378
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000379 ArgvArray CArgv;
380 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000381 if (NumArgs) {
382 GVArgs.push_back(GVArgc); // Arg #0 = argc.
383 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000384 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000385 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000386 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000387 "argv[0] was null after CreateArgv");
388 if (NumArgs > 2) {
389 std::vector<std::string> EnvVars;
390 for (unsigned i = 0; envp[i]; ++i)
391 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000392 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000393 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000394 }
395 }
396 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000397
Reid Spencer8fb0f192007-03-06 03:04:04 +0000398 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000399}
400
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000401ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000402 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000403 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000404 CodeGenOpt::Level OptLevel,
405 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000406 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000407 .setEngineKind(ForceInterpreter
408 ? EngineKind::Interpreter
409 : EngineKind::JIT)
410 .setErrorStr(ErrorStr)
411 .setOptLevel(OptLevel)
412 .setAllocateGVsWithCode(GVsWithCode)
413 .create();
414}
Brian Gaeke82d82772003-09-03 20:34:19 +0000415
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000416/// createJIT - This is the factory method for creating a JIT for the current
417/// machine, it does not fall back to the interpreter. This takes ownership
418/// of the module.
419ExecutionEngine *ExecutionEngine::createJIT(Module *M,
420 std::string *ErrorStr,
421 JITMemoryManager *JMM,
Dylan Noblesmithd95e67d2011-12-01 21:49:21 +0000422 CodeGenOpt::Level OL,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000423 bool GVsWithCode,
Evan Cheng43966132011-07-19 06:37:02 +0000424 Reloc::Model RM,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000425 CodeModel::Model CMM) {
426 if (ExecutionEngine::JITCtor == 0) {
427 if (ErrorStr)
428 *ErrorStr = "JIT has not been linked in.";
429 return 0;
430 }
431
432 // Use the defaults for extra parameters. Users can use EngineBuilder to
433 // set them.
434 StringRef MArch = "";
435 StringRef MCPU = "";
436 SmallVector<std::string, 1> MAttrs;
437
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000438 Triple TT(M->getTargetTriple());
Peter Collingbourned40e1032011-12-07 23:58:57 +0000439 // TODO: permit custom TargetOptions here
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000440 TargetMachine *TM =
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000441 EngineBuilder::selectTarget(TT, MArch, MCPU, MAttrs, TargetOptions(), RM,
Peter Collingbourned40e1032011-12-07 23:58:57 +0000442 CMM, OL, ErrorStr);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000443 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000444
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000445 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000446}
447
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000448ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000449 // Make sure we can resolve symbols in the program as well. The zero arg
450 // to the function tells DynamicLibrary to load the program, not a library.
451 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
452 return 0;
453
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000454 // If the user specified a memory manager but didn't specify which engine to
455 // create, we assume they only want the JIT, and we fail if they only want
456 // the interpreter.
457 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000458 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000459 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000460 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000461 if (ErrorStr)
462 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000463 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000464 }
465 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000466
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000467 // Unless the interpreter was explicitly selected or the JIT is not linked,
468 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000469 if (WhichEngine & EngineKind::JIT) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000470 Triple TT(M->getTargetTriple());
471 if (TargetMachine *TM = EngineBuilder::selectTarget(TT, MArch, MCPU, MAttrs,
Peter Collingbourned40e1032011-12-07 23:58:57 +0000472 Options,
Evan Cheng34ad6db2011-07-20 07:51:56 +0000473 RelocModel, CMModel,
Dylan Noblesmithd95e67d2011-12-01 21:49:21 +0000474 OptLevel, ErrorStr)) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000475 if (!TM->getTarget().hasJIT()) {
476 errs() << "WARNING: This target JIT is not designed for the host"
477 << " you are running. If bad things happen, please choose"
478 << " a different -march switch.\n";
479 }
480
Dylan Noblesmithc5b28582011-05-13 21:51:29 +0000481 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
482 ExecutionEngine *EE =
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000483 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +0000484 AllocateGVsWithCode, TM);
485 if (EE) return EE;
486 } else if (ExecutionEngine::JITCtor) {
487 ExecutionEngine *EE =
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000488 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +0000489 AllocateGVsWithCode, TM);
490 if (EE) return EE;
491 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000492 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000493 }
494
495 // If we can't make a JIT and we didn't request one specifically, try making
496 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000497 if (WhichEngine & EngineKind::Interpreter) {
498 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000499 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000500 if (ErrorStr)
501 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000502 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000503 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000504
505 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
506 if (ErrorStr)
507 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000508 }
509
Chris Lattnerfbd39762009-09-23 01:46:04 +0000510 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000511}
512
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000513void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000514 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000515 return getPointerToFunction(F);
516
Reid Spenceree448632005-07-12 15:51:55 +0000517 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000518 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
519 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000520
521 // Global variable might have been added since interpreter started.
522 if (GlobalVariable *GVar =
523 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
524 EmitGlobalVariable(GVar);
525 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000526 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000527
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000528 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000529}
530
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000531/// \brief Converts a Constant* into a GenericValue, including handling of
532/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000533GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000534 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000535 if (isa<UndefValue>(C)) {
536 GenericValue Result;
537 switch (C->getType()->getTypeID()) {
538 case Type::IntegerTyID:
539 case Type::X86_FP80TyID:
540 case Type::FP128TyID:
541 case Type::PPC_FP128TyID:
542 // Although the value is undefined, we still have to construct an APInt
543 // with the correct bit width.
544 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
545 break;
546 default:
547 break;
548 }
549 return Result;
550 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000551
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000552 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000553 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000554 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000555 switch (CE->getOpcode()) {
556 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000557 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000558 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000559 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +0000560 uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000561
Reid Spencer8fb0f192007-03-06 03:04:04 +0000562 char* tmp = (char*) Result.PointerVal;
563 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000564 return Result;
565 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000566 case Instruction::Trunc: {
567 GenericValue GV = getConstantValue(Op0);
568 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
569 GV.IntVal = GV.IntVal.trunc(BitWidth);
570 return GV;
571 }
572 case Instruction::ZExt: {
573 GenericValue GV = getConstantValue(Op0);
574 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
575 GV.IntVal = GV.IntVal.zext(BitWidth);
576 return GV;
577 }
578 case Instruction::SExt: {
579 GenericValue GV = getConstantValue(Op0);
580 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
581 GV.IntVal = GV.IntVal.sext(BitWidth);
582 return GV;
583 }
584 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000585 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000586 GenericValue GV = getConstantValue(Op0);
587 GV.FloatVal = float(GV.DoubleVal);
588 return GV;
589 }
590 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000591 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000592 GenericValue GV = getConstantValue(Op0);
593 GV.DoubleVal = double(GV.FloatVal);
594 return GV;
595 }
596 case Instruction::UIToFP: {
597 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000598 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000599 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000600 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000601 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000602 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000603 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000604 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000605 false,
606 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000607 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000608 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000609 return GV;
610 }
611 case Instruction::SIToFP: {
612 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000613 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000614 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000615 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000616 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000617 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000618 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000619 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000620 true,
621 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000622 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000623 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000624 return GV;
625 }
626 case Instruction::FPToUI: // double->APInt conversion handles sign
627 case Instruction::FPToSI: {
628 GenericValue GV = getConstantValue(Op0);
629 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000630 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000631 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000632 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000633 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000634 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000635 APFloat apf = APFloat(GV.IntVal);
636 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000637 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000638 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000639 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000640 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000641 GV.IntVal = v; // endian?
642 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000643 return GV;
644 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000645 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000646 GenericValue GV = getConstantValue(Op0);
647 uint32_t PtrWidth = TD->getPointerSizeInBits();
648 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
649 return GV;
650 }
651 case Instruction::IntToPtr: {
652 GenericValue GV = getConstantValue(Op0);
653 uint32_t PtrWidth = TD->getPointerSizeInBits();
654 if (PtrWidth != GV.IntVal.getBitWidth())
655 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
656 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
657 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000658 return GV;
659 }
660 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000661 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000662 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000664 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000665 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000666 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000667 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000668 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000669 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000670 GV.DoubleVal = GV.IntVal.bitsToDouble();
671 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000672 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000673 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000674 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000675 break;
676 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000677 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000678 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000679 break;
680 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000681 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000682 break; // getConstantValue(Op0) above already converted it
683 }
684 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000685 }
Chris Lattner9a231222003-05-14 17:51:49 +0000686 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000687 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000688 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000689 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000690 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000691 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000692 case Instruction::UDiv:
693 case Instruction::SDiv:
694 case Instruction::URem:
695 case Instruction::SRem:
696 case Instruction::And:
697 case Instruction::Or:
698 case Instruction::Xor: {
699 GenericValue LHS = getConstantValue(Op0);
700 GenericValue RHS = getConstantValue(CE->getOperand(1));
701 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000702 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000703 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000704 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000705 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000706 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000707 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
708 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
709 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
710 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
711 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
712 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
713 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
714 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
715 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
716 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
717 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000718 break;
719 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000720 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000721 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000722 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000723 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000724 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000725 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000726 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000727 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000728 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000729 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000730 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000731 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000732 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000733 break;
734 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000735 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000736 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000737 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000738 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000739 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000740 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000741 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000742 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000743 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000744 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000745 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000746 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000747 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000748 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000749 case Type::X86_FP80TyID:
750 case Type::PPC_FP128TyID:
751 case Type::FP128TyID: {
752 APFloat apfLHS = APFloat(LHS.IntVal);
753 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000754 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000755 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000756 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000757 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000758 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000759 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000760 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000761 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000762 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000763 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000764 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000765 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000766 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000767 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000768 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000769 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000770 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000771 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000772 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000773 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000774 break;
775 }
776 }
777 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000778 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000779 return GV;
780 }
Chris Lattner9a231222003-05-14 17:51:49 +0000781 default:
782 break;
783 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000784
785 SmallString<256> Msg;
786 raw_svector_ostream OS(Msg);
787 OS << "ConstantExpr not handled: " << *CE;
788 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000789 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000790
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000791 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000792 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000793 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000794 case Type::FloatTyID:
795 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000796 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000797 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000798 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000799 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000800 case Type::X86_FP80TyID:
801 case Type::FP128TyID:
802 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000803 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000804 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000805 case Type::IntegerTyID:
806 Result.IntVal = cast<ConstantInt>(C)->getValue();
807 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000808 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000809 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000810 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000811 else if (const Function *F = dyn_cast<Function>(C))
812 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000813 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000814 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000815 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
816 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
817 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000818 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000819 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000820 break;
821 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000822 SmallString<256> Msg;
823 raw_svector_ostream OS(Msg);
824 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
825 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000826 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000827
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000828 return Result;
829}
830
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000831/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
832/// with the integer held in IntVal.
833static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
834 unsigned StoreBytes) {
835 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
836 uint8_t *Src = (uint8_t *)IntVal.getRawData();
837
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000838 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000839 // Little-endian host - the source is ordered from LSB to MSB. Order the
840 // destination from LSB to MSB: Do a straight copy.
841 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000842 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000843 // Big-endian host - the source is an array of 64 bit words ordered from
844 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
845 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
846 while (StoreBytes > sizeof(uint64_t)) {
847 StoreBytes -= sizeof(uint64_t);
848 // May not be aligned so use memcpy.
849 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
850 Src += sizeof(uint64_t);
851 }
852
853 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
854 }
855}
856
Evan Cheng89687e32008-11-04 06:10:31 +0000857void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000858 GenericValue *Ptr, Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000859 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
860
Reid Spencer8fb0f192007-03-06 03:04:04 +0000861 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000862 case Type::IntegerTyID:
863 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000864 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000865 case Type::FloatTyID:
866 *((float*)Ptr) = Val.FloatVal;
867 break;
868 case Type::DoubleTyID:
869 *((double*)Ptr) = Val.DoubleVal;
870 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000871 case Type::X86_FP80TyID:
872 memcpy(Ptr, Val.IntVal.getRawData(), 10);
873 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000874 case Type::PointerTyID:
875 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
876 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +0000877 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000878
Reid Spencer8fb0f192007-03-06 03:04:04 +0000879 *((PointerTy*)Ptr) = Val.PointerVal;
880 break;
881 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000882 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000883 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000884
Chris Lattnerb67c9582009-01-22 19:53:00 +0000885 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000886 // Host and target are different endian - reverse the stored bytes.
887 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
888}
889
890/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
891/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
892static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
893 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
894 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
895
Chris Lattnerb67c9582009-01-22 19:53:00 +0000896 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000897 // Little-endian host - the destination must be ordered from LSB to MSB.
898 // The source is ordered from LSB to MSB: Do a straight copy.
899 memcpy(Dst, Src, LoadBytes);
900 else {
901 // Big-endian - the destination is an array of 64 bit words ordered from
902 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
903 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
904 // a word.
905 while (LoadBytes > sizeof(uint64_t)) {
906 LoadBytes -= sizeof(uint64_t);
907 // May not be aligned so use memcpy.
908 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
909 Dst += sizeof(uint64_t);
910 }
911
912 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
913 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000914}
915
Misha Brukman4afac182003-10-10 17:45:12 +0000916/// FIXME: document
917///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000918void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000919 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000920 Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000921 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000922
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000923 switch (Ty->getTypeID()) {
924 case Type::IntegerTyID:
925 // An APInt with all words initially zero.
926 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
927 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
928 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000929 case Type::FloatTyID:
930 Result.FloatVal = *((float*)Ptr);
931 break;
932 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000933 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000934 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000935 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000936 Result.PointerVal = *((PointerTy*)Ptr);
937 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000938 case Type::X86_FP80TyID: {
939 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000940 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000941 uint64_t y[2];
942 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +0000943 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000944 break;
945 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000946 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000947 SmallString<256> Msg;
948 raw_svector_ostream OS(Msg);
949 OS << "Cannot load value of type " << *Ty << "!";
950 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000951 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000952}
953
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000954void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000955 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000956 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000957 if (isa<UndefValue>(Init)) {
958 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000959 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000960 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000961 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000962 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
963 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
964 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000965 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000966 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000967 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000968 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
969 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000970 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000971 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
972 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
973 return;
974 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
975 const StructLayout *SL =
976 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
977 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
978 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
979 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000980 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000981 GenericValue Val = getConstantValue(Init);
982 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
983 return;
984 }
985
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000986 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +0000987 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000988}
989
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000990/// EmitGlobals - Emit all of the global variables to memory, storing their
991/// addresses into GlobalAddress. This must make sure to copy the contents of
992/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000993void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000994 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000995 // to hold them. If there is more than one module, do a prepass over globals
996 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000997 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +0000998 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000999
Chris Lattnerfe854032006-08-16 01:24:12 +00001000 if (Modules.size() != 1) {
1001 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001002 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001003 for (Module::const_global_iterator I = M.global_begin(),
1004 E = M.global_end(); I != E; ++I) {
1005 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001006 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +00001007 GV->hasAppendingLinkage() || !GV->hasName())
1008 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001009
1010 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001011 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1012
1013 // If this is the first time we've seen this global, it is the canonical
1014 // version.
1015 if (!GVEntry) {
1016 GVEntry = GV;
1017 continue;
1018 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001019
Chris Lattnerfe854032006-08-16 01:24:12 +00001020 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001021 if (GVEntry->hasExternalLinkage() ||
1022 GVEntry->hasDLLImportLinkage() ||
1023 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001024 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001025
Chris Lattnerfe854032006-08-16 01:24:12 +00001026 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001027 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001028 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001029 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001030 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001031 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001032 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001033
Chris Lattnerfe854032006-08-16 01:24:12 +00001034 std::vector<const GlobalValue*> NonCanonicalGlobals;
1035 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001036 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001037 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1038 I != E; ++I) {
1039 // In the multi-module case, see what this global maps to.
1040 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001041 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001042 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1043 // If something else is the canonical global, ignore this one.
1044 if (GVEntry != &*I) {
1045 NonCanonicalGlobals.push_back(I);
1046 continue;
1047 }
1048 }
1049 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001050
Reid Spencer5cbf9852007-01-30 20:08:39 +00001051 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001052 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001053 } else {
1054 // External variable reference. Try to use the dynamic loader to
1055 // get a pointer to it.
1056 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001057 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001058 addGlobalMapping(I, SymAddr);
1059 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001060 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001061 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001062 }
1063 }
1064 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001065
Chris Lattnerfe854032006-08-16 01:24:12 +00001066 // If there are multiple modules, map the non-canonical globals to their
1067 // canonical location.
1068 if (!NonCanonicalGlobals.empty()) {
1069 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1070 const GlobalValue *GV = NonCanonicalGlobals[i];
1071 const GlobalValue *CGV =
1072 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1073 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1074 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001075 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001076 }
1077 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001078
1079 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001080 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001081 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1082 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001083 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001084 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001085 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001086 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1087 if (GVEntry != &*I) // Not the canonical variable.
1088 continue;
1089 }
1090 EmitGlobalVariable(I);
1091 }
1092 }
1093 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001094}
1095
1096// EmitGlobalVariable - This method emits the specified global variable to the
1097// address specified in GlobalAddresses, or allocates new memory if it's not
1098// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001099void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001100 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001101
Chris Lattner24b0a182003-12-20 02:45:37 +00001102 if (GA == 0) {
1103 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001104 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001105 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001106 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001107
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001108 // Don't initialize if it's thread local, let the client do it.
1109 if (!GV->isThreadLocal())
1110 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001111
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001112 Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001113 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001114 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001115 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001116}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001117
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001118ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1119 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001120}
1121
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001122sys::Mutex *
1123ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001124 return &EES->EE.lock;
1125}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001126
1127void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1128 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001129 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1130 EES->GlobalAddressReverseMap.erase(OldVal);
1131}
1132
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001133void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1134 const GlobalValue *,
1135 const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001136 assert(false && "The ExecutionEngine doesn't know how to handle a"
1137 " RAUW on a value it has a global mapping for.");
1138}