blob: 21e0ad3fcd36576fad19d13cd901b241f42662b5 [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/Constants.h"
20#include "llvm/DataLayout.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/ExecutionEngine/GenericValue.h"
23#include "llvm/Module.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000025#include "llvm/Support/DynamicLibrary.h"
Torok Edwin31e24662009-07-07 17:32:34 +000026#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/Support/Host.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000028#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/Support/TargetRegistry.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000030#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000031#include "llvm/Support/raw_ostream.h"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000032#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000033#include <cmath>
34#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000035using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000036
Chris Lattner36343732006-12-19 22:43:32 +000037STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
38STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000039
Jeffrey Yasskin46882612010-02-05 16:19:36 +000040ExecutionEngine *(*ExecutionEngine::JITCtor)(
41 Module *M,
42 std::string *ErrorStr,
43 JITMemoryManager *JMM,
Jeffrey Yasskin46882612010-02-05 16:19:36 +000044 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000045 TargetMachine *TM) = 0;
Daniel Dunbar6d135972010-11-17 16:06:37 +000046ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
47 Module *M,
48 std::string *ErrorStr,
49 JITMemoryManager *JMM,
Daniel Dunbar6d135972010-11-17 16:06:37 +000050 bool GVsWithCode,
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000051 TargetMachine *TM) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000052ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000053 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000054
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000055ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000056 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000057 LazyFunctionCreator(0),
Daniel Dunbar48dd8752010-11-13 02:48:57 +000058 ExceptionTableRegister(0),
Duncan Sandsb35fd442010-10-21 08:57:29 +000059 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000060 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000061 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000062 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000063 Modules.push_back(M);
64 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000065}
66
Brian Gaeke8e539482003-09-04 22:57:27 +000067ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000068 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000069 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
70 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000071}
72
Duncan Sandsb35fd442010-10-21 08:57:29 +000073void ExecutionEngine::DeregisterAllTables() {
74 if (ExceptionTableDeregister) {
Eric Christopher515c67e2011-03-04 23:37:39 +000075 DenseMap<const Function*, void*>::iterator it = AllExceptionTables.begin();
76 DenseMap<const Function*, void*>::iterator ite = AllExceptionTables.end();
77 for (; it != ite; ++it)
78 ExceptionTableDeregister(it->second);
Duncan Sandsb35fd442010-10-21 08:57:29 +000079 AllExceptionTables.clear();
80 }
81}
82
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000083namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000084/// \brief Helper class which uses a value handler to automatically deletes the
85/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000086class GVMemoryBlock : public CallbackVH {
87 GVMemoryBlock(const GlobalVariable *GV)
88 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
89
90public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000091 /// \brief Returns the address the GlobalVariable should be written into. The
92 /// GVMemoryBlock object prefixes that.
Micah Villmow3574eca2012-10-08 16:38:25 +000093 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000094 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000095 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
96 void *RawMemory = ::operator new(
Micah Villmow3574eca2012-10-08 16:38:25 +000097 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000098 TD.getPreferredAlignment(GV))
99 + GVSize);
100 new(RawMemory) GVMemoryBlock(GV);
101 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
102 }
103
104 virtual void deleted() {
105 // We allocated with operator new and with some extra memory hanging off the
106 // end, so don't just delete this. I'm not sure if this is actually
107 // required.
108 this->~GVMemoryBlock();
109 ::operator delete(this);
110 }
111};
112} // anonymous namespace
113
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000114char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000115 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000116}
117
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000118bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000119 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000120 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000121 Module *Found = *I;
122 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000123 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000124 clearGlobalMappingsFromModule(M);
125 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000126 }
127 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000128 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000129}
130
Chris Lattnerfe854032006-08-16 01:24:12 +0000131Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
132 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000133 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000134 return F;
135 }
136 return 0;
137}
138
139
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000140void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
141 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000142 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000143 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000144
145 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
146 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000147 if (I == GlobalAddressMap.end())
148 OldVal = 0;
149 else {
150 OldVal = I->second;
151 GlobalAddressMap.erase(I);
152 }
153
154 GlobalAddressReverseMap.erase(OldVal);
155 return OldVal;
156}
157
Chris Lattnere7fd5532006-05-08 22:00:52 +0000158void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
159 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000160
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000161 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000162 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000163 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000164 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
165 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000166
167 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000168 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000169 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000170 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000171 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
172 V = GV;
173 }
174}
175
Chris Lattnere7fd5532006-05-08 22:00:52 +0000176void ExecutionEngine::clearAllGlobalMappings() {
177 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000178
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000179 EEState.getGlobalAddressMap(locked).clear();
180 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000181}
182
Nate Begemanf049e072008-05-21 16:34:48 +0000183void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
184 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000185
186 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000187 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000188 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
189 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000190 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000191}
192
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000193void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000194 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000195
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000196 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000197 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000198
Chris Lattnere7fd5532006-05-08 22:00:52 +0000199 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000200 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000201 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000202
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000203 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000204 void *OldVal = CurVal;
205
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000206 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
207 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000208 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000209
210 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000211 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000212 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000213 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000214 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
215 V = GV;
216 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000217 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000218}
219
Chris Lattnere7fd5532006-05-08 22:00:52 +0000220void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
221 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000222
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000223 ExecutionEngineState::GlobalAddressMapTy::iterator I =
224 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000225 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000226}
227
Chris Lattner55d86482003-12-31 20:21:04 +0000228const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000229 MutexGuard locked(lock);
230
Chris Lattner55d86482003-12-31 20:21:04 +0000231 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000232 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000233 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000234 I = EEState.getGlobalAddressMap(locked).begin(),
235 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000236 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
237 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000238 }
239
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000240 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000241 EEState.getGlobalAddressReverseMap(locked).find(Addr);
242 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000243}
Chris Lattner87f03102003-12-26 06:50:30 +0000244
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000245namespace {
246class ArgvArray {
247 char *Array;
248 std::vector<char*> Values;
249public:
250 ArgvArray() : Array(NULL) {}
251 ~ArgvArray() { clear(); }
252 void clear() {
253 delete[] Array;
254 Array = NULL;
255 for (size_t I = 0, E = Values.size(); I != E; ++I) {
256 delete[] Values[I];
257 }
258 Values.clear();
259 }
260 /// Turn a vector of strings into a nice argv style array of pointers to null
261 /// terminated strings.
262 void *reset(LLVMContext &C, ExecutionEngine *EE,
263 const std::vector<std::string> &InputArgv);
264};
265} // anonymous namespace
266void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
267 const std::vector<std::string> &InputArgv) {
268 clear(); // Free the old contents.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000269 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000270 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000271
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000272 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000273 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000274
275 for (unsigned i = 0; i != InputArgv.size(); ++i) {
276 unsigned Size = InputArgv[i].size()+1;
277 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000278 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000279 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000280
Chris Lattner87f03102003-12-26 06:50:30 +0000281 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
282 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000283
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000284 // Endian safe: Array[i] = (PointerTy)Dest;
285 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000286 SBytePtr);
287 }
288
289 // Null terminate it
290 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000291 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000292 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000293 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000294}
295
Chris Lattnerfbd39762009-09-23 01:46:04 +0000296void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
297 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000298 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000299 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000300
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000301 // If this global has internal linkage, or if it has a use, then it must be
302 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
303 // this is the case, don't execute any of the global ctors, __main will do
304 // it.
305 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
306
Nick Lewyckya040d472011-04-06 20:38:44 +0000307 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000308 // the init priority, which we ignore.
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000309 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
310 if (InitList == 0)
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000311 return;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000312 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000313 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
314 if (CS == 0) continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000315
316 Constant *FP = CS->getOperand(1);
317 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000318 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000319
320 // Strip off constant expression casts.
321 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
322 if (CE->isCast())
323 FP = CE->getOperand(0);
324
325 // Execute the ctor/dtor function!
326 if (Function *F = dyn_cast<Function>(FP))
327 runFunction(F, std::vector<GenericValue>());
328
329 // FIXME: It is marginally lame that we just do nothing here if we see an
330 // entry we don't recognize. It might not be unreasonable for the verifier
331 // to not even allow this and just assert here.
332 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000333}
334
Evan Cheng18314dc2008-09-30 15:51:21 +0000335void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
336 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000337 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
338 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000339}
340
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000341#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000342/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
343static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000344 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000345 for (unsigned i = 0; i < PtrSize; ++i)
346 if (*(i + (uint8_t*)Loc))
347 return false;
348 return true;
349}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000350#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000351
Chris Lattner87f03102003-12-26 06:50:30 +0000352int ExecutionEngine::runFunctionAsMain(Function *Fn,
353 const std::vector<std::string> &argv,
354 const char * const * envp) {
355 std::vector<GenericValue> GVArgs;
356 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000357 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000358
359 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000360 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000361 FunctionType *FTy = Fn->getFunctionType();
362 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000363
364 // Check the argument types.
365 if (NumArgs > 3)
366 report_fatal_error("Invalid number of arguments of main() supplied");
367 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
368 report_fatal_error("Invalid type for third argument of main() supplied");
369 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
370 report_fatal_error("Invalid type for second argument of main() supplied");
371 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
372 report_fatal_error("Invalid type for first argument of main() supplied");
373 if (!FTy->getReturnType()->isIntegerTy() &&
374 !FTy->getReturnType()->isVoidTy())
375 report_fatal_error("Invalid return type of main() supplied");
376
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000377 ArgvArray CArgv;
378 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000379 if (NumArgs) {
380 GVArgs.push_back(GVArgc); // Arg #0 = argc.
381 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000382 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000383 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000384 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000385 "argv[0] was null after CreateArgv");
386 if (NumArgs > 2) {
387 std::vector<std::string> EnvVars;
388 for (unsigned i = 0; envp[i]; ++i)
389 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000390 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000391 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000392 }
393 }
394 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000395
Reid Spencer8fb0f192007-03-06 03:04:04 +0000396 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000397}
398
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000399ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000400 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000401 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000402 CodeGenOpt::Level OptLevel,
403 bool GVsWithCode) {
Owen Anderson8e1fc562012-03-23 17:40:56 +0000404 EngineBuilder EB = EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000405 .setEngineKind(ForceInterpreter
406 ? EngineKind::Interpreter
407 : EngineKind::JIT)
408 .setErrorStr(ErrorStr)
409 .setOptLevel(OptLevel)
Owen Anderson8e1fc562012-03-23 17:40:56 +0000410 .setAllocateGVsWithCode(GVsWithCode);
411
412 return EB.create();
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000413}
Brian Gaeke82d82772003-09-03 20:34:19 +0000414
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000415/// createJIT - This is the factory method for creating a JIT for the current
416/// machine, it does not fall back to the interpreter. This takes ownership
417/// of the module.
418ExecutionEngine *ExecutionEngine::createJIT(Module *M,
419 std::string *ErrorStr,
420 JITMemoryManager *JMM,
Dylan Noblesmithd95e67d2011-12-01 21:49:21 +0000421 CodeGenOpt::Level OL,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000422 bool GVsWithCode,
Evan Cheng43966132011-07-19 06:37:02 +0000423 Reloc::Model RM,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000424 CodeModel::Model CMM) {
425 if (ExecutionEngine::JITCtor == 0) {
426 if (ErrorStr)
427 *ErrorStr = "JIT has not been linked in.";
428 return 0;
429 }
430
431 // Use the defaults for extra parameters. Users can use EngineBuilder to
432 // set them.
Owen Anderson8e1fc562012-03-23 17:40:56 +0000433 EngineBuilder EB(M);
434 EB.setEngineKind(EngineKind::JIT);
435 EB.setErrorStr(ErrorStr);
436 EB.setRelocationModel(RM);
437 EB.setCodeModel(CMM);
438 EB.setAllocateGVsWithCode(GVsWithCode);
439 EB.setOptLevel(OL);
440 EB.setJITMemoryManager(JMM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000441
Peter Collingbourned40e1032011-12-07 23:58:57 +0000442 // TODO: permit custom TargetOptions here
Owen Anderson8e1fc562012-03-23 17:40:56 +0000443 TargetMachine *TM = EB.selectTarget();
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000444 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return 0;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000445
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000446 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000447}
448
Owen Anderson8e1fc562012-03-23 17:40:56 +0000449ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Benjamin Kramer0f554492012-04-08 14:53:14 +0000450 OwningPtr<TargetMachine> TheTM(TM); // Take ownership.
451
Nick Lewycky6456d862008-03-08 02:49:45 +0000452 // Make sure we can resolve symbols in the program as well. The zero arg
453 // to the function tells DynamicLibrary to load the program, not a library.
454 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
455 return 0;
456
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000457 // If the user specified a memory manager but didn't specify which engine to
458 // create, we assume they only want the JIT, and we fail if they only want
459 // the interpreter.
460 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000461 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000462 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000463 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000464 if (ErrorStr)
465 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000466 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000467 }
468 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000469
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000470 // Unless the interpreter was explicitly selected or the JIT is not linked,
471 // try making a JIT.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000472 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000473 Triple TT(M->getTargetTriple());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000474 if (!TM->getTarget().hasJIT()) {
475 errs() << "WARNING: This target JIT is not designed for the host"
476 << " you are running. If bad things happen, please choose"
477 << " a different -march switch.\n";
478 }
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000479
Owen Anderson8e1fc562012-03-23 17:40:56 +0000480 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
481 ExecutionEngine *EE =
482 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM,
Benjamin Kramer0f554492012-04-08 14:53:14 +0000483 AllocateGVsWithCode, TheTM.take());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000484 if (EE) return EE;
485 } else if (ExecutionEngine::JITCtor) {
486 ExecutionEngine *EE =
487 ExecutionEngine::JITCtor(M, ErrorStr, JMM,
Benjamin Kramer0f554492012-04-08 14:53:14 +0000488 AllocateGVsWithCode, TheTM.take());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000489 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000490 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000491 }
492
493 // If we can't make a JIT and we didn't request one specifically, try making
494 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000495 if (WhichEngine & EngineKind::Interpreter) {
496 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000497 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000498 if (ErrorStr)
499 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000500 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000501 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000502
Jim Grosbach8005bcd2012-08-21 15:42:49 +0000503 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0 &&
504 ExecutionEngine::MCJITCtor == 0) {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000505 if (ErrorStr)
506 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000507 }
508
Chris Lattnerfbd39762009-09-23 01:46:04 +0000509 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000510}
511
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000512void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000513 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000514 return getPointerToFunction(F);
515
Reid Spenceree448632005-07-12 15:51:55 +0000516 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000517 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
518 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000519
520 // Global variable might have been added since interpreter started.
521 if (GlobalVariable *GVar =
522 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
523 EmitGlobalVariable(GVar);
524 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000525 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000526
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000527 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000528}
529
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000530/// \brief Converts a Constant* into a GenericValue, including handling of
531/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000532GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000533 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000534 if (isa<UndefValue>(C)) {
535 GenericValue Result;
536 switch (C->getType()->getTypeID()) {
537 case Type::IntegerTyID:
538 case Type::X86_FP80TyID:
539 case Type::FP128TyID:
540 case Type::PPC_FP128TyID:
541 // Although the value is undefined, we still have to construct an APInt
542 // with the correct bit width.
543 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
544 break;
545 default:
546 break;
547 }
548 return Result;
549 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000550
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000551 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000552 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000553 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000554 switch (CE->getOpcode()) {
555 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000556 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000557 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000558 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Jay Foad8fbbb392011-07-19 14:01:37 +0000559 uint64_t Offset = TD->getIndexedOffset(Op0->getType(), Indices);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000560
Reid Spencer8fb0f192007-03-06 03:04:04 +0000561 char* tmp = (char*) Result.PointerVal;
562 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000563 return Result;
564 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000565 case Instruction::Trunc: {
566 GenericValue GV = getConstantValue(Op0);
567 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
568 GV.IntVal = GV.IntVal.trunc(BitWidth);
569 return GV;
570 }
571 case Instruction::ZExt: {
572 GenericValue GV = getConstantValue(Op0);
573 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
574 GV.IntVal = GV.IntVal.zext(BitWidth);
575 return GV;
576 }
577 case Instruction::SExt: {
578 GenericValue GV = getConstantValue(Op0);
579 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
580 GV.IntVal = GV.IntVal.sext(BitWidth);
581 return GV;
582 }
583 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000584 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000585 GenericValue GV = getConstantValue(Op0);
586 GV.FloatVal = float(GV.DoubleVal);
587 return GV;
588 }
589 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000590 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000591 GenericValue GV = getConstantValue(Op0);
592 GV.DoubleVal = double(GV.FloatVal);
593 return GV;
594 }
595 case Instruction::UIToFP: {
596 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000597 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000598 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000599 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000600 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000601 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000602 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000603 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000604 false,
605 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000606 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000607 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000608 return GV;
609 }
610 case Instruction::SIToFP: {
611 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000612 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000613 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000614 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000615 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000616 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000617 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000618 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000619 true,
620 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000621 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000622 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000623 return GV;
624 }
625 case Instruction::FPToUI: // double->APInt conversion handles sign
626 case Instruction::FPToSI: {
627 GenericValue GV = getConstantValue(Op0);
628 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000629 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000630 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000631 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000632 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000633 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000634 APFloat apf = APFloat(GV.IntVal);
635 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000636 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000637 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000638 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000639 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000640 GV.IntVal = v; // endian?
641 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000642 return GV;
643 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000644 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000645 GenericValue GV = getConstantValue(Op0);
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000646 uint32_t PtrWidth = TD->getTypeSizeInBits(Op0->getType());
647 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencerbce30f12007-03-06 22:23:15 +0000648 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000649 uint32_t IntWidth = TD->getTypeSizeInBits(CE->getType());
650 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000651 return GV;
652 }
653 case Instruction::IntToPtr: {
654 GenericValue GV = getConstantValue(Op0);
Micah Villmowb52fb872012-10-24 18:36:13 +0000655 uint32_t PtrWidth = TD->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000656 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000657 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
658 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000659 return GV;
660 }
661 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000662 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000663 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000664 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000665 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000666 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000667 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000668 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000669 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000670 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 GV.DoubleVal = GV.IntVal.bitsToDouble();
672 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000673 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000674 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000675 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000676 break;
677 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000678 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000679 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000680 break;
681 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000682 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000683 break; // getConstantValue(Op0) above already converted it
684 }
685 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000686 }
Chris Lattner9a231222003-05-14 17:51:49 +0000687 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000688 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000689 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000690 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000691 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000692 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000693 case Instruction::UDiv:
694 case Instruction::SDiv:
695 case Instruction::URem:
696 case Instruction::SRem:
697 case Instruction::And:
698 case Instruction::Or:
699 case Instruction::Xor: {
700 GenericValue LHS = getConstantValue(Op0);
701 GenericValue RHS = getConstantValue(CE->getOperand(1));
702 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000703 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000704 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000705 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000706 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000707 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000708 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
709 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
710 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
711 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
712 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
713 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
714 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
715 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
716 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
717 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
718 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000719 break;
720 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000721 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000722 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000723 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000724 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000725 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000726 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000727 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000728 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000729 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000730 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000731 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000732 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000733 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000734 break;
735 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000736 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000737 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000738 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000739 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000740 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000741 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000742 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000743 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000744 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000745 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000746 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000747 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000748 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000749 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000750 case Type::X86_FP80TyID:
751 case Type::PPC_FP128TyID:
752 case Type::FP128TyID: {
753 APFloat apfLHS = APFloat(LHS.IntVal);
754 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000755 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000756 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000757 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000758 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000759 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000760 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000761 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000762 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000763 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000764 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000765 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000766 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000767 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000768 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000769 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000770 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000771 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000772 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000773 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000774 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000775 break;
776 }
777 }
778 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000779 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000780 return GV;
781 }
Chris Lattner9a231222003-05-14 17:51:49 +0000782 default:
783 break;
784 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000785
786 SmallString<256> Msg;
787 raw_svector_ostream OS(Msg);
788 OS << "ConstantExpr not handled: " << *CE;
789 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000790 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000791
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000792 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000793 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000794 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000795 case Type::FloatTyID:
796 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000797 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000798 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000799 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000800 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000801 case Type::X86_FP80TyID:
802 case Type::FP128TyID:
803 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000804 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000805 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000806 case Type::IntegerTyID:
807 Result.IntVal = cast<ConstantInt>(C)->getValue();
808 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000809 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000810 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000811 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000812 else if (const Function *F = dyn_cast<Function>(C))
813 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000814 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000815 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000816 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
817 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
818 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000819 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000820 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000821 break;
822 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000823 SmallString<256> Msg;
824 raw_svector_ostream OS(Msg);
825 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
826 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000827 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000828
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000829 return Result;
830}
831
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000832/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
833/// with the integer held in IntVal.
834static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
835 unsigned StoreBytes) {
836 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divacky59324292012-09-05 22:26:57 +0000837 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000838
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000839 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000840 // Little-endian host - the source is ordered from LSB to MSB. Order the
841 // destination from LSB to MSB: Do a straight copy.
842 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000843 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000844 // Big-endian host - the source is an array of 64 bit words ordered from
845 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
846 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
847 while (StoreBytes > sizeof(uint64_t)) {
848 StoreBytes -= sizeof(uint64_t);
849 // May not be aligned so use memcpy.
850 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
851 Src += sizeof(uint64_t);
852 }
853
854 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
855 }
856}
857
Evan Cheng89687e32008-11-04 06:10:31 +0000858void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000859 GenericValue *Ptr, Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000860 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000861
Reid Spencer8fb0f192007-03-06 03:04:04 +0000862 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000863 case Type::IntegerTyID:
864 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000865 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000866 case Type::FloatTyID:
867 *((float*)Ptr) = Val.FloatVal;
868 break;
869 case Type::DoubleTyID:
870 *((double*)Ptr) = Val.DoubleVal;
871 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000872 case Type::X86_FP80TyID:
873 memcpy(Ptr, Val.IntVal.getRawData(), 10);
874 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000875 case Type::PointerTyID:
876 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
877 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +0000878 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000879
Reid Spencer8fb0f192007-03-06 03:04:04 +0000880 *((PointerTy*)Ptr) = Val.PointerVal;
881 break;
882 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000883 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000884 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000885
Micah Villmow3574eca2012-10-08 16:38:25 +0000886 if (sys::isLittleEndianHost() != getDataLayout()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000887 // Host and target are different endian - reverse the stored bytes.
888 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
889}
890
891/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
892/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
893static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
894 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
895 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
896
Chris Lattnerb67c9582009-01-22 19:53:00 +0000897 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000898 // Little-endian host - the destination must be ordered from LSB to MSB.
899 // The source is ordered from LSB to MSB: Do a straight copy.
900 memcpy(Dst, Src, LoadBytes);
901 else {
902 // Big-endian - the destination is an array of 64 bit words ordered from
903 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
904 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
905 // a word.
906 while (LoadBytes > sizeof(uint64_t)) {
907 LoadBytes -= sizeof(uint64_t);
908 // May not be aligned so use memcpy.
909 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
910 Dst += sizeof(uint64_t);
911 }
912
913 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
914 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000915}
916
Misha Brukman4afac182003-10-10 17:45:12 +0000917/// FIXME: document
918///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000919void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000920 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000921 Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000922 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000923
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000924 switch (Ty->getTypeID()) {
925 case Type::IntegerTyID:
926 // An APInt with all words initially zero.
927 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
928 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
929 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000930 case Type::FloatTyID:
931 Result.FloatVal = *((float*)Ptr);
932 break;
933 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000934 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000935 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000936 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000937 Result.PointerVal = *((PointerTy*)Ptr);
938 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000939 case Type::X86_FP80TyID: {
940 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000941 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000942 uint64_t y[2];
943 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +0000944 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000945 break;
946 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000947 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000948 SmallString<256> Msg;
949 raw_svector_ostream OS(Msg);
950 OS << "Cannot load value of type " << *Ty << "!";
951 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000952 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000953}
954
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000955void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000956 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000957 DEBUG(Init->dump());
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000958 if (isa<UndefValue>(Init))
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000959 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000960
961 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000962 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +0000963 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000964 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
965 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
966 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000967 }
968
969 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000970 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000971 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000972 }
973
974 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +0000975 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +0000976 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000977 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
978 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
979 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000980 }
981
982 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +0000983 const StructLayout *SL =
Micah Villmow3574eca2012-10-08 16:38:25 +0000984 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman638e3782008-05-20 03:20:09 +0000985 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
986 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
987 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000988 }
989
990 if (const ConstantDataSequential *CDS =
991 dyn_cast<ConstantDataSequential>(Init)) {
992 // CDS is already laid out in host memory order.
993 StringRef Data = CDS->getRawDataValues();
994 memcpy(Addr, Data.data(), Data.size());
995 return;
996 }
997
998 if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000999 GenericValue Val = getConstantValue(Init);
1000 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1001 return;
1002 }
1003
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001004 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +00001005 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001006}
1007
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001008/// EmitGlobals - Emit all of the global variables to memory, storing their
1009/// addresses into GlobalAddress. This must make sure to copy the contents of
1010/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001011void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001012 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +00001013 // to hold them. If there is more than one module, do a prepass over globals
1014 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001015 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +00001016 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001017
Chris Lattnerfe854032006-08-16 01:24:12 +00001018 if (Modules.size() != 1) {
1019 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001020 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001021 for (Module::const_global_iterator I = M.global_begin(),
1022 E = M.global_end(); I != E; ++I) {
1023 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001024 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +00001025 GV->hasAppendingLinkage() || !GV->hasName())
1026 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001027
1028 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001029 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1030
1031 // If this is the first time we've seen this global, it is the canonical
1032 // version.
1033 if (!GVEntry) {
1034 GVEntry = GV;
1035 continue;
1036 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001037
Chris Lattnerfe854032006-08-16 01:24:12 +00001038 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001039 if (GVEntry->hasExternalLinkage() ||
1040 GVEntry->hasDLLImportLinkage() ||
1041 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001042 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001043
Chris Lattnerfe854032006-08-16 01:24:12 +00001044 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001045 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001046 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001047 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001048 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001049 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001050 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001051
Chris Lattnerfe854032006-08-16 01:24:12 +00001052 std::vector<const GlobalValue*> NonCanonicalGlobals;
1053 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001054 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001055 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1056 I != E; ++I) {
1057 // In the multi-module case, see what this global maps to.
1058 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001059 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001060 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1061 // If something else is the canonical global, ignore this one.
1062 if (GVEntry != &*I) {
1063 NonCanonicalGlobals.push_back(I);
1064 continue;
1065 }
1066 }
1067 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001068
Reid Spencer5cbf9852007-01-30 20:08:39 +00001069 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001070 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001071 } else {
1072 // External variable reference. Try to use the dynamic loader to
1073 // get a pointer to it.
1074 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001075 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001076 addGlobalMapping(I, SymAddr);
1077 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001078 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001079 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001080 }
1081 }
1082 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001083
Chris Lattnerfe854032006-08-16 01:24:12 +00001084 // If there are multiple modules, map the non-canonical globals to their
1085 // canonical location.
1086 if (!NonCanonicalGlobals.empty()) {
1087 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1088 const GlobalValue *GV = NonCanonicalGlobals[i];
1089 const GlobalValue *CGV =
1090 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1091 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1092 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001093 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001094 }
1095 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001096
1097 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001098 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001099 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1100 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001101 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001102 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001103 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001104 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1105 if (GVEntry != &*I) // Not the canonical variable.
1106 continue;
1107 }
1108 EmitGlobalVariable(I);
1109 }
1110 }
1111 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001112}
1113
1114// EmitGlobalVariable - This method emits the specified global variable to the
1115// address specified in GlobalAddresses, or allocates new memory if it's not
1116// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001117void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001118 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001119
Chris Lattner24b0a182003-12-20 02:45:37 +00001120 if (GA == 0) {
1121 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001122 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001123 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001124 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001125
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001126 // Don't initialize if it's thread local, let the client do it.
1127 if (!GV->isThreadLocal())
1128 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001129
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001130 Type *ElTy = GV->getType()->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001131 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001132 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001133 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001134}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001135
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001136ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1137 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001138}
1139
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001140sys::Mutex *
1141ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001142 return &EES->EE.lock;
1143}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001144
1145void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1146 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001147 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1148 EES->GlobalAddressReverseMap.erase(OldVal);
1149}
1150
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001151void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1152 const GlobalValue *,
1153 const GlobalValue *) {
Craig Topper85814382012-02-07 05:05:23 +00001154 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1155 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001156}