blob: de3d647438b4c0fadf128606d30141c4e435af32 [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"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbar868e3f02010-11-13 02:48:57 +000017#include "llvm/ADT/SmallString.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000018#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ExecutionEngine/GenericValue.h"
Lang Hamesb5c7b1f2014-11-26 16:54:40 +000020#include "llvm/ExecutionEngine/JITEventListener.h"
Lang Hames633fe142015-03-30 03:37:06 +000021#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
Lang Hames3dac3f72015-03-31 20:31:14 +000025#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
27#include "llvm/IR/Operator.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000028#include "llvm/IR/ValueHandle.h"
Rafael Espindoladd396572014-08-01 19:28:15 +000029#include "llvm/Object/Archive.h"
David Blaikie35907d82014-04-29 22:04:55 +000030#include "llvm/Object/ObjectFile.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/DynamicLibrary.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000033#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/Host.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000035#include "llvm/Support/MutexGuard.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/TargetRegistry.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000037#include "llvm/Support/raw_ostream.h"
Dylan Noblesmith8418fdc2011-05-13 21:51:29 +000038#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000039#include <cmath>
40#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000041using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000042
Chandler Carruthf58e3762014-04-22 03:04:17 +000043#define DEBUG_TYPE "jit"
44
Chris Lattnerc346ecd2006-12-19 22:43:32 +000045STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
46STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000047
Daniel Dunbar70ff8b02010-11-17 16:06:37 +000048ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
David Blaikie196e3232014-09-02 22:41:07 +000049 std::unique_ptr<Module> M, std::string *ErrorStr,
Lang Hames633fe142015-03-30 03:37:06 +000050 std::shared_ptr<MCJITMemoryManager> MemMgr,
51 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
Lang Hames4a5697e2014-12-03 00:51:19 +000052 std::unique_ptr<TargetMachine> TM) = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +000053
54ExecutionEngine *(*ExecutionEngine::OrcMCJITReplacementCtor)(
Lang Hames633fe142015-03-30 03:37:06 +000055 std::string *ErrorStr, std::shared_ptr<MCJITMemoryManager> MemMgr,
56 std::shared_ptr<RuntimeDyld::SymbolResolver> Resolver,
Lang Hames93de2a12015-01-23 21:25:00 +000057 std::unique_ptr<TargetMachine> TM) = nullptr;
58
Rafael Espindola2a8a2792014-08-19 04:04:25 +000059ExecutionEngine *(*ExecutionEngine::InterpCtor)(std::unique_ptr<Module> M,
Craig Topper2617dcc2014-04-15 06:32:26 +000060 std::string *ErrorStr) =nullptr;
Chris Lattner2d52c1b2006-03-22 06:07:50 +000061
Lang Hames7ea98e12014-11-27 01:41:16 +000062void JITEventListener::anchor() {}
63
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000064void ExecutionEngine::Init(std::unique_ptr<Module> M) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000065 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000066 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000067 SymbolSearchingDisabled = false;
Lang Hamesbc876012014-04-18 06:48:23 +000068
69 // IR module verification is enabled by default in debug builds, and disabled
70 // by default in release builds.
71#ifndef NDEBUG
72 VerifyModules = true;
73#else
74 VerifyModules = false;
75#endif
76
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000077 assert(M && "Module is null?");
Rafael Espindola2a8a2792014-08-19 04:04:25 +000078 Modules.push_back(std::move(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000079}
80
Mehdi Aminia3fcefb2015-07-16 16:34:23 +000081ExecutionEngine::ExecutionEngine(std::unique_ptr<Module> M)
82 : DL(M->getDataLayout()), LazyFunctionCreator(nullptr) {
83 Init(std::move(M));
84}
85
86ExecutionEngine::ExecutionEngine(DataLayout DL, std::unique_ptr<Module> M)
87 : DL(std::move(DL)), LazyFunctionCreator(nullptr) {
88 Init(std::move(M));
89}
90
Brian Gaeke92f8b302003-09-04 22:57:27 +000091ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000092 clearAllGlobalMappings();
Brian Gaeke92f8b302003-09-04 22:57:27 +000093}
94
Jeffrey Yasskina4044332010-03-27 04:53:56 +000095namespace {
Daniel Dunbar868e3f02010-11-13 02:48:57 +000096/// \brief Helper class which uses a value handler to automatically deletes the
97/// memory block when the GlobalVariable is destroyed.
David Blaikie774b5842015-08-03 22:30:24 +000098class GVMemoryBlock final : public CallbackVH {
Jeffrey Yasskina4044332010-03-27 04:53:56 +000099 GVMemoryBlock(const GlobalVariable *GV)
100 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
101
102public:
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000103 /// \brief Returns the address the GlobalVariable should be written into. The
104 /// GVMemoryBlock object prefixes that.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000105 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000106 Type *ElTy = GV->getValueType();
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000107 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
108 void *RawMemory = ::operator new(
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000109 alignTo(sizeof(GVMemoryBlock), TD.getPreferredAlignment(GV)) + GVSize);
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000110 new(RawMemory) GVMemoryBlock(GV);
111 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
112 }
113
Craig Topperb51ff602014-03-08 07:51:20 +0000114 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000115 // We allocated with operator new and with some extra memory hanging off the
116 // end, so don't just delete this. I'm not sure if this is actually
117 // required.
118 this->~GVMemoryBlock();
119 ::operator delete(this);
120 }
121};
122} // anonymous namespace
123
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000124char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000125 return GVMemoryBlock::Create(GV, getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000126}
127
David Blaikie35907d82014-04-29 22:04:55 +0000128void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
129 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
130}
131
Rafael Espindola7271c192014-08-26 21:04:04 +0000132void
133ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
134 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
135}
136
Rafael Espindola48af1c22014-08-19 18:44:46 +0000137void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000138 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
139}
140
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000141bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000142 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
143 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000144 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000145 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000146 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000147 clearGlobalMappingsFromModule(M);
148 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000149 }
150 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000151 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000152}
153
Chris Lattner0621cae2006-08-16 01:24:12 +0000154Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
155 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000156 Function *F = Modules[i]->getFunction(FnName);
157 if (F && !F->isDeclaration())
Chris Lattner0621cae2006-08-16 01:24:12 +0000158 return F;
159 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000160 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000161}
162
Keno Fischer73378eb2015-06-20 00:55:58 +0000163GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
164 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
165 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
166 if (GV && !GV->isDeclaration())
167 return GV;
168 }
169 return nullptr;
170}
Chris Lattner0621cae2006-08-16 01:24:12 +0000171
Lang Hames3dac3f72015-03-31 20:31:14 +0000172uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
173 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
174 uint64_t OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000175
176 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
177 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000178 if (I == GlobalAddressMap.end())
Lang Hames3dac3f72015-03-31 20:31:14 +0000179 OldVal = 0;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000180 else {
Lang Hames3dac3f72015-03-31 20:31:14 +0000181 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000182 OldVal = I->second;
183 GlobalAddressMap.erase(I);
184 }
185
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000186 return OldVal;
187}
188
Lang Hames3dac3f72015-03-31 20:31:14 +0000189std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
Lang Hames3393cfd2015-07-29 23:12:33 +0000190 assert(GV->hasName() && "Global must have name.");
191
Lang Hames3dac3f72015-03-31 20:31:14 +0000192 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000193 SmallString<128> FullName;
Lang Hames3393cfd2015-07-29 23:12:33 +0000194
195 const DataLayout &DL =
196 GV->getParent()->getDataLayout().isDefault()
197 ? getDataLayout()
198 : GV->getParent()->getDataLayout();
199
200 Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
Lang Hames3dac3f72015-03-31 20:31:14 +0000201 return FullName.str();
202}
203
Chris Lattner6d8dd182006-05-08 22:00:52 +0000204void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000205 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000206 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
207}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000208
Lang Hames3dac3f72015-03-31 20:31:14 +0000209void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
210 MutexGuard locked(lock);
211
212 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
213
214 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
215 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000216 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000217 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000218
219 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000220 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000221 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
222 assert((!V.empty() || !Name.empty()) &&
223 "GlobalMapping already established!");
224 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000225 }
226}
227
Chris Lattner6d8dd182006-05-08 22:00:52 +0000228void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000229 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000230
Zachary Turner2f825df2014-06-16 20:54:28 +0000231 EEState.getGlobalAddressMap().clear();
232 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000233}
234
Nate Begeman8f83fc42008-05-21 16:34:48 +0000235void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000236 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000237
Duncan P. N. Exon Smith4ead9202015-10-13 18:11:02 +0000238 for (Function &FI : *M)
239 EEState.RemoveMapping(getMangledName(&FI));
240 for (GlobalVariable &GI : M->globals())
241 EEState.RemoveMapping(getMangledName(&GI));
Nate Begeman8f83fc42008-05-21 16:34:48 +0000242}
243
Lang Hames3dac3f72015-03-31 20:31:14 +0000244uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
245 void *Addr) {
246 MutexGuard locked(lock);
247 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
248}
249
250uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000251 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000252
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000253 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000254 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000255
Chris Lattner6d8dd182006-05-08 22:00:52 +0000256 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000257 if (!Addr)
Lang Hames3dac3f72015-03-31 20:31:14 +0000258 return EEState.RemoveMapping(Name);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000259
Lang Hames3dac3f72015-03-31 20:31:14 +0000260 uint64_t &CurVal = Map[Name];
261 uint64_t OldVal = CurVal;
Chris Lattneree181732008-04-04 04:47:41 +0000262
Zachary Turner2f825df2014-06-16 20:54:28 +0000263 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
264 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000265 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000266
267 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000268 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000269 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
270 assert((!V.empty() || !Name.empty()) &&
271 "GlobalMapping already established!");
272 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000273 }
Chris Lattneree181732008-04-04 04:47:41 +0000274 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000275}
276
Lang Hames3dac3f72015-03-31 20:31:14 +0000277uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
278 MutexGuard locked(lock);
279 uint64_t Address = 0;
280 ExecutionEngineState::GlobalAddressMapTy::iterator I =
281 EEState.getGlobalAddressMap().find(S);
282 if (I != EEState.getGlobalAddressMap().end())
283 Address = I->second;
284 return Address;
285}
286
287
288void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
289 MutexGuard locked(lock);
290 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
291 return Address;
292 return nullptr;
293}
294
Chris Lattner6d8dd182006-05-08 22:00:52 +0000295void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000296 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000297 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattner6d8dd182006-05-08 22:00:52 +0000298}
299
Chris Lattner748e8572003-12-31 20:21:04 +0000300const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000301 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000302
Chris Lattner748e8572003-12-31 20:21:04 +0000303 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000304 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000305 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames3dac3f72015-03-31 20:31:14 +0000306 I = EEState.getGlobalAddressMap().begin(),
307 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
308 StringRef Name = I->first();
309 uint64_t Addr = I->second;
Zachary Turner2f825df2014-06-16 20:54:28 +0000310 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames3dac3f72015-03-31 20:31:14 +0000311 Addr, Name));
312 }
Chris Lattner748e8572003-12-31 20:21:04 +0000313 }
314
Lang Hames3dac3f72015-03-31 20:31:14 +0000315 std::map<uint64_t, std::string>::iterator I =
316 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
317
318 if (I != EEState.getGlobalAddressReverseMap().end()) {
319 StringRef Name = I->second;
320 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
321 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
322 return GV;
323 }
324 return nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000325}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000326
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000327namespace {
328class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000329 std::unique_ptr<char[]> Array;
330 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000331public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000332 /// Turn a vector of strings into a nice argv style array of pointers to null
333 /// terminated strings.
334 void *reset(LLVMContext &C, ExecutionEngine *EE,
335 const std::vector<std::string> &InputArgv);
336};
337} // anonymous namespace
338void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
339 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000340 Values.clear(); // Free the old contents.
341 Values.reserve(InputArgv.size());
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000342 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000343 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000344
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000345 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000346 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000347
348 for (unsigned i = 0; i != InputArgv.size(); ++i) {
349 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000350 auto Dest = make_unique<char[]>(Size);
351 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000352
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000353 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000354 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000355
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000356 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000357 EE->StoreValueToMemory(PTOGV(Dest.get()),
358 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
359 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000360 }
361
362 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000363 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000364 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000365 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000366 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000367}
368
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000369void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000370 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000371 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000372 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000373
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000374 // If this global has internal linkage, or if it has a use, then it must be
375 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
376 // this is the case, don't execute any of the global ctors, __main will do
377 // it.
378 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
379
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000380 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000381 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000382 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000383 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000384 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000385 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000386 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000387 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000388
389 Constant *FP = CS->getOperand(1);
390 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000391 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000392
393 // Strip off constant expression casts.
394 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
395 if (CE->isCast())
396 FP = CE->getOperand(0);
397
398 // Execute the ctor/dtor function!
399 if (Function *F = dyn_cast<Function>(FP))
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000400 runFunction(F, None);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000401
402 // FIXME: It is marginally lame that we just do nothing here if we see an
403 // entry we don't recognize. It might not be unreasonable for the verifier
404 // to not even allow this and just assert here.
405 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000406}
407
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000408void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
409 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000410 for (std::unique_ptr<Module> &M : Modules)
411 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000412}
413
Dan Gohmancf3e3012008-08-26 01:38:29 +0000414#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000415/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
416static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000417 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000418 for (unsigned i = 0; i < PtrSize; ++i)
419 if (*(i + (uint8_t*)Loc))
420 return false;
421 return true;
422}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000423#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000424
Chris Lattner5a0d4822003-12-26 06:50:30 +0000425int ExecutionEngine::runFunctionAsMain(Function *Fn,
426 const std::vector<std::string> &argv,
427 const char * const * envp) {
428 std::vector<GenericValue> GVArgs;
429 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000430 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000431
432 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000433 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000434 FunctionType *FTy = Fn->getFunctionType();
435 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000436
437 // Check the argument types.
438 if (NumArgs > 3)
439 report_fatal_error("Invalid number of arguments of main() supplied");
440 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
441 report_fatal_error("Invalid type for third argument of main() supplied");
442 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
443 report_fatal_error("Invalid type for second argument of main() supplied");
444 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
445 report_fatal_error("Invalid type for first argument of main() supplied");
446 if (!FTy->getReturnType()->isIntegerTy() &&
447 !FTy->getReturnType()->isVoidTy())
448 report_fatal_error("Invalid return type of main() supplied");
449
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000450 ArgvArray CArgv;
451 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000452 if (NumArgs) {
453 GVArgs.push_back(GVArgc); // Arg #0 = argc.
454 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000455 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000456 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000457 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000458 "argv[0] was null after CreateArgv");
459 if (NumArgs > 2) {
460 std::vector<std::string> EnvVars;
461 for (unsigned i = 0; envp[i]; ++i)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000462 EnvVars.emplace_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000463 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000464 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000465 }
466 }
467 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000468
Reid Spencer87aa65f2007-03-06 03:04:04 +0000469 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000470}
471
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000472EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames93de2a12015-01-23 21:25:00 +0000473
Lang Hames4a5697e2014-12-03 00:51:19 +0000474EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000475 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +0000476 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000477 CMModel(CodeModel::JITDefault), UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000478// IR module verification is enabled by default in debug builds, and disabled
479// by default in release builds.
480#ifndef NDEBUG
481 VerifyModules = true;
482#else
483 VerifyModules = false;
484#endif
485}
486
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000487EngineBuilder::~EngineBuilder() = default;
488
489EngineBuilder &EngineBuilder::setMCJITMemoryManager(
490 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000491 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
492 MemMgr = SharedMM;
493 Resolver = SharedMM;
494 return *this;
495}
496
497EngineBuilder&
498EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
499 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
500 return *this;
501}
502
503EngineBuilder&
504EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
505 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000506 return *this;
507}
508
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000509ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000510 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000511
Nick Lewyckya53414f2008-03-08 02:49:45 +0000512 // Make sure we can resolve symbols in the program as well. The zero arg
513 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000514 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
515 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000516
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000517 // If the user specified a memory manager but didn't specify which engine to
518 // create, we assume they only want the JIT, and we fail if they only want
519 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000520 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000521 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000522 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000523 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000524 if (ErrorStr)
525 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000526 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000527 }
528 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000529
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000530 // Unless the interpreter was explicitly selected or the JIT is not linked,
531 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000532 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000533 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000534 if (!TM->getTarget().hasJIT()) {
535 errs() << "WARNING: This target JIT is not designed for the host"
536 << " you are running. If bad things happen, please choose"
537 << " a different -march switch.\n";
538 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000539
Lang Hamesbc876012014-04-18 06:48:23 +0000540 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000541 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000542 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
543 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000544 std::move(TheTM));
545 EE->addModule(std::move(M));
546 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000547 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
548 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000549
Lang Hamesbc876012014-04-18 06:48:23 +0000550 if (EE) {
551 EE->setVerifyModules(VerifyModules);
552 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000553 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000554 }
555
556 // If we can't make a JIT and we didn't request one specifically, try making
557 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000558 if (WhichEngine & EngineKind::Interpreter) {
559 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000560 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000561 if (ErrorStr)
562 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000563 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000564 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000565
Eric Christopher79cc1e32014-09-02 22:28:02 +0000566 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000567 if (ErrorStr)
568 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000569 }
570
Craig Topper2617dcc2014-04-15 06:32:26 +0000571 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000572}
573
Chris Lattner996fe012002-12-24 00:01:05 +0000574void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000575 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000576 return getPointerToFunction(F);
577
Zachary Turnerc04b8922014-06-20 21:07:14 +0000578 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000579 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000580 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000581
582 // Global variable might have been added since interpreter started.
583 if (GlobalVariable *GVar =
584 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
585 EmitGlobalVariable(GVar);
586 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000587 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000588
Lang Hames3dac3f72015-03-31 20:31:14 +0000589 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000590}
591
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000592/// \brief Converts a Constant* into a GenericValue, including handling of
593/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000594GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000595 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000596 if (isa<UndefValue>(C)) {
597 GenericValue Result;
598 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000599 default:
600 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000601 case Type::IntegerTyID:
602 case Type::X86_FP80TyID:
603 case Type::FP128TyID:
604 case Type::PPC_FP128TyID:
605 // Although the value is undefined, we still have to construct an APInt
606 // with the correct bit width.
607 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
608 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000609 case Type::StructTyID: {
610 // if the whole struct is 'undef' just reserve memory for the value.
611 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
612 unsigned int elemNum = STy->getNumElements();
613 Result.AggregateVal.resize(elemNum);
614 for (unsigned int i = 0; i < elemNum; ++i) {
615 Type *ElemTy = STy->getElementType(i);
616 if (ElemTy->isIntegerTy())
617 Result.AggregateVal[i].IntVal =
618 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
619 else if (ElemTy->isAggregateType()) {
620 const Constant *ElemUndef = UndefValue::get(ElemTy);
621 Result.AggregateVal[i] = getConstantValue(ElemUndef);
622 }
623 }
624 }
625 }
626 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000627 case Type::VectorTyID:
628 // if the whole vector is 'undef' just reserve memory for the value.
Craig Toppere3dcce92015-08-01 22:20:21 +0000629 auto* VTy = dyn_cast<VectorType>(C->getType());
630 Type *ElemTy = VTy->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000631 unsigned int elemNum = VTy->getNumElements();
632 Result.AggregateVal.resize(elemNum);
633 if (ElemTy->isIntegerTy())
634 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000635 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000636 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000637 break;
638 }
639 return Result;
640 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000641
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000642 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000643 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000644 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000645 switch (CE->getOpcode()) {
646 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000647 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000648 GenericValue Result = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000649 APInt Offset(DL.getPointerSizeInBits(), 0);
650 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000651
Reid Spencer87aa65f2007-03-06 03:04:04 +0000652 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000653 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000654 return Result;
655 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000656 case Instruction::Trunc: {
657 GenericValue GV = getConstantValue(Op0);
658 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
659 GV.IntVal = GV.IntVal.trunc(BitWidth);
660 return GV;
661 }
662 case Instruction::ZExt: {
663 GenericValue GV = getConstantValue(Op0);
664 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
665 GV.IntVal = GV.IntVal.zext(BitWidth);
666 return GV;
667 }
668 case Instruction::SExt: {
669 GenericValue GV = getConstantValue(Op0);
670 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
671 GV.IntVal = GV.IntVal.sext(BitWidth);
672 return GV;
673 }
674 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000675 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000676 GenericValue GV = getConstantValue(Op0);
677 GV.FloatVal = float(GV.DoubleVal);
678 return GV;
679 }
680 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000681 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000682 GenericValue GV = getConstantValue(Op0);
683 GV.DoubleVal = double(GV.FloatVal);
684 return GV;
685 }
686 case Instruction::UIToFP: {
687 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000688 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000689 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000690 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000691 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000692 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000693 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000694 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000695 false,
696 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000697 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000698 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000699 return GV;
700 }
701 case Instruction::SIToFP: {
702 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000703 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000704 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000705 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000706 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000707 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000708 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000709 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000710 true,
711 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000712 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000713 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000714 return GV;
715 }
716 case Instruction::FPToUI: // double->APInt conversion handles sign
717 case Instruction::FPToSI: {
718 GenericValue GV = getConstantValue(Op0);
719 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000720 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000721 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000722 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000723 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000724 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000725 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000726 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000727 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000728 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000729 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000730 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000731 GV.IntVal = v; // endian?
732 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000733 return GV;
734 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000735 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000736 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000737 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000738 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000739 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000740 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000741 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000742 return GV;
743 }
744 case Instruction::IntToPtr: {
745 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000746 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000747 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000748 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
749 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000750 return GV;
751 }
752 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000753 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000754 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000755 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000756 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000757 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000758 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000759 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000760 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000761 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000762 GV.DoubleVal = GV.IntVal.bitsToDouble();
763 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000764 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000765 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000766 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000767 break;
768 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000769 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000770 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000771 break;
772 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000773 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000774 break; // getConstantValue(Op0) above already converted it
775 }
776 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000777 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000778 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000779 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000780 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000781 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000782 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000783 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000784 case Instruction::UDiv:
785 case Instruction::SDiv:
786 case Instruction::URem:
787 case Instruction::SRem:
788 case Instruction::And:
789 case Instruction::Or:
790 case Instruction::Xor: {
791 GenericValue LHS = getConstantValue(Op0);
792 GenericValue RHS = getConstantValue(CE->getOperand(1));
793 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000794 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000795 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000796 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000797 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000798 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000799 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
800 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
801 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
802 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
803 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
804 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
805 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
806 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
807 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
808 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
809 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000810 break;
811 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000812 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000813 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000814 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000815 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000816 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000817 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000818 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000819 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000820 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000821 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000822 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000823 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000824 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000825 break;
826 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000827 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000828 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000829 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000830 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000831 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000832 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000833 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000834 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000835 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000836 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000837 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000838 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000839 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000840 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000841 case Type::X86_FP80TyID:
842 case Type::PPC_FP128TyID:
843 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000844 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
845 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000846 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000847 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000848 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000849 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000850 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000851 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000852 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000853 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
854 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000855 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000856 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000857 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000858 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
859 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000860 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000861 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000862 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000863 apfLHS.divide(APFloat(Sem, RHS.IntVal),
864 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000865 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000866 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000867 case Instruction::FRem:
Stephen Canonb12db0e2015-09-21 19:29:25 +0000868 apfLHS.mod(APFloat(Sem, RHS.IntVal));
Dale Johannesen54306fe2008-10-09 18:53:47 +0000869 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000870 break;
871 }
872 }
873 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000874 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000875 return GV;
876 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000877 default:
878 break;
879 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000880
881 SmallString<256> Msg;
882 raw_svector_ostream OS(Msg);
883 OS << "ConstantExpr not handled: " << *CE;
884 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000885 }
Misha Brukman835702a2005-04-21 22:36:52 +0000886
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000887 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000888 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000889 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000890 case Type::FloatTyID:
891 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000892 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000893 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000894 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000895 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000896 case Type::X86_FP80TyID:
897 case Type::FP128TyID:
898 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000899 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000900 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000901 case Type::IntegerTyID:
902 Result.IntVal = cast<ConstantInt>(C)->getValue();
903 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000904 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000905 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000906 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000907 else if (const Function *F = dyn_cast<Function>(C))
908 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000909 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000910 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
911 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000912 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000913 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000914 case Type::VectorTyID: {
915 unsigned elemNum;
916 Type* ElemTy;
917 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
918 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
919 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
920
921 if (CDV) {
922 elemNum = CDV->getNumElements();
923 ElemTy = CDV->getElementType();
924 } else if (CV || CAZ) {
925 VectorType* VTy = dyn_cast<VectorType>(C->getType());
926 elemNum = VTy->getNumElements();
927 ElemTy = VTy->getElementType();
928 } else {
929 llvm_unreachable("Unknown constant vector type!");
930 }
931
932 Result.AggregateVal.resize(elemNum);
933 // Check if vector holds floats.
934 if(ElemTy->isFloatTy()) {
935 if (CAZ) {
936 GenericValue floatZero;
937 floatZero.FloatVal = 0.f;
938 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
939 floatZero);
940 break;
941 }
942 if(CV) {
943 for (unsigned i = 0; i < elemNum; ++i)
944 if (!isa<UndefValue>(CV->getOperand(i)))
945 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
946 CV->getOperand(i))->getValueAPF().convertToFloat();
947 break;
948 }
949 if(CDV)
950 for (unsigned i = 0; i < elemNum; ++i)
951 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
952
953 break;
954 }
955 // Check if vector holds doubles.
956 if (ElemTy->isDoubleTy()) {
957 if (CAZ) {
958 GenericValue doubleZero;
959 doubleZero.DoubleVal = 0.0;
960 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
961 doubleZero);
962 break;
963 }
964 if(CV) {
965 for (unsigned i = 0; i < elemNum; ++i)
966 if (!isa<UndefValue>(CV->getOperand(i)))
967 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
968 CV->getOperand(i))->getValueAPF().convertToDouble();
969 break;
970 }
971 if(CDV)
972 for (unsigned i = 0; i < elemNum; ++i)
973 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
974
975 break;
976 }
977 // Check if vector holds integers.
978 if (ElemTy->isIntegerTy()) {
979 if (CAZ) {
980 GenericValue intZero;
981 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
982 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
983 intZero);
984 break;
985 }
986 if(CV) {
987 for (unsigned i = 0; i < elemNum; ++i)
988 if (!isa<UndefValue>(CV->getOperand(i)))
989 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
990 CV->getOperand(i))->getValue();
991 else {
992 Result.AggregateVal[i].IntVal =
993 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
994 }
995 break;
996 }
997 if(CDV)
998 for (unsigned i = 0; i < elemNum; ++i)
999 Result.AggregateVal[i].IntVal = APInt(
1000 CDV->getElementType()->getPrimitiveSizeInBits(),
1001 CDV->getElementAsInteger(i));
1002
1003 break;
1004 }
1005 llvm_unreachable("Unknown constant pointer type!");
1006 }
1007 break;
1008
Chris Lattner996fe012002-12-24 00:01:05 +00001009 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001010 SmallString<256> Msg;
1011 raw_svector_ostream OS(Msg);
1012 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1013 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001014 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001015
Chris Lattner996fe012002-12-24 00:01:05 +00001016 return Result;
1017}
1018
Duncan Sands1202d1b2007-12-14 19:38:31 +00001019/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1020/// with the integer held in IntVal.
1021static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1022 unsigned StoreBytes) {
1023 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001024 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001025
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001026 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001027 // Little-endian host - the source is ordered from LSB to MSB. Order the
1028 // destination from LSB to MSB: Do a straight copy.
1029 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001030 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001031 // Big-endian host - the source is an array of 64 bit words ordered from
1032 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1033 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1034 while (StoreBytes > sizeof(uint64_t)) {
1035 StoreBytes -= sizeof(uint64_t);
1036 // May not be aligned so use memcpy.
1037 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1038 Src += sizeof(uint64_t);
1039 }
1040
1041 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1042 }
1043}
1044
Evan Cheng09053e62008-11-04 06:10:31 +00001045void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001046 GenericValue *Ptr, Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001047 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001048
Reid Spencer87aa65f2007-03-06 03:04:04 +00001049 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001050 default:
1051 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1052 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001053 case Type::IntegerTyID:
1054 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001055 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001056 case Type::FloatTyID:
1057 *((float*)Ptr) = Val.FloatVal;
1058 break;
1059 case Type::DoubleTyID:
1060 *((double*)Ptr) = Val.DoubleVal;
1061 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001062 case Type::X86_FP80TyID:
1063 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1064 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001065 case Type::PointerTyID:
1066 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1067 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001068 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001069
Reid Spencer87aa65f2007-03-06 03:04:04 +00001070 *((PointerTy*)Ptr) = Val.PointerVal;
1071 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001072 case Type::VectorTyID:
1073 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1074 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1075 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1076 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1077 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1078 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1079 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1080 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1081 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1082 }
1083 }
1084 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001085 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001086
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001087 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001088 // Host and target are different endian - reverse the stored bytes.
1089 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1090}
1091
1092/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1093/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1094static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1095 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001096 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1097 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001098
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001099 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001100 // Little-endian host - the destination must be ordered from LSB to MSB.
1101 // The source is ordered from LSB to MSB: Do a straight copy.
1102 memcpy(Dst, Src, LoadBytes);
1103 else {
1104 // Big-endian - the destination is an array of 64 bit words ordered from
1105 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1106 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1107 // a word.
1108 while (LoadBytes > sizeof(uint64_t)) {
1109 LoadBytes -= sizeof(uint64_t);
1110 // May not be aligned so use memcpy.
1111 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1112 Dst += sizeof(uint64_t);
1113 }
1114
1115 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1116 }
Chris Lattner996fe012002-12-24 00:01:05 +00001117}
1118
Misha Brukman857c21b2003-10-10 17:45:12 +00001119/// FIXME: document
1120///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001121void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001122 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001123 Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001124 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001125
Duncan Sands1202d1b2007-12-14 19:38:31 +00001126 switch (Ty->getTypeID()) {
1127 case Type::IntegerTyID:
1128 // An APInt with all words initially zero.
1129 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1130 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1131 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001132 case Type::FloatTyID:
1133 Result.FloatVal = *((float*)Ptr);
1134 break;
1135 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001136 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001137 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001138 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001139 Result.PointerVal = *((PointerTy*)Ptr);
1140 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001141 case Type::X86_FP80TyID: {
1142 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001143 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001144 uint64_t y[2];
1145 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001146 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001147 break;
1148 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001149 case Type::VectorTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001150 auto *VT = cast<VectorType>(Ty);
1151 Type *ElemT = VT->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001152 const unsigned numElems = VT->getNumElements();
1153 if (ElemT->isFloatTy()) {
1154 Result.AggregateVal.resize(numElems);
1155 for (unsigned i = 0; i < numElems; ++i)
1156 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1157 }
1158 if (ElemT->isDoubleTy()) {
1159 Result.AggregateVal.resize(numElems);
1160 for (unsigned i = 0; i < numElems; ++i)
1161 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1162 }
1163 if (ElemT->isIntegerTy()) {
1164 GenericValue intZero;
1165 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1166 intZero.IntVal = APInt(elemBitWidth, 0);
1167 Result.AggregateVal.resize(numElems, intZero);
1168 for (unsigned i = 0; i < numElems; ++i)
1169 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1170 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1171 }
1172 break;
1173 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001174 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001175 SmallString<256> Msg;
1176 raw_svector_ostream OS(Msg);
1177 OS << "Cannot load value of type " << *Ty << "!";
1178 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001179 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001180}
1181
Chris Lattner996fe012002-12-24 00:01:05 +00001182void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001183 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001184 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001185 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001186 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001187
1188 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001189 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001190 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001191 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1192 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1193 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001194 }
1195
1196 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001197 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001198 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001199 }
1200
1201 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001202 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001203 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001204 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1205 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1206 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001207 }
1208
1209 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001210 const StructLayout *SL =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001211 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001212 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1213 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1214 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001215 }
1216
1217 if (const ConstantDataSequential *CDS =
1218 dyn_cast<ConstantDataSequential>(Init)) {
1219 // CDS is already laid out in host memory order.
1220 StringRef Data = CDS->getRawDataValues();
1221 memcpy(Addr, Data.data(), Data.size());
1222 return;
1223 }
1224
1225 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001226 GenericValue Val = getConstantValue(Init);
1227 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1228 return;
1229 }
1230
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001231 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001232 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001233}
1234
Chris Lattner996fe012002-12-24 00:01:05 +00001235/// EmitGlobals - Emit all of the global variables to memory, storing their
1236/// addresses into GlobalAddress. This must make sure to copy the contents of
1237/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001238void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001239 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001240 // to hold them. If there is more than one module, do a prepass over globals
1241 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001242 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001243 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001244
Chris Lattner0621cae2006-08-16 01:24:12 +00001245 if (Modules.size() != 1) {
1246 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001247 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001248 for (const auto &GV : M.globals()) {
1249 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1250 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001251 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001252
1253 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001254 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001255
1256 // If this is the first time we've seen this global, it is the canonical
1257 // version.
1258 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001259 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001260 continue;
1261 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001262
Chris Lattner0621cae2006-08-16 01:24:12 +00001263 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001264 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001265 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001266
Chris Lattner0621cae2006-08-16 01:24:12 +00001267 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001268 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001269 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1270 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001271 }
Chris Lattner996fe012002-12-24 00:01:05 +00001272 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001273 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001274
Chris Lattner0621cae2006-08-16 01:24:12 +00001275 std::vector<const GlobalValue*> NonCanonicalGlobals;
1276 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001277 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001278 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001279 // In the multi-module case, see what this global maps to.
1280 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001281 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001282 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001283 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001284 if (GVEntry != &GV) {
1285 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001286 continue;
1287 }
1288 }
1289 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001290
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001291 if (!GV.isDeclaration()) {
1292 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001293 } else {
1294 // External variable reference. Try to use the dynamic loader to
1295 // get a pointer to it.
1296 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001297 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1298 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001299 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001300 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001301 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001302 }
1303 }
1304 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001305
Chris Lattner0621cae2006-08-16 01:24:12 +00001306 // If there are multiple modules, map the non-canonical globals to their
1307 // canonical location.
1308 if (!NonCanonicalGlobals.empty()) {
1309 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1310 const GlobalValue *GV = NonCanonicalGlobals[i];
1311 const GlobalValue *CGV =
1312 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1313 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1314 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001315 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001316 }
1317 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001318
1319 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001320 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001321 for (const auto &GV : M.globals()) {
1322 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001323 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001324 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001325 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1326 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001327 continue;
1328 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001329 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001330 }
1331 }
1332 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001333}
1334
1335// EmitGlobalVariable - This method emits the specified global variable to the
1336// address specified in GlobalAddresses, or allocates new memory if it's not
1337// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001338void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001339 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001340
Craig Topper2617dcc2014-04-15 06:32:26 +00001341 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001342 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001343 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001344
1345 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001346 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001347
Chris Lattner748e8572003-12-31 20:21:04 +00001348 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001349 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001350
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001351 // Don't initialize if it's thread local, let the client do it.
1352 if (!GV->isThreadLocal())
1353 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001354
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001355 Type *ElTy = GV->getValueType();
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001356 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001357 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001358 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001359}