blob: 20d1631a0ceb7b0bdfa93e559e22967c12548699 [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Daniel Dunbar868e3f02010-11-13 02:48:57 +000016#include "llvm/ADT/SmallString.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000017#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ExecutionEngine/GenericValue.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000019#include "llvm/ExecutionEngine/JITEventListener.h"
Chandler Carruth9fb823b2013-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"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000025#include "llvm/IR/ValueHandle.h"
Rafael Espindoladd396572014-08-01 19:28:15 +000026#include "llvm/Object/Archive.h"
David Blaikie35907d82014-04-29 22:04:55 +000027#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Support/DynamicLibrary.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/Host.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000032#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/TargetRegistry.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000034#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000035#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000036#include <cmath>
37#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000038using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000039
Chandler Carruthf58e3762014-04-22 03:04:17 +000040#define DEBUG_TYPE "jit"
41
Chris Lattnerc346ecd2006-12-19 22:43:32 +000042STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000044
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000045ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie196e3232014-09-02 22:41:07 +000046 std::unique_ptr<Module> M, std::string *ErrorStr,
47 RTDyldMemoryManager *MCJMM, std::unique_ptr<TargetMachine> TM) = nullptr;
Rafael Espindola2a8a2792014-08-19 04:04:25 +000048ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper2617dcc2014-04-15 06:32:26 +000049 std::string *ErrorStr) =nullptr;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000050
Rafael Espindola2a8a2792014-08-19 04:04:25 +000051ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +000052 : EEState(*this),
Craig Topper2617dcc2014-04-15 06:32:26 +000053 LazyFunctionCreator(nullptr) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000054 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000055 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000056 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000057
58 // IR module verification is enabled by default in debug builds, and disabled
59 // by default in release builds.
60#ifndef NDEBUG
61 VerifyModules = true;
62#else
63 VerifyModules = false;
64#endif
65
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000066 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000067 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000068}
69
Brian Gaeke92f8b302003-09-04 22:57:27 +000070ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000071 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000072}
73
Jeffrey Yasskina4044332010-03-27 04:53:56 +000074namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000075/// \brief Helper class which uses a value handler to automatically deletes the
76/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000077class GVMemoryBlock : public CallbackVH {
78 GVMemoryBlock(const GlobalVariable *GV)
79 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
80
81public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +000082 /// \brief Returns the address the GlobalVariable should be written into. The
83 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +000084 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattner229907c2011-07-18 04:54:35 +000085 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +000086 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
87 void *RawMemory = ::operator new(
David Majnemerf3cadce2014-10-20 06:13:33 +000088 RoundUpToAlignment(sizeof(GVMemoryBlock),
89 TD.getPreferredAlignment(GV))
Jeffrey Yasskina4044332010-03-27 04:53:56 +000090 + GVSize);
91 new(RawMemory) GVMemoryBlock(GV);
92 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
93 }
94
Craig Topperb51ff602014-03-08 07:51:20 +000095 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +000096 // We allocated with operator new and with some extra memory hanging off the
97 // end, so don't just delete this. I'm not sure if this is actually
98 // required.
99 this->~GVMemoryBlock();
100 ::operator delete(this);
101 }
102};
103} // anonymous namespace
104
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000105char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000106 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000107}
108
David Blaikie35907d82014-04-29 22:04:55 +0000109void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
110 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
111}
112
Rafael Espindola7271c192014-08-26 21:04:04 +0000113void
114ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
115 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
116}
117
Rafael Espindola48af1c22014-08-19 18:44:46 +0000118void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000119 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
120}
121
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000122bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000123 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
124 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000125 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000126 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000127 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000128 clearGlobalMappingsFromModule(M);
129 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000130 }
131 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000132 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000133}
134
Chris Lattner0621cae2006-08-16 01:24:12 +0000135Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
136 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000137 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattner0621cae2006-08-16 01:24:12 +0000138 return F;
139 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000140 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000141}
142
143
Zachary Turner2f825df2014-06-16 20:54:28 +0000144void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000145 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000146 void *OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000147
148 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
149 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000150 if (I == GlobalAddressMap.end())
Craig Topper2617dcc2014-04-15 06:32:26 +0000151 OldVal = nullptr;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000152 else {
153 OldVal = I->second;
154 GlobalAddressMap.erase(I);
155 }
156
157 GlobalAddressReverseMap.erase(OldVal);
158 return OldVal;
159}
160
Chris Lattner6d8dd182006-05-08 22:00:52 +0000161void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000162 MutexGuard locked(lock);
Evan Cheng5cc53c32008-09-18 07:54:21 +0000163
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000164 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar9813b0b2009-07-26 07:49:05 +0000165 << "\' to [" << Addr << "]\n";);
Zachary Turner2f825df2014-06-16 20:54:28 +0000166 void *&CurVal = EEState.getGlobalAddressMap()[GV];
Craig Topper2617dcc2014-04-15 06:32:26 +0000167 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000168 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000169
170 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000171 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000172 AssertingVH<const GlobalValue> &V =
Zachary Turner2f825df2014-06-16 20:54:28 +0000173 EEState.getGlobalAddressReverseMap()[Addr];
Craig Topper2617dcc2014-04-15 06:32:26 +0000174 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000175 V = GV;
176 }
177}
178
Chris Lattner6d8dd182006-05-08 22:00:52 +0000179void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000180 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000181
Zachary Turner2f825df2014-06-16 20:54:28 +0000182 EEState.getGlobalAddressMap().clear();
183 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000184}
185
Nate Begeman8f83fc42008-05-21 16:34:48 +0000186void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000187 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000188
189 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Zachary Turner2f825df2014-06-16 20:54:28 +0000190 EEState.RemoveMapping(FI);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000191 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
192 GI != GE; ++GI)
Zachary Turner2f825df2014-06-16 20:54:28 +0000193 EEState.RemoveMapping(GI);
Nate Begeman8f83fc42008-05-21 16:34:48 +0000194}
195
Chris Lattneree181732008-04-04 04:47:41 +0000196void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000197 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000198
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000199 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000200 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000201
Chris Lattner6d8dd182006-05-08 22:00:52 +0000202 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000203 if (!Addr)
Zachary Turner2f825df2014-06-16 20:54:28 +0000204 return EEState.RemoveMapping(GV);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000205
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000206 void *&CurVal = Map[GV];
Chris Lattneree181732008-04-04 04:47:41 +0000207 void *OldVal = CurVal;
208
Zachary Turner2f825df2014-06-16 20:54:28 +0000209 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
210 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000211 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000212
213 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000214 if (!EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000215 AssertingVH<const GlobalValue> &V =
Zachary Turner2f825df2014-06-16 20:54:28 +0000216 EEState.getGlobalAddressReverseMap()[Addr];
Craig Topper2617dcc2014-04-15 06:32:26 +0000217 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000218 V = GV;
219 }
Chris Lattneree181732008-04-04 04:47:41 +0000220 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000221}
222
Chris Lattner6d8dd182006-05-08 22:00:52 +0000223void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000224 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000225
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000226 ExecutionEngineState::GlobalAddressMapTy::iterator I =
Zachary Turner2f825df2014-06-16 20:54:28 +0000227 EEState.getGlobalAddressMap().find(GV);
228 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000229}
230
Chris Lattner748e8572003-12-31 20:21:04 +0000231const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000232 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000233
Chris Lattner748e8572003-12-31 20:21:04 +0000234 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000235 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000236 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Zachary Turner2f825df2014-06-16 20:54:28 +0000237 I = EEState.getGlobalAddressMap().begin(),
238 E = EEState.getGlobalAddressMap().end(); I != E; ++I)
239 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Daniel Dunbare4f47432010-11-13 00:55:42 +0000240 I->second, I->first));
Chris Lattner748e8572003-12-31 20:21:04 +0000241 }
242
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000243 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Zachary Turner2f825df2014-06-16 20:54:28 +0000244 EEState.getGlobalAddressReverseMap().find(Addr);
245 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000246}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000247
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000248namespace {
249class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000250 std::unique_ptr<char[]> Array;
251 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000252public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000253 /// Turn a vector of strings into a nice argv style array of pointers to null
254 /// terminated strings.
255 void *reset(LLVMContext &C, ExecutionEngine *EE,
256 const std::vector<std::string> &InputArgv);
257};
258} // anonymous namespace
259void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
260 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000261 Values.clear(); // Free the old contents.
262 Values.reserve(InputArgv.size());
Chandler Carruth5da3f052012-11-01 09:14:31 +0000263 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000264 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000265
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000266 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000267 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000268
269 for (unsigned i = 0; i != InputArgv.size(); ++i) {
270 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000271 auto Dest = make_unique<char[]>(Size);
272 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000273
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000274 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000275 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000276
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000277 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000278 EE->StoreValueToMemory(PTOGV(Dest.get()),
279 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
280 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000281 }
282
283 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000284 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000285 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000286 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000287 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000288}
289
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000290void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000291 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000292 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000293 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000294
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000295 // If this global has internal linkage, or if it has a use, then it must be
296 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
297 // this is the case, don't execute any of the global ctors, __main will do
298 // it.
299 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
300
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000301 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000302 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000303 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000304 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000305 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000306 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000307 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000308 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000309
310 Constant *FP = CS->getOperand(1);
311 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000312 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000313
314 // Strip off constant expression casts.
315 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
316 if (CE->isCast())
317 FP = CE->getOperand(0);
318
319 // Execute the ctor/dtor function!
320 if (Function *F = dyn_cast<Function>(FP))
321 runFunction(F, std::vector<GenericValue>());
322
323 // FIXME: It is marginally lame that we just do nothing here if we see an
324 // entry we don't recognize. It might not be unreasonable for the verifier
325 // to not even allow this and just assert here.
326 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000327}
328
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000329void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
330 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000331 for (std::unique_ptr<Module> &M : Modules)
332 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000333}
334
Dan Gohmancf3e3012008-08-26 01:38:29 +0000335#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000336/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
337static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth5da3f052012-11-01 09:14:31 +0000338 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000339 for (unsigned i = 0; i < PtrSize; ++i)
340 if (*(i + (uint8_t*)Loc))
341 return false;
342 return true;
343}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000344#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000345
Chris Lattner5a0d4822003-12-26 06:50:30 +0000346int ExecutionEngine::runFunctionAsMain(Function *Fn,
347 const std::vector<std::string> &argv,
348 const char * const * envp) {
349 std::vector<GenericValue> GVArgs;
350 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000351 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000352
353 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000354 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000355 FunctionType *FTy = Fn->getFunctionType();
356 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000357
358 // Check the argument types.
359 if (NumArgs > 3)
360 report_fatal_error("Invalid number of arguments of main() supplied");
361 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
362 report_fatal_error("Invalid type for third argument of main() supplied");
363 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
364 report_fatal_error("Invalid type for second argument of main() supplied");
365 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
366 report_fatal_error("Invalid type for first argument of main() supplied");
367 if (!FTy->getReturnType()->isIntegerTy() &&
368 !FTy->getReturnType()->isVoidTy())
369 report_fatal_error("Invalid return type of main() supplied");
370
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000371 ArgvArray CArgv;
372 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000373 if (NumArgs) {
374 GVArgs.push_back(GVArgc); // Arg #0 = argc.
375 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000376 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000377 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000378 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000379 "argv[0] was null after CreateArgv");
380 if (NumArgs > 2) {
381 std::vector<std::string> EnvVars;
382 for (unsigned i = 0; envp[i]; ++i)
383 EnvVars.push_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000384 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000385 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000386 }
387 }
388 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000389
Reid Spencer87aa65f2007-03-06 03:04:04 +0000390 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000391}
392
Alp Toker322db9e2014-05-31 21:26:17 +0000393void EngineBuilder::InitEngine() {
394 WhichEngine = EngineKind::Either;
395 ErrorStr = nullptr;
396 OptLevel = CodeGenOpt::Default;
397 MCJMM = nullptr;
Alp Toker322db9e2014-05-31 21:26:17 +0000398 Options = TargetOptions();
Alp Toker322db9e2014-05-31 21:26:17 +0000399 RelocModel = Reloc::Default;
400 CMModel = CodeModel::JITDefault;
Alp Toker322db9e2014-05-31 21:26:17 +0000401
402// IR module verification is enabled by default in debug builds, and disabled
403// by default in release builds.
404#ifndef NDEBUG
405 VerifyModules = true;
406#else
407 VerifyModules = false;
408#endif
409}
410
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000411ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000412 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000413
Nick Lewyckya53414f2008-03-08 02:49:45 +0000414 // Make sure we can resolve symbols in the program as well. The zero arg
415 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000416 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
417 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000418
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000419 // If the user specified a memory manager but didn't specify which engine to
420 // create, we assume they only want the JIT, and we fail if they only want
421 // the interpreter.
Lang Hames0f154902014-09-23 16:56:02 +0000422 if (MCJMM) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000423 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000424 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000425 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000426 if (ErrorStr)
427 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000428 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000429 }
430 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000431
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000432 // Unless the interpreter was explicitly selected or the JIT is not linked,
433 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000434 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000435 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000436 if (!TM->getTarget().hasJIT()) {
437 errs() << "WARNING: This target JIT is not designed for the host"
438 << " you are running. If bad things happen, please choose"
439 << " a different -march switch.\n";
440 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000441
Lang Hamesbc876012014-04-18 06:48:23 +0000442 ExecutionEngine *EE = nullptr;
Eric Christopher79cc1e32014-09-02 22:28:02 +0000443 if (ExecutionEngine::MCJITCtor)
Lang Hames0f154902014-09-23 16:56:02 +0000444 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, MCJMM,
445 std::move(TheTM));
Lang Hamesbc876012014-04-18 06:48:23 +0000446 if (EE) {
447 EE->setVerifyModules(VerifyModules);
448 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000449 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000450 }
451
452 // If we can't make a JIT and we didn't request one specifically, try making
453 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000454 if (WhichEngine & EngineKind::Interpreter) {
455 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000456 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000457 if (ErrorStr)
458 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000459 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000460 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000461
Eric Christopher79cc1e32014-09-02 22:28:02 +0000462 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000463 if (ErrorStr)
464 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000465 }
466
Craig Topper2617dcc2014-04-15 06:32:26 +0000467 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000468}
469
Chris Lattner996fe012002-12-24 00:01:05 +0000470void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000471 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000472 return getPointerToFunction(F);
473
Zachary Turnerc04b8922014-06-20 21:07:14 +0000474 MutexGuard locked(lock);
Zachary Turner2f825df2014-06-16 20:54:28 +0000475 if (void *P = EEState.getGlobalAddressMap()[GV])
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000476 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000477
478 // Global variable might have been added since interpreter started.
479 if (GlobalVariable *GVar =
480 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
481 EmitGlobalVariable(GVar);
482 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000483 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000484
Zachary Turner2f825df2014-06-16 20:54:28 +0000485 return EEState.getGlobalAddressMap()[GV];
Chris Lattner996fe012002-12-24 00:01:05 +0000486}
487
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000488/// \brief Converts a Constant* into a GenericValue, including handling of
489/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000490GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000491 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000492 if (isa<UndefValue>(C)) {
493 GenericValue Result;
494 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000495 default:
496 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000497 case Type::IntegerTyID:
498 case Type::X86_FP80TyID:
499 case Type::FP128TyID:
500 case Type::PPC_FP128TyID:
501 // Although the value is undefined, we still have to construct an APInt
502 // with the correct bit width.
503 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
504 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000505 case Type::StructTyID: {
506 // if the whole struct is 'undef' just reserve memory for the value.
507 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
508 unsigned int elemNum = STy->getNumElements();
509 Result.AggregateVal.resize(elemNum);
510 for (unsigned int i = 0; i < elemNum; ++i) {
511 Type *ElemTy = STy->getElementType(i);
512 if (ElemTy->isIntegerTy())
513 Result.AggregateVal[i].IntVal =
514 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
515 else if (ElemTy->isAggregateType()) {
516 const Constant *ElemUndef = UndefValue::get(ElemTy);
517 Result.AggregateVal[i] = getConstantValue(ElemUndef);
518 }
519 }
520 }
521 }
522 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000523 case Type::VectorTyID:
524 // if the whole vector is 'undef' just reserve memory for the value.
525 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
526 const Type *ElemTy = VTy->getElementType();
527 unsigned int elemNum = VTy->getNumElements();
528 Result.AggregateVal.resize(elemNum);
529 if (ElemTy->isIntegerTy())
530 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000531 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000532 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000533 break;
534 }
535 return Result;
536 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000537
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000538 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000539 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000540 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000541 switch (CE->getOpcode()) {
542 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000543 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000544 GenericValue Result = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000545 APInt Offset(DL->getPointerSizeInBits(), 0);
546 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000547
Reid Spencer87aa65f2007-03-06 03:04:04 +0000548 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000549 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000550 return Result;
551 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000552 case Instruction::Trunc: {
553 GenericValue GV = getConstantValue(Op0);
554 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
555 GV.IntVal = GV.IntVal.trunc(BitWidth);
556 return GV;
557 }
558 case Instruction::ZExt: {
559 GenericValue GV = getConstantValue(Op0);
560 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
561 GV.IntVal = GV.IntVal.zext(BitWidth);
562 return GV;
563 }
564 case Instruction::SExt: {
565 GenericValue GV = getConstantValue(Op0);
566 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
567 GV.IntVal = GV.IntVal.sext(BitWidth);
568 return GV;
569 }
570 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000571 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000572 GenericValue GV = getConstantValue(Op0);
573 GV.FloatVal = float(GV.DoubleVal);
574 return GV;
575 }
576 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000577 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000578 GenericValue GV = getConstantValue(Op0);
579 GV.DoubleVal = double(GV.FloatVal);
580 return GV;
581 }
582 case Instruction::UIToFP: {
583 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000584 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000585 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000586 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000587 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000588 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000589 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000590 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000591 false,
592 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000593 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000594 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000595 return GV;
596 }
597 case Instruction::SIToFP: {
598 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000599 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000600 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000601 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000602 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000603 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000604 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000605 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000606 true,
607 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000608 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000609 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000610 return GV;
611 }
612 case Instruction::FPToUI: // double->APInt conversion handles sign
613 case Instruction::FPToSI: {
614 GenericValue GV = getConstantValue(Op0);
615 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000616 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000617 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000618 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000619 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000620 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000621 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000622 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000623 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000624 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000625 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000626 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000627 GV.IntVal = v; // endian?
628 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000629 return GV;
630 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000631 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000632 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000633 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000634 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000635 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000636 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000637 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000638 return GV;
639 }
640 case Instruction::IntToPtr: {
641 GenericValue GV = getConstantValue(Op0);
Rafael Espindola7c68beb2014-02-18 15:33:12 +0000642 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000643 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000644 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
645 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000646 return GV;
647 }
648 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000649 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000650 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000651 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000652 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000653 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000654 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000655 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000656 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000657 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000658 GV.DoubleVal = GV.IntVal.bitsToDouble();
659 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000660 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000661 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000662 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000663 break;
664 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000665 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000666 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000667 break;
668 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000669 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000670 break; // getConstantValue(Op0) above already converted it
671 }
672 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000673 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000674 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000675 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000676 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000677 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000678 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000679 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000680 case Instruction::UDiv:
681 case Instruction::SDiv:
682 case Instruction::URem:
683 case Instruction::SRem:
684 case Instruction::And:
685 case Instruction::Or:
686 case Instruction::Xor: {
687 GenericValue LHS = getConstantValue(Op0);
688 GenericValue RHS = getConstantValue(CE->getOperand(1));
689 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000690 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000691 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000692 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000693 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000694 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000695 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
696 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
697 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
698 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
699 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
700 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
701 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
702 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
703 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
704 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
705 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000706 break;
707 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000708 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000709 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000710 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000711 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000712 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000713 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000714 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000715 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000716 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000717 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000718 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000719 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000720 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000721 break;
722 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000723 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000724 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000725 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000726 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000727 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000728 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000729 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000730 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000731 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000732 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000733 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000734 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000735 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000736 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000737 case Type::X86_FP80TyID:
738 case Type::PPC_FP128TyID:
739 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000740 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
741 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000742 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000743 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000744 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000745 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000746 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000747 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000748 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000749 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
750 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000751 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000752 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000753 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000754 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
755 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000756 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000757 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000758 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000759 apfLHS.divide(APFloat(Sem, RHS.IntVal),
760 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000761 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000762 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000763 case Instruction::FRem:
Tim Northover29178a32013-01-22 09:46:31 +0000764 apfLHS.mod(APFloat(Sem, RHS.IntVal),
765 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000766 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000767 break;
768 }
769 }
770 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000771 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000772 return GV;
773 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000774 default:
775 break;
776 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000777
778 SmallString<256> Msg;
779 raw_svector_ostream OS(Msg);
780 OS << "ConstantExpr not handled: " << *CE;
781 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000782 }
Misha Brukman835702a2005-04-21 22:36:52 +0000783
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000784 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000785 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000786 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000787 case Type::FloatTyID:
788 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000789 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000790 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000791 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000792 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000793 case Type::X86_FP80TyID:
794 case Type::FP128TyID:
795 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000796 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000797 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000798 case Type::IntegerTyID:
799 Result.IntVal = cast<ConstantInt>(C)->getValue();
800 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000801 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000802 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000803 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000804 else if (const Function *F = dyn_cast<Function>(C))
805 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000806 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000807 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
808 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000809 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000810 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000811 case Type::VectorTyID: {
812 unsigned elemNum;
813 Type* ElemTy;
814 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
815 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
816 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
817
818 if (CDV) {
819 elemNum = CDV->getNumElements();
820 ElemTy = CDV->getElementType();
821 } else if (CV || CAZ) {
822 VectorType* VTy = dyn_cast<VectorType>(C->getType());
823 elemNum = VTy->getNumElements();
824 ElemTy = VTy->getElementType();
825 } else {
826 llvm_unreachable("Unknown constant vector type!");
827 }
828
829 Result.AggregateVal.resize(elemNum);
830 // Check if vector holds floats.
831 if(ElemTy->isFloatTy()) {
832 if (CAZ) {
833 GenericValue floatZero;
834 floatZero.FloatVal = 0.f;
835 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
836 floatZero);
837 break;
838 }
839 if(CV) {
840 for (unsigned i = 0; i < elemNum; ++i)
841 if (!isa<UndefValue>(CV->getOperand(i)))
842 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
843 CV->getOperand(i))->getValueAPF().convertToFloat();
844 break;
845 }
846 if(CDV)
847 for (unsigned i = 0; i < elemNum; ++i)
848 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
849
850 break;
851 }
852 // Check if vector holds doubles.
853 if (ElemTy->isDoubleTy()) {
854 if (CAZ) {
855 GenericValue doubleZero;
856 doubleZero.DoubleVal = 0.0;
857 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
858 doubleZero);
859 break;
860 }
861 if(CV) {
862 for (unsigned i = 0; i < elemNum; ++i)
863 if (!isa<UndefValue>(CV->getOperand(i)))
864 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
865 CV->getOperand(i))->getValueAPF().convertToDouble();
866 break;
867 }
868 if(CDV)
869 for (unsigned i = 0; i < elemNum; ++i)
870 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
871
872 break;
873 }
874 // Check if vector holds integers.
875 if (ElemTy->isIntegerTy()) {
876 if (CAZ) {
877 GenericValue intZero;
878 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
879 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
880 intZero);
881 break;
882 }
883 if(CV) {
884 for (unsigned i = 0; i < elemNum; ++i)
885 if (!isa<UndefValue>(CV->getOperand(i)))
886 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
887 CV->getOperand(i))->getValue();
888 else {
889 Result.AggregateVal[i].IntVal =
890 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
891 }
892 break;
893 }
894 if(CDV)
895 for (unsigned i = 0; i < elemNum; ++i)
896 Result.AggregateVal[i].IntVal = APInt(
897 CDV->getElementType()->getPrimitiveSizeInBits(),
898 CDV->getElementAsInteger(i));
899
900 break;
901 }
902 llvm_unreachable("Unknown constant pointer type!");
903 }
904 break;
905
Chris Lattner996fe012002-12-24 00:01:05 +0000906 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000907 SmallString<256> Msg;
908 raw_svector_ostream OS(Msg);
909 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
910 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +0000911 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000912
Chris Lattner996fe012002-12-24 00:01:05 +0000913 return Result;
914}
915
Duncan Sands1202d1b2007-12-14 19:38:31 +0000916/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
917/// with the integer held in IntVal.
918static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
919 unsigned StoreBytes) {
920 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +0000921 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000922
Rafael Espindola41cb64f2013-04-15 14:44:24 +0000923 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000924 // Little-endian host - the source is ordered from LSB to MSB. Order the
925 // destination from LSB to MSB: Do a straight copy.
926 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000927 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000928 // Big-endian host - the source is an array of 64 bit words ordered from
929 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
930 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
931 while (StoreBytes > sizeof(uint64_t)) {
932 StoreBytes -= sizeof(uint64_t);
933 // May not be aligned so use memcpy.
934 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
935 Src += sizeof(uint64_t);
936 }
937
938 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
939 }
940}
941
Evan Cheng09053e62008-11-04 06:10:31 +0000942void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +0000943 GenericValue *Ptr, Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000944 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +0000945
Reid Spencer87aa65f2007-03-06 03:04:04 +0000946 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000947 default:
948 dbgs() << "Cannot store value of type " << *Ty << "!\n";
949 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000950 case Type::IntegerTyID:
951 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000952 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000953 case Type::FloatTyID:
954 *((float*)Ptr) = Val.FloatVal;
955 break;
956 case Type::DoubleTyID:
957 *((double*)Ptr) = Val.DoubleVal;
958 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000959 case Type::X86_FP80TyID:
960 memcpy(Ptr, Val.IntVal.getRawData(), 10);
961 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000962 case Type::PointerTyID:
963 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
964 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +0000965 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +0000966
Reid Spencer87aa65f2007-03-06 03:04:04 +0000967 *((PointerTy*)Ptr) = Val.PointerVal;
968 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000969 case Type::VectorTyID:
970 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
971 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
972 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
973 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
974 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
975 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
976 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
977 StoreIntToMemory(Val.AggregateVal[i].IntVal,
978 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
979 }
980 }
981 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000982 }
Duncan Sands1202d1b2007-12-14 19:38:31 +0000983
Rafael Espindola41cb64f2013-04-15 14:44:24 +0000984 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000985 // Host and target are different endian - reverse the stored bytes.
986 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
987}
988
989/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
990/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
991static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
992 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +0000993 uint8_t *Dst = reinterpret_cast<uint8_t *>(
994 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000995
Rafael Espindola41cb64f2013-04-15 14:44:24 +0000996 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +0000997 // Little-endian host - the destination must be ordered from LSB to MSB.
998 // The source is ordered from LSB to MSB: Do a straight copy.
999 memcpy(Dst, Src, LoadBytes);
1000 else {
1001 // Big-endian - the destination is an array of 64 bit words ordered from
1002 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1003 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1004 // a word.
1005 while (LoadBytes > sizeof(uint64_t)) {
1006 LoadBytes -= sizeof(uint64_t);
1007 // May not be aligned so use memcpy.
1008 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1009 Dst += sizeof(uint64_t);
1010 }
1011
1012 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1013 }
Chris Lattner996fe012002-12-24 00:01:05 +00001014}
1015
Misha Brukman857c21b2003-10-10 17:45:12 +00001016/// FIXME: document
1017///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001018void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001019 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001020 Type *Ty) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001021 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001022
Duncan Sands1202d1b2007-12-14 19:38:31 +00001023 switch (Ty->getTypeID()) {
1024 case Type::IntegerTyID:
1025 // An APInt with all words initially zero.
1026 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1027 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1028 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001029 case Type::FloatTyID:
1030 Result.FloatVal = *((float*)Ptr);
1031 break;
1032 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001033 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001034 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001035 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001036 Result.PointerVal = *((PointerTy*)Ptr);
1037 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001038 case Type::X86_FP80TyID: {
1039 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001040 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001041 uint64_t y[2];
1042 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001043 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001044 break;
1045 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001046 case Type::VectorTyID: {
1047 const VectorType *VT = cast<VectorType>(Ty);
1048 const Type *ElemT = VT->getElementType();
1049 const unsigned numElems = VT->getNumElements();
1050 if (ElemT->isFloatTy()) {
1051 Result.AggregateVal.resize(numElems);
1052 for (unsigned i = 0; i < numElems; ++i)
1053 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1054 }
1055 if (ElemT->isDoubleTy()) {
1056 Result.AggregateVal.resize(numElems);
1057 for (unsigned i = 0; i < numElems; ++i)
1058 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1059 }
1060 if (ElemT->isIntegerTy()) {
1061 GenericValue intZero;
1062 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1063 intZero.IntVal = APInt(elemBitWidth, 0);
1064 Result.AggregateVal.resize(numElems, intZero);
1065 for (unsigned i = 0; i < numElems; ++i)
1066 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1067 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1068 }
1069 break;
1070 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001071 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001072 SmallString<256> Msg;
1073 raw_svector_ostream OS(Msg);
1074 OS << "Cannot load value of type " << *Ty << "!";
1075 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001076 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001077}
1078
Chris Lattner996fe012002-12-24 00:01:05 +00001079void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001080 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001081 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001082 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001083 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001084
1085 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001086 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001087 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001088 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1089 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1090 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001091 }
1092
1093 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001094 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001095 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001096 }
1097
1098 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001099 unsigned ElementSize =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001100 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001101 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1102 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1103 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001104 }
1105
1106 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001107 const StructLayout *SL =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001108 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001109 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1110 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1111 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001112 }
1113
1114 if (const ConstantDataSequential *CDS =
1115 dyn_cast<ConstantDataSequential>(Init)) {
1116 // CDS is already laid out in host memory order.
1117 StringRef Data = CDS->getRawDataValues();
1118 memcpy(Addr, Data.data(), Data.size());
1119 return;
1120 }
1121
1122 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001123 GenericValue Val = getConstantValue(Init);
1124 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1125 return;
1126 }
1127
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001128 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001129 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001130}
1131
Chris Lattner996fe012002-12-24 00:01:05 +00001132/// EmitGlobals - Emit all of the global variables to memory, storing their
1133/// addresses into GlobalAddress. This must make sure to copy the contents of
1134/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001135void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001136 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001137 // to hold them. If there is more than one module, do a prepass over globals
1138 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001139 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001140 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001141
Chris Lattner0621cae2006-08-16 01:24:12 +00001142 if (Modules.size() != 1) {
1143 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001144 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001145 for (const auto &GV : M.globals()) {
1146 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1147 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001148 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001149
1150 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001151 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001152
1153 // If this is the first time we've seen this global, it is the canonical
1154 // version.
1155 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001156 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001157 continue;
1158 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001159
Chris Lattner0621cae2006-08-16 01:24:12 +00001160 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001161 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001162 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001163
Chris Lattner0621cae2006-08-16 01:24:12 +00001164 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001165 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001166 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1167 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001168 }
Chris Lattner996fe012002-12-24 00:01:05 +00001169 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001170 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001171
Chris Lattner0621cae2006-08-16 01:24:12 +00001172 std::vector<const GlobalValue*> NonCanonicalGlobals;
1173 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001174 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001175 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001176 // In the multi-module case, see what this global maps to.
1177 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001178 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001179 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001180 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001181 if (GVEntry != &GV) {
1182 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001183 continue;
1184 }
1185 }
1186 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001187
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001188 if (!GV.isDeclaration()) {
1189 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001190 } else {
1191 // External variable reference. Try to use the dynamic loader to
1192 // get a pointer to it.
1193 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001194 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1195 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001196 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001197 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001198 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001199 }
1200 }
1201 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001202
Chris Lattner0621cae2006-08-16 01:24:12 +00001203 // If there are multiple modules, map the non-canonical globals to their
1204 // canonical location.
1205 if (!NonCanonicalGlobals.empty()) {
1206 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1207 const GlobalValue *GV = NonCanonicalGlobals[i];
1208 const GlobalValue *CGV =
1209 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1210 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1211 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001212 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001213 }
1214 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001215
1216 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001217 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001218 for (const auto &GV : M.globals()) {
1219 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001220 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001221 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001222 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1223 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001224 continue;
1225 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001226 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001227 }
1228 }
1229 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001230}
1231
1232// EmitGlobalVariable - This method emits the specified global variable to the
1233// address specified in GlobalAddresses, or allocates new memory if it's not
1234// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001235void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001236 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001237
Craig Topper2617dcc2014-04-15 06:32:26 +00001238 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001239 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001240 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001241
1242 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001243 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001244
Chris Lattner748e8572003-12-31 20:21:04 +00001245 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001246 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001247
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001248 // Don't initialize if it's thread local, let the client do it.
1249 if (!GV->isThreadLocal())
1250 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001251
Chris Lattner229907c2011-07-18 04:54:35 +00001252 Type *ElTy = GV->getType()->getElementType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001253 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001254 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001255 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001256}
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001257
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001258ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1259 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001260}
1261
Zachary Turnerc04b8922014-06-20 21:07:14 +00001262sys::Mutex *
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001263ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001264 return &EES->EE.lock;
1265}
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001266
1267void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1268 const GlobalValue *Old) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001269 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1270 EES->GlobalAddressReverseMap.erase(OldVal);
1271}
1272
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001273void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1274 const GlobalValue *,
1275 const GlobalValue *) {
Craig Toppera2886c22012-02-07 05:05:23 +00001276 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1277 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001278}