blob: e43ba4f1dd02c54752f36c3f7f1ea101adb649bd [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"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000017#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/ExecutionEngine/GenericValue.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Module.h"
24#include "llvm/IR/Operator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/Support/DynamicLibrary.h"
Torok Edwin31e24662009-07-07 17:32:34 +000027#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/Support/Host.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000029#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Support/TargetRegistry.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000031#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000032#include "llvm/Support/raw_ostream.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.
Micah Villmow3574eca2012-10-08 16:38:25 +000094 static char *Create(const GlobalVariable *GV, const DataLayout& 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(
Micah Villmow3574eca2012-10-08 16:38:25 +000098 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000099 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) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000116 return GVMemoryBlock::Create(GV, *getDataLayout());
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.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000270 unsigned PtrSize = EE->getDataLayout()->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.
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000310 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
311 if (InitList == 0)
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000312 return;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000313 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000314 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
315 if (CS == 0) continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000316
317 Constant *FP = CS->getOperand(1);
318 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000319 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000320
321 // Strip off constant expression casts.
322 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
323 if (CE->isCast())
324 FP = CE->getOperand(0);
325
326 // Execute the ctor/dtor function!
327 if (Function *F = dyn_cast<Function>(FP))
328 runFunction(F, std::vector<GenericValue>());
329
330 // FIXME: It is marginally lame that we just do nothing here if we see an
331 // entry we don't recognize. It might not be unreasonable for the verifier
332 // to not even allow this and just assert here.
333 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000334}
335
Evan Cheng18314dc2008-09-30 15:51:21 +0000336void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
337 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000338 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
339 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000340}
341
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000342#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000343/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
344static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000345 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000346 for (unsigned i = 0; i < PtrSize; ++i)
347 if (*(i + (uint8_t*)Loc))
348 return false;
349 return true;
350}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000351#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000352
Chris Lattner87f03102003-12-26 06:50:30 +0000353int ExecutionEngine::runFunctionAsMain(Function *Fn,
354 const std::vector<std::string> &argv,
355 const char * const * envp) {
356 std::vector<GenericValue> GVArgs;
357 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000358 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000359
360 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000361 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000362 FunctionType *FTy = Fn->getFunctionType();
363 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000364
365 // Check the argument types.
366 if (NumArgs > 3)
367 report_fatal_error("Invalid number of arguments of main() supplied");
368 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
369 report_fatal_error("Invalid type for third argument of main() supplied");
370 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
371 report_fatal_error("Invalid type for second argument of main() supplied");
372 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
373 report_fatal_error("Invalid type for first argument of main() supplied");
374 if (!FTy->getReturnType()->isIntegerTy() &&
375 !FTy->getReturnType()->isVoidTy())
376 report_fatal_error("Invalid return type of main() supplied");
377
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000378 ArgvArray CArgv;
379 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000380 if (NumArgs) {
381 GVArgs.push_back(GVArgc); // Arg #0 = argc.
382 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000383 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000384 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000385 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000386 "argv[0] was null after CreateArgv");
387 if (NumArgs > 2) {
388 std::vector<std::string> EnvVars;
389 for (unsigned i = 0; envp[i]; ++i)
390 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000391 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000392 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000393 }
394 }
395 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000396
Reid Spencer8fb0f192007-03-06 03:04:04 +0000397 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000398}
399
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000400ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000401 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000402 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000403 CodeGenOpt::Level OptLevel,
404 bool GVsWithCode) {
Owen Anderson8e1fc562012-03-23 17:40:56 +0000405 EngineBuilder EB = EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000406 .setEngineKind(ForceInterpreter
407 ? EngineKind::Interpreter
408 : EngineKind::JIT)
409 .setErrorStr(ErrorStr)
410 .setOptLevel(OptLevel)
Owen Anderson8e1fc562012-03-23 17:40:56 +0000411 .setAllocateGVsWithCode(GVsWithCode);
412
413 return EB.create();
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000414}
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.
Owen Anderson8e1fc562012-03-23 17:40:56 +0000434 EngineBuilder EB(M);
435 EB.setEngineKind(EngineKind::JIT);
436 EB.setErrorStr(ErrorStr);
437 EB.setRelocationModel(RM);
438 EB.setCodeModel(CMM);
439 EB.setAllocateGVsWithCode(GVsWithCode);
440 EB.setOptLevel(OL);
441 EB.setJITMemoryManager(JMM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000442
Peter Collingbourned40e1032011-12-07 23:58:57 +0000443 // TODO: permit custom TargetOptions here
Owen Anderson8e1fc562012-03-23 17:40:56 +0000444 TargetMachine *TM = EB.selectTarget();
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000445 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000446
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000447 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000448}
449
Owen Anderson8e1fc562012-03-23 17:40:56 +0000450ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Benjamin Kramer0f554492012-04-08 14:53:14 +0000451 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
452
Nick Lewycky6456d862008-03-08 02:49:45 +0000453 // Make sure we can resolve symbols in the program as well. The zero arg
454 // to the function tells DynamicLibrary to load the program, not a library.
455 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
456 return 0;
457
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000458 // If the user specified a memory manager but didn't specify which engine to
459 // create, we assume they only want the JIT, and we fail if they only want
460 // the interpreter.
461 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000462 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000463 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000464 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000465 if (ErrorStr)
466 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000467 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000468 }
469 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000470
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000471 // Unless the interpreter was explicitly selected or the JIT is not linked,
472 // try making a JIT.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000473 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000474 Triple TT(M->getTargetTriple());
Owen Anderson8e1fc562012-03-23 17:40:56 +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 }
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000480
Owen Anderson8e1fc562012-03-23 17:40:56 +0000481 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
482 ExecutionEngine *EE =
483 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
Benjamin Kramer0f554492012-04-08 14:53:14 +0000484 AllocateGVsWithCode, TheTM.take());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000485 if (EE) return EE;
486 } else if (ExecutionEngine::JITCtor) {
487 ExecutionEngine *EE =
488 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
Benjamin Kramer0f554492012-04-08 14:53:14 +0000489 AllocateGVsWithCode, TheTM.take());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000490 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000491 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000492 }
493
494 // If we can't make a JIT and we didn't request one specifically, try making
495 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000496 if (WhichEngine & EngineKind::Interpreter) {
497 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000498 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000499 if (ErrorStr)
500 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000501 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000502 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000503
Jim Grosbach8005bcd2012-08-21 15:42:49 +0000504 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
505 ExecutionEngine::MCJITCtor == 0) {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000506 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()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000538 default:
539 break;
Jay Foad5b370122010-01-15 08:32:58 +0000540 case Type::IntegerTyID:
541 case Type::X86_FP80TyID:
542 case Type::FP128TyID:
543 case Type::PPC_FP128TyID:
544 // Although the value is undefined, we still have to construct an APInt
545 // with the correct bit width.
546 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
547 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000548 case Type::VectorTyID:
549 // if the whole vector is 'undef' just reserve memory for the value.
550 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
551 const Type *ElemTy = VTy->getElementType();
552 unsigned int elemNum = VTy->getNumElements();
553 Result.AggregateVal.resize(elemNum);
554 if (ElemTy->isIntegerTy())
555 for (unsigned int i = 0; i < elemNum; ++i)
556 Result.AggregateVal[i].IntVal =
557 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foad5b370122010-01-15 08:32:58 +0000558 break;
559 }
560 return Result;
561 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000562
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000563 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000564 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000565 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000566 switch (CE->getOpcode()) {
567 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000568 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000569 GenericValue Result = getConstantValue(Op0);
Nuno Lopes98281a22012-12-30 16:25:48 +0000570 APInt Offset(TD->getPointerSizeInBits(), 0);
571 cast<GEPOperator>(CE)->accumulateConstantOffset(*TD, Offset);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000572
Reid Spencer8fb0f192007-03-06 03:04:04 +0000573 char* tmp = (char*) Result.PointerVal;
Nuno Lopes98281a22012-12-30 16:25:48 +0000574 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000575 return Result;
576 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000577 case Instruction::Trunc: {
578 GenericValue GV = getConstantValue(Op0);
579 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
580 GV.IntVal = GV.IntVal.trunc(BitWidth);
581 return GV;
582 }
583 case Instruction::ZExt: {
584 GenericValue GV = getConstantValue(Op0);
585 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
586 GV.IntVal = GV.IntVal.zext(BitWidth);
587 return GV;
588 }
589 case Instruction::SExt: {
590 GenericValue GV = getConstantValue(Op0);
591 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
592 GV.IntVal = GV.IntVal.sext(BitWidth);
593 return GV;
594 }
595 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000596 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000597 GenericValue GV = getConstantValue(Op0);
598 GV.FloatVal = float(GV.DoubleVal);
599 return GV;
600 }
601 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000602 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000603 GenericValue GV = getConstantValue(Op0);
604 GV.DoubleVal = double(GV.FloatVal);
605 return GV;
606 }
607 case Instruction::UIToFP: {
608 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000609 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000610 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000611 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000612 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000613 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000614 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000615 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000616 false,
617 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000618 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000619 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000620 return GV;
621 }
622 case Instruction::SIToFP: {
623 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000624 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000625 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000626 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000627 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000628 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000629 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000630 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000631 true,
632 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000633 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000634 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000635 return GV;
636 }
637 case Instruction::FPToUI: // double->APInt conversion handles sign
638 case Instruction::FPToSI: {
639 GenericValue GV = getConstantValue(Op0);
640 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000641 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000642 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000643 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000644 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000645 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover0a29cb02013-01-22 09:46:31 +0000646 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000647 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000648 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000649 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000650 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000651 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000652 GV.IntVal = v; // endian?
653 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000654 return GV;
655 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000656 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000657 GenericValue GV = getConstantValue(Op0);
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000658 uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
659 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencerbce30f12007-03-06 22:23:15 +0000660 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000661 uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
662 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 return GV;
664 }
665 case Instruction::IntToPtr: {
666 GenericValue GV = getConstantValue(Op0);
Micah Villmowb52fb872012-10-24 18:36:13 +0000667 uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000668 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000669 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
670 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000671 return GV;
672 }
673 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000674 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000675 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000676 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000677 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000678 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000679 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000680 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000681 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000682 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000683 GV.DoubleVal = GV.IntVal.bitsToDouble();
684 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000685 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000686 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000687 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000688 break;
689 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000690 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000691 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000692 break;
693 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000694 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000695 break; // getConstantValue(Op0) above already converted it
696 }
697 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000698 }
Chris Lattner9a231222003-05-14 17:51:49 +0000699 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000700 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000701 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000702 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000703 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000704 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000705 case Instruction::UDiv:
706 case Instruction::SDiv:
707 case Instruction::URem:
708 case Instruction::SRem:
709 case Instruction::And:
710 case Instruction::Or:
711 case Instruction::Xor: {
712 GenericValue LHS = getConstantValue(Op0);
713 GenericValue RHS = getConstantValue(CE->getOperand(1));
714 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000715 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000716 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000717 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000718 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000719 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000720 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
721 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
722 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
723 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
724 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
725 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
726 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
727 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
728 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
729 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
730 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000731 break;
732 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000733 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000734 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000735 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000736 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000737 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000738 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000739 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000740 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000741 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000742 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000743 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000744 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000745 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000746 break;
747 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000748 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000749 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000750 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000751 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000752 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000753 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000754 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000755 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000756 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000757 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000758 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000759 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000760 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000761 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000762 case Type::X86_FP80TyID:
763 case Type::PPC_FP128TyID:
764 case Type::FP128TyID: {
Tim Northover0a29cb02013-01-22 09:46:31 +0000765 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
766 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000767 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000768 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000769 case Instruction::FAdd:
Tim Northover0a29cb02013-01-22 09:46:31 +0000770 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000771 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000772 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000773 case Instruction::FSub:
Tim Northover0a29cb02013-01-22 09:46:31 +0000774 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
775 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000776 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000777 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000778 case Instruction::FMul:
Tim Northover0a29cb02013-01-22 09:46:31 +0000779 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
780 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000781 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000782 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000783 case Instruction::FDiv:
Tim Northover0a29cb02013-01-22 09:46:31 +0000784 apfLHS.divide(APFloat(Sem, RHS.IntVal),
785 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000786 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000787 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000788 case Instruction::FRem:
Tim Northover0a29cb02013-01-22 09:46:31 +0000789 apfLHS.mod(APFloat(Sem, RHS.IntVal),
790 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000791 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000792 break;
793 }
794 }
795 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000796 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000797 return GV;
798 }
Chris Lattner9a231222003-05-14 17:51:49 +0000799 default:
800 break;
801 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000802
803 SmallString<256> Msg;
804 raw_svector_ostream OS(Msg);
805 OS << "ConstantExpr not handled: " << *CE;
806 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000807 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000808
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000809 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000810 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000811 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000812 case Type::FloatTyID:
813 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000814 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000815 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000816 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000817 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000818 case Type::X86_FP80TyID:
819 case Type::FP128TyID:
820 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000821 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000822 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000823 case Type::IntegerTyID:
824 Result.IntVal = cast<ConstantInt>(C)->getValue();
825 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000826 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000827 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000828 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000829 else if (const Function *F = dyn_cast<Function>(C))
830 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000831 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000832 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000833 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
834 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
835 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000836 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000837 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000838 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000839 case Type::VectorTyID: {
840 unsigned elemNum;
841 Type* ElemTy;
842 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
843 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
844 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
845
846 if (CDV) {
847 elemNum = CDV->getNumElements();
848 ElemTy = CDV->getElementType();
849 } else if (CV || CAZ) {
850 VectorType* VTy = dyn_cast<VectorType>(C->getType());
851 elemNum = VTy->getNumElements();
852 ElemTy = VTy->getElementType();
853 } else {
854 llvm_unreachable("Unknown constant vector type!");
855 }
856
857 Result.AggregateVal.resize(elemNum);
858 // Check if vector holds floats.
859 if(ElemTy->isFloatTy()) {
860 if (CAZ) {
861 GenericValue floatZero;
862 floatZero.FloatVal = 0.f;
863 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
864 floatZero);
865 break;
866 }
867 if(CV) {
868 for (unsigned i = 0; i < elemNum; ++i)
869 if (!isa<UndefValue>(CV->getOperand(i)))
870 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
871 CV->getOperand(i))->getValueAPF().convertToFloat();
872 break;
873 }
874 if(CDV)
875 for (unsigned i = 0; i < elemNum; ++i)
876 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
877
878 break;
879 }
880 // Check if vector holds doubles.
881 if (ElemTy->isDoubleTy()) {
882 if (CAZ) {
883 GenericValue doubleZero;
884 doubleZero.DoubleVal = 0.0;
885 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
886 doubleZero);
887 break;
888 }
889 if(CV) {
890 for (unsigned i = 0; i < elemNum; ++i)
891 if (!isa<UndefValue>(CV->getOperand(i)))
892 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
893 CV->getOperand(i))->getValueAPF().convertToDouble();
894 break;
895 }
896 if(CDV)
897 for (unsigned i = 0; i < elemNum; ++i)
898 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
899
900 break;
901 }
902 // Check if vector holds integers.
903 if (ElemTy->isIntegerTy()) {
904 if (CAZ) {
905 GenericValue intZero;
906 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
907 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
908 intZero);
909 break;
910 }
911 if(CV) {
912 for (unsigned i = 0; i < elemNum; ++i)
913 if (!isa<UndefValue>(CV->getOperand(i)))
914 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
915 CV->getOperand(i))->getValue();
916 else {
917 Result.AggregateVal[i].IntVal =
918 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
919 }
920 break;
921 }
922 if(CDV)
923 for (unsigned i = 0; i < elemNum; ++i)
924 Result.AggregateVal[i].IntVal = APInt(
925 CDV->getElementType()->getPrimitiveSizeInBits(),
926 CDV->getElementAsInteger(i));
927
928 break;
929 }
930 llvm_unreachable("Unknown constant pointer type!");
931 }
932 break;
933
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000934 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000935 SmallString<256> Msg;
936 raw_svector_ostream OS(Msg);
937 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
938 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000939 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000940
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000941 return Result;
942}
943
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000944/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
945/// with the integer held in IntVal.
946static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
947 unsigned StoreBytes) {
948 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divacky59324292012-09-05 22:26:57 +0000949 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000950
Rafael Espindola21a01d12013-04-15 14:44:24 +0000951 if (sys::IsLittleEndianHost) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000952 // Little-endian host - the source is ordered from LSB to MSB. Order the
953 // destination from LSB to MSB: Do a straight copy.
954 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000955 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000956 // Big-endian host - the source is an array of 64 bit words ordered from
957 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
958 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
959 while (StoreBytes > sizeof(uint64_t)) {
960 StoreBytes -= sizeof(uint64_t);
961 // May not be aligned so use memcpy.
962 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
963 Src += sizeof(uint64_t);
964 }
965
966 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
967 }
968}
969
Evan Cheng89687e32008-11-04 06:10:31 +0000970void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000971 GenericValue *Ptr, Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000972 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000973
Reid Spencer8fb0f192007-03-06 03:04:04 +0000974 switch (Ty->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000975 default:
976 dbgs() << "Cannot store value of type " << *Ty << "!\n";
977 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000978 case Type::IntegerTyID:
979 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000980 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000981 case Type::FloatTyID:
982 *((float*)Ptr) = Val.FloatVal;
983 break;
984 case Type::DoubleTyID:
985 *((double*)Ptr) = Val.DoubleVal;
986 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000987 case Type::X86_FP80TyID:
988 memcpy(Ptr, Val.IntVal.getRawData(), 10);
989 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000990 case Type::PointerTyID:
991 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
992 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +0000993 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000994
Reid Spencer8fb0f192007-03-06 03:04:04 +0000995 *((PointerTy*)Ptr) = Val.PointerVal;
996 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000997 case Type::VectorTyID:
998 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
999 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1000 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1001 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1002 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1003 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1004 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1005 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1006 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1007 }
1008 }
1009 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001010 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001011
Rafael Espindola21a01d12013-04-15 14:44:24 +00001012 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001013 // Host and target are different endian - reverse the stored bytes.
1014 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1015}
1016
1017/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1018/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1019static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1020 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greenec2680be2013-01-14 21:04:45 +00001021 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1022 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001023
Rafael Espindola21a01d12013-04-15 14:44:24 +00001024 if (sys::IsLittleEndianHost)
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001025 // Little-endian host - the destination must be ordered from LSB to MSB.
1026 // The source is ordered from LSB to MSB: Do a straight copy.
1027 memcpy(Dst, Src, LoadBytes);
1028 else {
1029 // Big-endian - the destination is an array of 64 bit words ordered from
1030 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1031 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1032 // a word.
1033 while (LoadBytes > sizeof(uint64_t)) {
1034 LoadBytes -= sizeof(uint64_t);
1035 // May not be aligned so use memcpy.
1036 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1037 Dst += sizeof(uint64_t);
1038 }
1039
1040 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1041 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001042}
1043
Misha Brukman4afac182003-10-10 17:45:12 +00001044/// FIXME: document
1045///
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001046void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +00001047 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001048 Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001049 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +00001050
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001051 switch (Ty->getTypeID()) {
1052 case Type::IntegerTyID:
1053 // An APInt with all words initially zero.
1054 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1055 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1056 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001057 case Type::FloatTyID:
1058 Result.FloatVal = *((float*)Ptr);
1059 break;
1060 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001061 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001062 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001063 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +00001064 Result.PointerVal = *((PointerTy*)Ptr);
1065 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001066 case Type::X86_FP80TyID: {
1067 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +00001068 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001069 uint64_t y[2];
1070 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001071 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001072 break;
1073 }
Nadav Rotem953783e2013-04-01 15:53:30 +00001074 case Type::VectorTyID: {
1075 const VectorType *VT = cast<VectorType>(Ty);
1076 const Type *ElemT = VT->getElementType();
1077 const unsigned numElems = VT->getNumElements();
1078 if (ElemT->isFloatTy()) {
1079 Result.AggregateVal.resize(numElems);
1080 for (unsigned i = 0; i < numElems; ++i)
1081 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1082 }
1083 if (ElemT->isDoubleTy()) {
1084 Result.AggregateVal.resize(numElems);
1085 for (unsigned i = 0; i < numElems; ++i)
1086 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1087 }
1088 if (ElemT->isIntegerTy()) {
1089 GenericValue intZero;
1090 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1091 intZero.IntVal = APInt(elemBitWidth, 0);
1092 Result.AggregateVal.resize(numElems, intZero);
1093 for (unsigned i = 0; i < numElems; ++i)
1094 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1095 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1096 }
1097 break;
1098 }
Reid Spencer8fb0f192007-03-06 03:04:04 +00001099 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001100 SmallString<256> Msg;
1101 raw_svector_ostream OS(Msg);
1102 OS << "Cannot load value of type " << *Ty << "!";
1103 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001104 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001105}
1106
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001107void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +00001108 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001109 DEBUG(Init->dump());
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001110 if (isa<UndefValue>(Init))
Chris Lattnerbd1d3822004-10-16 18:19:26 +00001111 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001112
1113 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001114 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001115 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001116 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1117 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1118 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001119 }
1120
1121 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001122 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +00001123 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001124 }
1125
1126 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001127 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001128 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +00001129 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1130 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1131 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001132 }
1133
1134 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001135 const StructLayout *SL =
Micah Villmow3574eca2012-10-08 16:38:25 +00001136 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman638e3782008-05-20 03:20:09 +00001137 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1138 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1139 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001140 }
1141
1142 if (const ConstantDataSequential *CDS =
1143 dyn_cast<ConstantDataSequential>(Init)) {
1144 // CDS is already laid out in host memory order.
1145 StringRef Data = CDS->getRawDataValues();
1146 memcpy(Addr, Data.data(), Data.size());
1147 return;
1148 }
1149
1150 if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001151 GenericValue Val = getConstantValue(Init);
1152 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1153 return;
1154 }
1155
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001156 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +00001157 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001158}
1159
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001160/// EmitGlobals - Emit all of the global variables to memory, storing their
1161/// addresses into GlobalAddress. This must make sure to copy the contents of
1162/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001163void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001164 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +00001165 // to hold them. If there is more than one module, do a prepass over globals
1166 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001167 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +00001168 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001169
Chris Lattnerfe854032006-08-16 01:24:12 +00001170 if (Modules.size() != 1) {
1171 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001172 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001173 for (Module::const_global_iterator I = M.global_begin(),
1174 E = M.global_end(); I != E; ++I) {
1175 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001176 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +00001177 GV->hasAppendingLinkage() || !GV->hasName())
1178 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001179
1180 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001181 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1182
1183 // If this is the first time we've seen this global, it is the canonical
1184 // version.
1185 if (!GVEntry) {
1186 GVEntry = GV;
1187 continue;
1188 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001189
Chris Lattnerfe854032006-08-16 01:24:12 +00001190 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001191 if (GVEntry->hasExternalLinkage() ||
1192 GVEntry->hasDLLImportLinkage() ||
1193 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001194 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001195
Chris Lattnerfe854032006-08-16 01:24:12 +00001196 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001197 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001198 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001199 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001200 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001201 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001202 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001203
Chris Lattnerfe854032006-08-16 01:24:12 +00001204 std::vector<const GlobalValue*> NonCanonicalGlobals;
1205 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001206 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001207 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1208 I != E; ++I) {
1209 // In the multi-module case, see what this global maps to.
1210 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001211 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001212 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1213 // If something else is the canonical global, ignore this one.
1214 if (GVEntry != &*I) {
1215 NonCanonicalGlobals.push_back(I);
1216 continue;
1217 }
1218 }
1219 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001220
Reid Spencer5cbf9852007-01-30 20:08:39 +00001221 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001222 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001223 } else {
1224 // External variable reference. Try to use the dynamic loader to
1225 // get a pointer to it.
1226 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001227 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001228 addGlobalMapping(I, SymAddr);
1229 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001230 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001231 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001232 }
1233 }
1234 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001235
Chris Lattnerfe854032006-08-16 01:24:12 +00001236 // If there are multiple modules, map the non-canonical globals to their
1237 // canonical location.
1238 if (!NonCanonicalGlobals.empty()) {
1239 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1240 const GlobalValue *GV = NonCanonicalGlobals[i];
1241 const GlobalValue *CGV =
1242 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1243 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1244 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001245 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001246 }
1247 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001248
1249 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001250 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001251 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1252 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001253 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001254 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001255 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001256 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1257 if (GVEntry != &*I) // Not the canonical variable.
1258 continue;
1259 }
1260 EmitGlobalVariable(I);
1261 }
1262 }
1263 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001264}
1265
1266// EmitGlobalVariable - This method emits the specified global variable to the
1267// address specified in GlobalAddresses, or allocates new memory if it's not
1268// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001269void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001270 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001271
Chris Lattner24b0a182003-12-20 02:45:37 +00001272 if (GA == 0) {
1273 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001274 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001275 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001276 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001277
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001278 // Don't initialize if it's thread local, let the client do it.
1279 if (!GV->isThreadLocal())
1280 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001281
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001282 Type *ElTy = GV->getType()->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001283 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001284 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001285 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001286}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001287
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001288ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1289 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001290}
1291
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001292sys::Mutex *
1293ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001294 return &EES->EE.lock;
1295}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001296
1297void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1298 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001299 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1300 EES->GlobalAddressReverseMap.erase(OldVal);
1301}
1302
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001303void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1304 const GlobalValue *,
1305 const GlobalValue *) {
Craig Topper85814382012-02-07 05:05:23 +00001306 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1307 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001308}