blob: 7d09ec6d1dab4bb0892ac376f094e1d47521df73 [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) {
Chris Lattner229907c2011-07-18 04:54:35 +0000106 Type *ElTy = GV->getType()->getElementType();
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),
477 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
478 UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000479// IR module verification is enabled by default in debug builds, and disabled
480// by default in release builds.
481#ifndef NDEBUG
482 VerifyModules = true;
483#else
484 VerifyModules = false;
485#endif
486}
487
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000488EngineBuilder::~EngineBuilder() = default;
489
490EngineBuilder &EngineBuilder::setMCJITMemoryManager(
491 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000492 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
493 MemMgr = SharedMM;
494 Resolver = SharedMM;
495 return *this;
496}
497
498EngineBuilder&
499EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
500 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
501 return *this;
502}
503
504EngineBuilder&
505EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
506 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000507 return *this;
508}
509
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000510ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000511 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000512
Nick Lewyckya53414f2008-03-08 02:49:45 +0000513 // Make sure we can resolve symbols in the program as well. The zero arg
514 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000515 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
516 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000517
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000518 // If the user specified a memory manager but didn't specify which engine to
519 // create, we assume they only want the JIT, and we fail if they only want
520 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000521 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000522 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000523 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000524 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000525 if (ErrorStr)
526 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000527 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000528 }
529 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000530
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000531 // Unless the interpreter was explicitly selected or the JIT is not linked,
532 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000533 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000534 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000535 if (!TM->getTarget().hasJIT()) {
536 errs() << "WARNING: This target JIT is not designed for the host"
537 << " you are running. If bad things happen, please choose"
538 << " a different -march switch.\n";
539 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000540
Lang Hamesbc876012014-04-18 06:48:23 +0000541 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000542 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000543 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
544 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000545 std::move(TheTM));
546 EE->addModule(std::move(M));
547 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000548 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
549 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000550
Lang Hamesbc876012014-04-18 06:48:23 +0000551 if (EE) {
552 EE->setVerifyModules(VerifyModules);
553 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000554 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000555 }
556
557 // If we can't make a JIT and we didn't request one specifically, try making
558 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000559 if (WhichEngine & EngineKind::Interpreter) {
560 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000561 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000562 if (ErrorStr)
563 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000564 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000565 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000566
Eric Christopher79cc1e32014-09-02 22:28:02 +0000567 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000568 if (ErrorStr)
569 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000570 }
571
Craig Topper2617dcc2014-04-15 06:32:26 +0000572 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000573}
574
Chris Lattner996fe012002-12-24 00:01:05 +0000575void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000576 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000577 return getPointerToFunction(F);
578
Zachary Turnerc04b8922014-06-20 21:07:14 +0000579 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000580 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000581 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000582
583 // Global variable might have been added since interpreter started.
584 if (GlobalVariable *GVar =
585 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
586 EmitGlobalVariable(GVar);
587 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000588 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000589
Lang Hames3dac3f72015-03-31 20:31:14 +0000590 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000591}
592
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000593/// \brief Converts a Constant* into a GenericValue, including handling of
594/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000595GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000596 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000597 if (isa<UndefValue>(C)) {
598 GenericValue Result;
599 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000600 default:
601 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000602 case Type::IntegerTyID:
603 case Type::X86_FP80TyID:
604 case Type::FP128TyID:
605 case Type::PPC_FP128TyID:
606 // Although the value is undefined, we still have to construct an APInt
607 // with the correct bit width.
608 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
609 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000610 case Type::StructTyID: {
611 // if the whole struct is 'undef' just reserve memory for the value.
612 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
613 unsigned int elemNum = STy->getNumElements();
614 Result.AggregateVal.resize(elemNum);
615 for (unsigned int i = 0; i < elemNum; ++i) {
616 Type *ElemTy = STy->getElementType(i);
617 if (ElemTy->isIntegerTy())
618 Result.AggregateVal[i].IntVal =
619 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
620 else if (ElemTy->isAggregateType()) {
621 const Constant *ElemUndef = UndefValue::get(ElemTy);
622 Result.AggregateVal[i] = getConstantValue(ElemUndef);
623 }
624 }
625 }
626 }
627 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000628 case Type::VectorTyID:
629 // if the whole vector is 'undef' just reserve memory for the value.
Craig Toppere3dcce92015-08-01 22:20:21 +0000630 auto* VTy = dyn_cast<VectorType>(C->getType());
631 Type *ElemTy = VTy->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000632 unsigned int elemNum = VTy->getNumElements();
633 Result.AggregateVal.resize(elemNum);
634 if (ElemTy->isIntegerTy())
635 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000636 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000637 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000638 break;
639 }
640 return Result;
641 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000642
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000643 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000644 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000645 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000646 switch (CE->getOpcode()) {
647 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000648 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000649 GenericValue Result = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000650 APInt Offset(DL.getPointerSizeInBits(), 0);
651 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000652
Reid Spencer87aa65f2007-03-06 03:04:04 +0000653 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000654 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000655 return Result;
656 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000657 case Instruction::Trunc: {
658 GenericValue GV = getConstantValue(Op0);
659 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
660 GV.IntVal = GV.IntVal.trunc(BitWidth);
661 return GV;
662 }
663 case Instruction::ZExt: {
664 GenericValue GV = getConstantValue(Op0);
665 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
666 GV.IntVal = GV.IntVal.zext(BitWidth);
667 return GV;
668 }
669 case Instruction::SExt: {
670 GenericValue GV = getConstantValue(Op0);
671 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
672 GV.IntVal = GV.IntVal.sext(BitWidth);
673 return GV;
674 }
675 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000676 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000677 GenericValue GV = getConstantValue(Op0);
678 GV.FloatVal = float(GV.DoubleVal);
679 return GV;
680 }
681 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000682 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000683 GenericValue GV = getConstantValue(Op0);
684 GV.DoubleVal = double(GV.FloatVal);
685 return GV;
686 }
687 case Instruction::UIToFP: {
688 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000689 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000690 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000691 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000692 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000693 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000694 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000695 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000696 false,
697 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000698 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000699 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000700 return GV;
701 }
702 case Instruction::SIToFP: {
703 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000704 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000705 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000706 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000707 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000708 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000709 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000710 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000711 true,
712 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000713 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000714 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000715 return GV;
716 }
717 case Instruction::FPToUI: // double->APInt conversion handles sign
718 case Instruction::FPToSI: {
719 GenericValue GV = getConstantValue(Op0);
720 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000721 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000722 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000723 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000724 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000725 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000726 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000727 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000728 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000729 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000730 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000731 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000732 GV.IntVal = v; // endian?
733 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000734 return GV;
735 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000736 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000737 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000738 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000739 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000740 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000741 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000742 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000743 return GV;
744 }
745 case Instruction::IntToPtr: {
746 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000747 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000748 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000749 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
750 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000751 return GV;
752 }
753 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000754 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000755 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000756 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000757 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000758 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000759 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000760 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000761 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000762 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000763 GV.DoubleVal = GV.IntVal.bitsToDouble();
764 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000765 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000766 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000767 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000768 break;
769 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000770 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000771 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000772 break;
773 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000774 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000775 break; // getConstantValue(Op0) above already converted it
776 }
777 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000778 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000779 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000780 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000781 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000782 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000783 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000784 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000785 case Instruction::UDiv:
786 case Instruction::SDiv:
787 case Instruction::URem:
788 case Instruction::SRem:
789 case Instruction::And:
790 case Instruction::Or:
791 case Instruction::Xor: {
792 GenericValue LHS = getConstantValue(Op0);
793 GenericValue RHS = getConstantValue(CE->getOperand(1));
794 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000795 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000796 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000797 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000798 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000799 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000800 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
801 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
802 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
803 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
804 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
805 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
806 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
807 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
808 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
809 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
810 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000811 break;
812 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000813 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000814 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000815 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000816 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000817 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000818 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000819 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000820 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000821 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000822 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000823 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000824 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000825 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000826 break;
827 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000828 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000829 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000830 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000831 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000832 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000833 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000834 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000835 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000836 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000837 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000838 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000839 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000840 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000841 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000842 case Type::X86_FP80TyID:
843 case Type::PPC_FP128TyID:
844 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000845 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
846 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000847 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000848 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000849 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000850 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000851 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000852 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000853 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000854 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
855 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000856 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000857 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000858 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000859 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
860 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000861 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000862 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000863 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000864 apfLHS.divide(APFloat(Sem, RHS.IntVal),
865 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000866 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000867 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000868 case Instruction::FRem:
Stephen Canonb12db0e2015-09-21 19:29:25 +0000869 apfLHS.mod(APFloat(Sem, RHS.IntVal));
Dale Johannesen54306fe2008-10-09 18:53:47 +0000870 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000871 break;
872 }
873 }
874 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000875 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000876 return GV;
877 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000878 default:
879 break;
880 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000881
882 SmallString<256> Msg;
883 raw_svector_ostream OS(Msg);
884 OS << "ConstantExpr not handled: " << *CE;
885 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000886 }
Misha Brukman835702a2005-04-21 22:36:52 +0000887
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000888 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000889 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000890 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000891 case Type::FloatTyID:
892 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000893 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000894 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000895 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000896 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000897 case Type::X86_FP80TyID:
898 case Type::FP128TyID:
899 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000900 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000901 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000902 case Type::IntegerTyID:
903 Result.IntVal = cast<ConstantInt>(C)->getValue();
904 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000905 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000906 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000907 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000908 else if (const Function *F = dyn_cast<Function>(C))
909 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000910 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000911 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
912 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000913 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000914 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000915 case Type::VectorTyID: {
916 unsigned elemNum;
917 Type* ElemTy;
918 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
919 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
920 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
921
922 if (CDV) {
923 elemNum = CDV->getNumElements();
924 ElemTy = CDV->getElementType();
925 } else if (CV || CAZ) {
926 VectorType* VTy = dyn_cast<VectorType>(C->getType());
927 elemNum = VTy->getNumElements();
928 ElemTy = VTy->getElementType();
929 } else {
930 llvm_unreachable("Unknown constant vector type!");
931 }
932
933 Result.AggregateVal.resize(elemNum);
934 // Check if vector holds floats.
935 if(ElemTy->isFloatTy()) {
936 if (CAZ) {
937 GenericValue floatZero;
938 floatZero.FloatVal = 0.f;
939 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
940 floatZero);
941 break;
942 }
943 if(CV) {
944 for (unsigned i = 0; i < elemNum; ++i)
945 if (!isa<UndefValue>(CV->getOperand(i)))
946 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
947 CV->getOperand(i))->getValueAPF().convertToFloat();
948 break;
949 }
950 if(CDV)
951 for (unsigned i = 0; i < elemNum; ++i)
952 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
953
954 break;
955 }
956 // Check if vector holds doubles.
957 if (ElemTy->isDoubleTy()) {
958 if (CAZ) {
959 GenericValue doubleZero;
960 doubleZero.DoubleVal = 0.0;
961 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
962 doubleZero);
963 break;
964 }
965 if(CV) {
966 for (unsigned i = 0; i < elemNum; ++i)
967 if (!isa<UndefValue>(CV->getOperand(i)))
968 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
969 CV->getOperand(i))->getValueAPF().convertToDouble();
970 break;
971 }
972 if(CDV)
973 for (unsigned i = 0; i < elemNum; ++i)
974 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
975
976 break;
977 }
978 // Check if vector holds integers.
979 if (ElemTy->isIntegerTy()) {
980 if (CAZ) {
981 GenericValue intZero;
982 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
983 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
984 intZero);
985 break;
986 }
987 if(CV) {
988 for (unsigned i = 0; i < elemNum; ++i)
989 if (!isa<UndefValue>(CV->getOperand(i)))
990 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
991 CV->getOperand(i))->getValue();
992 else {
993 Result.AggregateVal[i].IntVal =
994 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
995 }
996 break;
997 }
998 if(CDV)
999 for (unsigned i = 0; i < elemNum; ++i)
1000 Result.AggregateVal[i].IntVal = APInt(
1001 CDV->getElementType()->getPrimitiveSizeInBits(),
1002 CDV->getElementAsInteger(i));
1003
1004 break;
1005 }
1006 llvm_unreachable("Unknown constant pointer type!");
1007 }
1008 break;
1009
Chris Lattner996fe012002-12-24 00:01:05 +00001010 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001011 SmallString<256> Msg;
1012 raw_svector_ostream OS(Msg);
1013 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1014 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001015 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001016
Chris Lattner996fe012002-12-24 00:01:05 +00001017 return Result;
1018}
1019
Duncan Sands1202d1b2007-12-14 19:38:31 +00001020/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1021/// with the integer held in IntVal.
1022static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1023 unsigned StoreBytes) {
1024 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001025 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001026
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001027 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001028 // Little-endian host - the source is ordered from LSB to MSB. Order the
1029 // destination from LSB to MSB: Do a straight copy.
1030 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001031 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001032 // Big-endian host - the source is an array of 64 bit words ordered from
1033 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1034 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1035 while (StoreBytes > sizeof(uint64_t)) {
1036 StoreBytes -= sizeof(uint64_t);
1037 // May not be aligned so use memcpy.
1038 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1039 Src += sizeof(uint64_t);
1040 }
1041
1042 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1043 }
1044}
1045
Evan Cheng09053e62008-11-04 06:10:31 +00001046void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001047 GenericValue *Ptr, Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001048 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001049
Reid Spencer87aa65f2007-03-06 03:04:04 +00001050 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001051 default:
1052 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1053 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001054 case Type::IntegerTyID:
1055 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001056 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001057 case Type::FloatTyID:
1058 *((float*)Ptr) = Val.FloatVal;
1059 break;
1060 case Type::DoubleTyID:
1061 *((double*)Ptr) = Val.DoubleVal;
1062 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001063 case Type::X86_FP80TyID:
1064 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1065 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001066 case Type::PointerTyID:
1067 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1068 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001069 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001070
Reid Spencer87aa65f2007-03-06 03:04:04 +00001071 *((PointerTy*)Ptr) = Val.PointerVal;
1072 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001073 case Type::VectorTyID:
1074 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1075 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1076 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1077 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1078 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1079 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1080 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1081 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1082 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1083 }
1084 }
1085 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001086 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001087
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001088 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001089 // Host and target are different endian - reverse the stored bytes.
1090 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1091}
1092
1093/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1094/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1095static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1096 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001097 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1098 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001099
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001100 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001101 // Little-endian host - the destination must be ordered from LSB to MSB.
1102 // The source is ordered from LSB to MSB: Do a straight copy.
1103 memcpy(Dst, Src, LoadBytes);
1104 else {
1105 // Big-endian - the destination is an array of 64 bit words ordered from
1106 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1107 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1108 // a word.
1109 while (LoadBytes > sizeof(uint64_t)) {
1110 LoadBytes -= sizeof(uint64_t);
1111 // May not be aligned so use memcpy.
1112 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1113 Dst += sizeof(uint64_t);
1114 }
1115
1116 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1117 }
Chris Lattner996fe012002-12-24 00:01:05 +00001118}
1119
Misha Brukman857c21b2003-10-10 17:45:12 +00001120/// FIXME: document
1121///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001122void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001123 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001124 Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001125 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001126
Duncan Sands1202d1b2007-12-14 19:38:31 +00001127 switch (Ty->getTypeID()) {
1128 case Type::IntegerTyID:
1129 // An APInt with all words initially zero.
1130 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1131 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1132 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001133 case Type::FloatTyID:
1134 Result.FloatVal = *((float*)Ptr);
1135 break;
1136 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001137 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001138 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001139 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001140 Result.PointerVal = *((PointerTy*)Ptr);
1141 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001142 case Type::X86_FP80TyID: {
1143 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001144 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001145 uint64_t y[2];
1146 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001147 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001148 break;
1149 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001150 case Type::VectorTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001151 auto *VT = cast<VectorType>(Ty);
1152 Type *ElemT = VT->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001153 const unsigned numElems = VT->getNumElements();
1154 if (ElemT->isFloatTy()) {
1155 Result.AggregateVal.resize(numElems);
1156 for (unsigned i = 0; i < numElems; ++i)
1157 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1158 }
1159 if (ElemT->isDoubleTy()) {
1160 Result.AggregateVal.resize(numElems);
1161 for (unsigned i = 0; i < numElems; ++i)
1162 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1163 }
1164 if (ElemT->isIntegerTy()) {
1165 GenericValue intZero;
1166 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1167 intZero.IntVal = APInt(elemBitWidth, 0);
1168 Result.AggregateVal.resize(numElems, intZero);
1169 for (unsigned i = 0; i < numElems; ++i)
1170 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1171 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1172 }
1173 break;
1174 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001175 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001176 SmallString<256> Msg;
1177 raw_svector_ostream OS(Msg);
1178 OS << "Cannot load value of type " << *Ty << "!";
1179 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001180 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001181}
1182
Chris Lattner996fe012002-12-24 00:01:05 +00001183void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001184 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001185 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001186 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001187 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001188
1189 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001190 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001191 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001192 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1193 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1194 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001195 }
1196
1197 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001198 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001199 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001200 }
1201
1202 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001203 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001204 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001205 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1206 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1207 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001208 }
1209
1210 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001211 const StructLayout *SL =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001212 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001213 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1214 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1215 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001216 }
1217
1218 if (const ConstantDataSequential *CDS =
1219 dyn_cast<ConstantDataSequential>(Init)) {
1220 // CDS is already laid out in host memory order.
1221 StringRef Data = CDS->getRawDataValues();
1222 memcpy(Addr, Data.data(), Data.size());
1223 return;
1224 }
1225
1226 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001227 GenericValue Val = getConstantValue(Init);
1228 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1229 return;
1230 }
1231
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001232 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001233 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001234}
1235
Chris Lattner996fe012002-12-24 00:01:05 +00001236/// EmitGlobals - Emit all of the global variables to memory, storing their
1237/// addresses into GlobalAddress. This must make sure to copy the contents of
1238/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001239void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001240 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001241 // to hold them. If there is more than one module, do a prepass over globals
1242 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001243 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001244 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001245
Chris Lattner0621cae2006-08-16 01:24:12 +00001246 if (Modules.size() != 1) {
1247 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001248 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001249 for (const auto &GV : M.globals()) {
1250 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1251 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001252 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001253
1254 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001255 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001256
1257 // If this is the first time we've seen this global, it is the canonical
1258 // version.
1259 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001260 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001261 continue;
1262 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001263
Chris Lattner0621cae2006-08-16 01:24:12 +00001264 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001265 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001266 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001267
Chris Lattner0621cae2006-08-16 01:24:12 +00001268 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001269 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001270 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1271 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001272 }
Chris Lattner996fe012002-12-24 00:01:05 +00001273 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001274 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001275
Chris Lattner0621cae2006-08-16 01:24:12 +00001276 std::vector<const GlobalValue*> NonCanonicalGlobals;
1277 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001278 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001279 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001280 // In the multi-module case, see what this global maps to.
1281 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001282 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001283 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001284 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001285 if (GVEntry != &GV) {
1286 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001287 continue;
1288 }
1289 }
1290 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001291
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001292 if (!GV.isDeclaration()) {
1293 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001294 } else {
1295 // External variable reference. Try to use the dynamic loader to
1296 // get a pointer to it.
1297 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001298 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1299 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001300 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001301 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001302 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001303 }
1304 }
1305 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001306
Chris Lattner0621cae2006-08-16 01:24:12 +00001307 // If there are multiple modules, map the non-canonical globals to their
1308 // canonical location.
1309 if (!NonCanonicalGlobals.empty()) {
1310 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1311 const GlobalValue *GV = NonCanonicalGlobals[i];
1312 const GlobalValue *CGV =
1313 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1314 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1315 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001316 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001317 }
1318 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001319
1320 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001321 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001322 for (const auto &GV : M.globals()) {
1323 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001324 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001325 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001326 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1327 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001328 continue;
1329 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001330 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001331 }
1332 }
1333 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001334}
1335
1336// EmitGlobalVariable - This method emits the specified global variable to the
1337// address specified in GlobalAddresses, or allocates new memory if it's not
1338// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001339void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001340 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001341
Craig Topper2617dcc2014-04-15 06:32:26 +00001342 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001343 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001344 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001345
1346 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001347 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001348
Chris Lattner748e8572003-12-31 20:21:04 +00001349 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001350 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001351
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001352 // Don't initialize if it's thread local, let the client do it.
1353 if (!GV->isThreadLocal())
1354 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001355
Chris Lattner229907c2011-07-18 04:54:35 +00001356 Type *ElTy = GV->getType()->getElementType();
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001357 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001358 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001359 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001360}