blob: 136a2d5f03790ee9fb2766cf7950938f97146310 [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(
David Majnemerf3cadce2014-10-20 06:13:33 +0000109 RoundUpToAlignment(sizeof(GVMemoryBlock),
110 TD.getPreferredAlignment(GV))
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000111 + GVSize);
112 new(RawMemory) GVMemoryBlock(GV);
113 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
114 }
115
Craig Topperb51ff602014-03-08 07:51:20 +0000116 void deleted() override {
Jeffrey Yasskina4044332010-03-27 04:53:56 +0000117 // We allocated with operator new and with some extra memory hanging off the
118 // end, so don't just delete this. I'm not sure if this is actually
119 // required.
120 this->~GVMemoryBlock();
121 ::operator delete(this);
122 }
123};
124} // anonymous namespace
125
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000126char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000127 return GVMemoryBlock::Create(GV, getDataLayout());
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000128}
129
David Blaikie35907d82014-04-29 22:04:55 +0000130void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
131 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
132}
133
Rafael Espindola7271c192014-08-26 21:04:04 +0000134void
135ExecutionEngine::addObjectFile(object::OwningBinary<object::ObjectFile> O) {
136 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
137}
138
Rafael Espindola48af1c22014-08-19 18:44:46 +0000139void ExecutionEngine::addArchive(object::OwningBinary<object::Archive> A) {
Rafael Espindolaacfd6282014-08-01 18:49:24 +0000140 llvm_unreachable("ExecutionEngine subclass doesn't implement addArchive.");
141}
142
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000143bool ExecutionEngine::removeModule(Module *M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000144 for (auto I = Modules.begin(), E = Modules.end(); I != E; ++I) {
145 Module *Found = I->get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000146 if (Found == M) {
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000147 I->release();
Devang Patel324fe892007-10-15 19:56:32 +0000148 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000149 clearGlobalMappingsFromModule(M);
150 return true;
Devang Patel324fe892007-10-15 19:56:32 +0000151 }
152 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000153 return false;
Nate Begeman617001d2009-01-23 19:27:28 +0000154}
155
Chris Lattner0621cae2006-08-16 01:24:12 +0000156Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
157 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Keno Fischer5f92a082015-01-27 19:29:00 +0000158 Function *F = Modules[i]->getFunction(FnName);
159 if (F && !F->isDeclaration())
Chris Lattner0621cae2006-08-16 01:24:12 +0000160 return F;
161 }
Craig Topper2617dcc2014-04-15 06:32:26 +0000162 return nullptr;
Chris Lattner0621cae2006-08-16 01:24:12 +0000163}
164
Keno Fischer73378eb2015-06-20 00:55:58 +0000165GlobalVariable *ExecutionEngine::FindGlobalVariableNamed(const char *Name, bool AllowInternal) {
166 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
167 GlobalVariable *GV = Modules[i]->getGlobalVariable(Name,AllowInternal);
168 if (GV && !GV->isDeclaration())
169 return GV;
170 }
171 return nullptr;
172}
Chris Lattner0621cae2006-08-16 01:24:12 +0000173
Lang Hames3dac3f72015-03-31 20:31:14 +0000174uint64_t ExecutionEngineState::RemoveMapping(StringRef Name) {
175 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(Name);
176 uint64_t OldVal;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000177
178 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
179 // GlobalAddressMap.
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000180 if (I == GlobalAddressMap.end())
Lang Hames3dac3f72015-03-31 20:31:14 +0000181 OldVal = 0;
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000182 else {
Lang Hames3dac3f72015-03-31 20:31:14 +0000183 GlobalAddressReverseMap.erase(I->second);
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000184 OldVal = I->second;
185 GlobalAddressMap.erase(I);
186 }
187
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000188 return OldVal;
189}
190
Lang Hames3dac3f72015-03-31 20:31:14 +0000191std::string ExecutionEngine::getMangledName(const GlobalValue *GV) {
Lang Hames3393cfd2015-07-29 23:12:33 +0000192 assert(GV->hasName() && "Global must have name.");
193
Lang Hames3dac3f72015-03-31 20:31:14 +0000194 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000195 SmallString<128> FullName;
Lang Hames3393cfd2015-07-29 23:12:33 +0000196
197 const DataLayout &DL =
198 GV->getParent()->getDataLayout().isDefault()
199 ? getDataLayout()
200 : GV->getParent()->getDataLayout();
201
202 Mangler::getNameWithPrefix(FullName, GV->getName(), DL);
Lang Hames3dac3f72015-03-31 20:31:14 +0000203 return FullName.str();
204}
205
Chris Lattner6d8dd182006-05-08 22:00:52 +0000206void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000207 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000208 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
209}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000210
Lang Hames3dac3f72015-03-31 20:31:14 +0000211void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
212 MutexGuard locked(lock);
213
214 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
215
216 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
217 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000218 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000219 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000220
221 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000222 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000223 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
224 assert((!V.empty() || !Name.empty()) &&
225 "GlobalMapping already established!");
226 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000227 }
228}
229
Chris Lattner6d8dd182006-05-08 22:00:52 +0000230void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000231 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000232
Zachary Turner2f825df2014-06-16 20:54:28 +0000233 EEState.getGlobalAddressMap().clear();
234 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000235}
236
Nate Begeman8f83fc42008-05-21 16:34:48 +0000237void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000238 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000239
240 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000241 EEState.RemoveMapping(getMangledName(FI));
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000242 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
243 GI != GE; ++GI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000244 EEState.RemoveMapping(getMangledName(GI));
Nate Begeman8f83fc42008-05-21 16:34:48 +0000245}
246
Lang Hames3dac3f72015-03-31 20:31:14 +0000247uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
248 void *Addr) {
249 MutexGuard locked(lock);
250 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
251}
252
253uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000254 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000255
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000256 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000257 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000258
Chris Lattner6d8dd182006-05-08 22:00:52 +0000259 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000260 if (!Addr)
Lang Hames3dac3f72015-03-31 20:31:14 +0000261 return EEState.RemoveMapping(Name);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000262
Lang Hames3dac3f72015-03-31 20:31:14 +0000263 uint64_t &CurVal = Map[Name];
264 uint64_t OldVal = CurVal;
Chris Lattneree181732008-04-04 04:47:41 +0000265
Zachary Turner2f825df2014-06-16 20:54:28 +0000266 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
267 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000268 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000269
270 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000271 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000272 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
273 assert((!V.empty() || !Name.empty()) &&
274 "GlobalMapping already established!");
275 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000276 }
Chris Lattneree181732008-04-04 04:47:41 +0000277 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000278}
279
Lang Hames3dac3f72015-03-31 20:31:14 +0000280uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
281 MutexGuard locked(lock);
282 uint64_t Address = 0;
283 ExecutionEngineState::GlobalAddressMapTy::iterator I =
284 EEState.getGlobalAddressMap().find(S);
285 if (I != EEState.getGlobalAddressMap().end())
286 Address = I->second;
287 return Address;
288}
289
290
291void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
292 MutexGuard locked(lock);
293 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
294 return Address;
295 return nullptr;
296}
297
Chris Lattner6d8dd182006-05-08 22:00:52 +0000298void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000299 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000300 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattner6d8dd182006-05-08 22:00:52 +0000301}
302
Chris Lattner748e8572003-12-31 20:21:04 +0000303const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000304 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000305
Chris Lattner748e8572003-12-31 20:21:04 +0000306 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000307 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000308 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames3dac3f72015-03-31 20:31:14 +0000309 I = EEState.getGlobalAddressMap().begin(),
310 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
311 StringRef Name = I->first();
312 uint64_t Addr = I->second;
Zachary Turner2f825df2014-06-16 20:54:28 +0000313 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames3dac3f72015-03-31 20:31:14 +0000314 Addr, Name));
315 }
Chris Lattner748e8572003-12-31 20:21:04 +0000316 }
317
Lang Hames3dac3f72015-03-31 20:31:14 +0000318 std::map<uint64_t, std::string>::iterator I =
319 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
320
321 if (I != EEState.getGlobalAddressReverseMap().end()) {
322 StringRef Name = I->second;
323 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
324 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
325 return GV;
326 }
327 return nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000328}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000329
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000330namespace {
331class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000332 std::unique_ptr<char[]> Array;
333 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000334public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000335 /// Turn a vector of strings into a nice argv style array of pointers to null
336 /// terminated strings.
337 void *reset(LLVMContext &C, ExecutionEngine *EE,
338 const std::vector<std::string> &InputArgv);
339};
340} // anonymous namespace
341void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
342 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000343 Values.clear(); // Free the old contents.
344 Values.reserve(InputArgv.size());
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000345 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000346 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000347
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000348 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000349 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000350
351 for (unsigned i = 0; i != InputArgv.size(); ++i) {
352 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000353 auto Dest = make_unique<char[]>(Size);
354 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000355
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000356 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000357 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000358
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000359 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000360 EE->StoreValueToMemory(PTOGV(Dest.get()),
361 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
362 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000363 }
364
365 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000366 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000367 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000368 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000369 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000370}
371
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000372void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000373 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000374 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000375 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000376
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000377 // If this global has internal linkage, or if it has a use, then it must be
378 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
379 // this is the case, don't execute any of the global ctors, __main will do
380 // it.
381 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
382
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000383 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000384 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000385 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000386 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000387 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000388 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000389 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000390 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000391
392 Constant *FP = CS->getOperand(1);
393 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000394 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000395
396 // Strip off constant expression casts.
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
398 if (CE->isCast())
399 FP = CE->getOperand(0);
400
401 // Execute the ctor/dtor function!
402 if (Function *F = dyn_cast<Function>(FP))
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000403 runFunction(F, None);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000404
405 // FIXME: It is marginally lame that we just do nothing here if we see an
406 // entry we don't recognize. It might not be unreasonable for the verifier
407 // to not even allow this and just assert here.
408 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000409}
410
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000411void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
412 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000413 for (std::unique_ptr<Module> &M : Modules)
414 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000415}
416
Dan Gohmancf3e3012008-08-26 01:38:29 +0000417#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000418/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
419static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000420 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000421 for (unsigned i = 0; i < PtrSize; ++i)
422 if (*(i + (uint8_t*)Loc))
423 return false;
424 return true;
425}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000426#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000427
Chris Lattner5a0d4822003-12-26 06:50:30 +0000428int ExecutionEngine::runFunctionAsMain(Function *Fn,
429 const std::vector<std::string> &argv,
430 const char * const * envp) {
431 std::vector<GenericValue> GVArgs;
432 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000433 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000434
435 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000436 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000437 FunctionType *FTy = Fn->getFunctionType();
438 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000439
440 // Check the argument types.
441 if (NumArgs > 3)
442 report_fatal_error("Invalid number of arguments of main() supplied");
443 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
444 report_fatal_error("Invalid type for third argument of main() supplied");
445 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
446 report_fatal_error("Invalid type for second argument of main() supplied");
447 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
448 report_fatal_error("Invalid type for first argument of main() supplied");
449 if (!FTy->getReturnType()->isIntegerTy() &&
450 !FTy->getReturnType()->isVoidTy())
451 report_fatal_error("Invalid return type of main() supplied");
452
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000453 ArgvArray CArgv;
454 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000455 if (NumArgs) {
456 GVArgs.push_back(GVArgc); // Arg #0 = argc.
457 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000458 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000459 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000460 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000461 "argv[0] was null after CreateArgv");
462 if (NumArgs > 2) {
463 std::vector<std::string> EnvVars;
464 for (unsigned i = 0; envp[i]; ++i)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000465 EnvVars.emplace_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000466 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000467 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000468 }
469 }
470 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000471
Reid Spencer87aa65f2007-03-06 03:04:04 +0000472 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000473}
474
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000475EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames93de2a12015-01-23 21:25:00 +0000476
Lang Hames4a5697e2014-12-03 00:51:19 +0000477EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000478 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +0000479 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
480 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
481 UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000482// IR module verification is enabled by default in debug builds, and disabled
483// by default in release builds.
484#ifndef NDEBUG
485 VerifyModules = true;
486#else
487 VerifyModules = false;
488#endif
489}
490
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000491EngineBuilder::~EngineBuilder() = default;
492
493EngineBuilder &EngineBuilder::setMCJITMemoryManager(
494 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000495 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
496 MemMgr = SharedMM;
497 Resolver = SharedMM;
498 return *this;
499}
500
501EngineBuilder&
502EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
503 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
504 return *this;
505}
506
507EngineBuilder&
508EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
509 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000510 return *this;
511}
512
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000513ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000514 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000515
Nick Lewyckya53414f2008-03-08 02:49:45 +0000516 // Make sure we can resolve symbols in the program as well. The zero arg
517 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000518 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
519 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000520
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000521 // If the user specified a memory manager but didn't specify which engine to
522 // create, we assume they only want the JIT, and we fail if they only want
523 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000524 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000525 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000526 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000527 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000528 if (ErrorStr)
529 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000530 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000531 }
532 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000533
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000534 // Unless the interpreter was explicitly selected or the JIT is not linked,
535 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000536 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000537 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000538 if (!TM->getTarget().hasJIT()) {
539 errs() << "WARNING: This target JIT is not designed for the host"
540 << " you are running. If bad things happen, please choose"
541 << " a different -march switch.\n";
542 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000543
Lang Hamesbc876012014-04-18 06:48:23 +0000544 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000545 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000546 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
547 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000548 std::move(TheTM));
549 EE->addModule(std::move(M));
550 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000551 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
552 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000553
Lang Hamesbc876012014-04-18 06:48:23 +0000554 if (EE) {
555 EE->setVerifyModules(VerifyModules);
556 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000557 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000558 }
559
560 // If we can't make a JIT and we didn't request one specifically, try making
561 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000562 if (WhichEngine & EngineKind::Interpreter) {
563 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000564 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000565 if (ErrorStr)
566 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000567 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000568 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000569
Eric Christopher79cc1e32014-09-02 22:28:02 +0000570 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000571 if (ErrorStr)
572 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000573 }
574
Craig Topper2617dcc2014-04-15 06:32:26 +0000575 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000576}
577
Chris Lattner996fe012002-12-24 00:01:05 +0000578void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000579 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000580 return getPointerToFunction(F);
581
Zachary Turnerc04b8922014-06-20 21:07:14 +0000582 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000583 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000584 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000585
586 // Global variable might have been added since interpreter started.
587 if (GlobalVariable *GVar =
588 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
589 EmitGlobalVariable(GVar);
590 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000591 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000592
Lang Hames3dac3f72015-03-31 20:31:14 +0000593 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000594}
595
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000596/// \brief Converts a Constant* into a GenericValue, including handling of
597/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000598GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000599 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000600 if (isa<UndefValue>(C)) {
601 GenericValue Result;
602 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000603 default:
604 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000605 case Type::IntegerTyID:
606 case Type::X86_FP80TyID:
607 case Type::FP128TyID:
608 case Type::PPC_FP128TyID:
609 // Although the value is undefined, we still have to construct an APInt
610 // with the correct bit width.
611 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
612 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000613 case Type::StructTyID: {
614 // if the whole struct is 'undef' just reserve memory for the value.
615 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
616 unsigned int elemNum = STy->getNumElements();
617 Result.AggregateVal.resize(elemNum);
618 for (unsigned int i = 0; i < elemNum; ++i) {
619 Type *ElemTy = STy->getElementType(i);
620 if (ElemTy->isIntegerTy())
621 Result.AggregateVal[i].IntVal =
622 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
623 else if (ElemTy->isAggregateType()) {
624 const Constant *ElemUndef = UndefValue::get(ElemTy);
625 Result.AggregateVal[i] = getConstantValue(ElemUndef);
626 }
627 }
628 }
629 }
630 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000631 case Type::VectorTyID:
632 // if the whole vector is 'undef' just reserve memory for the value.
Craig Toppere3dcce92015-08-01 22:20:21 +0000633 auto* VTy = dyn_cast<VectorType>(C->getType());
634 Type *ElemTy = VTy->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000635 unsigned int elemNum = VTy->getNumElements();
636 Result.AggregateVal.resize(elemNum);
637 if (ElemTy->isIntegerTy())
638 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000639 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000640 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000641 break;
642 }
643 return Result;
644 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000645
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000646 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000647 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000648 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000649 switch (CE->getOpcode()) {
650 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000651 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000652 GenericValue Result = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000653 APInt Offset(DL.getPointerSizeInBits(), 0);
654 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000655
Reid Spencer87aa65f2007-03-06 03:04:04 +0000656 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000657 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000658 return Result;
659 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000660 case Instruction::Trunc: {
661 GenericValue GV = getConstantValue(Op0);
662 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
663 GV.IntVal = GV.IntVal.trunc(BitWidth);
664 return GV;
665 }
666 case Instruction::ZExt: {
667 GenericValue GV = getConstantValue(Op0);
668 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
669 GV.IntVal = GV.IntVal.zext(BitWidth);
670 return GV;
671 }
672 case Instruction::SExt: {
673 GenericValue GV = getConstantValue(Op0);
674 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
675 GV.IntVal = GV.IntVal.sext(BitWidth);
676 return GV;
677 }
678 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000679 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000680 GenericValue GV = getConstantValue(Op0);
681 GV.FloatVal = float(GV.DoubleVal);
682 return GV;
683 }
684 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000685 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000686 GenericValue GV = getConstantValue(Op0);
687 GV.DoubleVal = double(GV.FloatVal);
688 return GV;
689 }
690 case Instruction::UIToFP: {
691 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000692 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000693 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000694 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000695 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000696 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000697 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000698 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000699 false,
700 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000701 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000702 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000703 return GV;
704 }
705 case Instruction::SIToFP: {
706 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000707 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000708 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000709 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000710 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000711 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000712 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000713 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000714 true,
715 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000716 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000717 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000718 return GV;
719 }
720 case Instruction::FPToUI: // double->APInt conversion handles sign
721 case Instruction::FPToSI: {
722 GenericValue GV = getConstantValue(Op0);
723 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000724 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000725 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000726 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000727 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000728 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000729 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000730 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000731 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000732 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000733 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000734 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000735 GV.IntVal = v; // endian?
736 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000737 return GV;
738 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000739 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000740 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000741 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000742 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000743 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000744 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000745 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000746 return GV;
747 }
748 case Instruction::IntToPtr: {
749 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000750 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000751 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000752 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
753 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000754 return GV;
755 }
756 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000757 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000758 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000759 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000760 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000761 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000762 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000763 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000764 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000765 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000766 GV.DoubleVal = GV.IntVal.bitsToDouble();
767 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000768 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000769 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000770 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000771 break;
772 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000773 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000774 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000775 break;
776 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000777 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000778 break; // getConstantValue(Op0) above already converted it
779 }
780 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000781 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000782 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000783 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000784 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000785 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000786 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000787 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000788 case Instruction::UDiv:
789 case Instruction::SDiv:
790 case Instruction::URem:
791 case Instruction::SRem:
792 case Instruction::And:
793 case Instruction::Or:
794 case Instruction::Xor: {
795 GenericValue LHS = getConstantValue(Op0);
796 GenericValue RHS = getConstantValue(CE->getOperand(1));
797 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000798 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000799 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000800 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000801 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000802 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000803 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
804 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
805 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
806 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
807 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
808 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
809 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
810 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
811 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
812 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
813 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000814 break;
815 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000816 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000817 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000818 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000819 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000820 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000821 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000822 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000823 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000824 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000825 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000826 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000827 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000828 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000829 break;
830 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000831 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000832 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000833 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000834 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000835 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000836 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000837 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000838 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000839 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000840 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000841 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000842 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000843 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000844 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000845 case Type::X86_FP80TyID:
846 case Type::PPC_FP128TyID:
847 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000848 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
849 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000850 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000851 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000852 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000853 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000854 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000855 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000856 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000857 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
858 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000859 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000860 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000861 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000862 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
863 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000864 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000865 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000866 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000867 apfLHS.divide(APFloat(Sem, RHS.IntVal),
868 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000869 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000870 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000871 case Instruction::FRem:
Tim Northover29178a32013-01-22 09:46:31 +0000872 apfLHS.mod(APFloat(Sem, RHS.IntVal),
873 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000874 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000875 break;
876 }
877 }
878 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000879 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000880 return GV;
881 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000882 default:
883 break;
884 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000885
886 SmallString<256> Msg;
887 raw_svector_ostream OS(Msg);
888 OS << "ConstantExpr not handled: " << *CE;
889 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000890 }
Misha Brukman835702a2005-04-21 22:36:52 +0000891
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000892 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000893 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000894 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000895 case Type::FloatTyID:
896 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000897 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000898 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000899 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000900 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000901 case Type::X86_FP80TyID:
902 case Type::FP128TyID:
903 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000904 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000905 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000906 case Type::IntegerTyID:
907 Result.IntVal = cast<ConstantInt>(C)->getValue();
908 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000909 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000910 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000911 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000912 else if (const Function *F = dyn_cast<Function>(C))
913 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000914 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000915 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
916 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000917 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000918 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000919 case Type::VectorTyID: {
920 unsigned elemNum;
921 Type* ElemTy;
922 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
923 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
924 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
925
926 if (CDV) {
927 elemNum = CDV->getNumElements();
928 ElemTy = CDV->getElementType();
929 } else if (CV || CAZ) {
930 VectorType* VTy = dyn_cast<VectorType>(C->getType());
931 elemNum = VTy->getNumElements();
932 ElemTy = VTy->getElementType();
933 } else {
934 llvm_unreachable("Unknown constant vector type!");
935 }
936
937 Result.AggregateVal.resize(elemNum);
938 // Check if vector holds floats.
939 if(ElemTy->isFloatTy()) {
940 if (CAZ) {
941 GenericValue floatZero;
942 floatZero.FloatVal = 0.f;
943 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
944 floatZero);
945 break;
946 }
947 if(CV) {
948 for (unsigned i = 0; i < elemNum; ++i)
949 if (!isa<UndefValue>(CV->getOperand(i)))
950 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
951 CV->getOperand(i))->getValueAPF().convertToFloat();
952 break;
953 }
954 if(CDV)
955 for (unsigned i = 0; i < elemNum; ++i)
956 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
957
958 break;
959 }
960 // Check if vector holds doubles.
961 if (ElemTy->isDoubleTy()) {
962 if (CAZ) {
963 GenericValue doubleZero;
964 doubleZero.DoubleVal = 0.0;
965 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
966 doubleZero);
967 break;
968 }
969 if(CV) {
970 for (unsigned i = 0; i < elemNum; ++i)
971 if (!isa<UndefValue>(CV->getOperand(i)))
972 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
973 CV->getOperand(i))->getValueAPF().convertToDouble();
974 break;
975 }
976 if(CDV)
977 for (unsigned i = 0; i < elemNum; ++i)
978 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
979
980 break;
981 }
982 // Check if vector holds integers.
983 if (ElemTy->isIntegerTy()) {
984 if (CAZ) {
985 GenericValue intZero;
986 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
987 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
988 intZero);
989 break;
990 }
991 if(CV) {
992 for (unsigned i = 0; i < elemNum; ++i)
993 if (!isa<UndefValue>(CV->getOperand(i)))
994 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
995 CV->getOperand(i))->getValue();
996 else {
997 Result.AggregateVal[i].IntVal =
998 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
999 }
1000 break;
1001 }
1002 if(CDV)
1003 for (unsigned i = 0; i < elemNum; ++i)
1004 Result.AggregateVal[i].IntVal = APInt(
1005 CDV->getElementType()->getPrimitiveSizeInBits(),
1006 CDV->getElementAsInteger(i));
1007
1008 break;
1009 }
1010 llvm_unreachable("Unknown constant pointer type!");
1011 }
1012 break;
1013
Chris Lattner996fe012002-12-24 00:01:05 +00001014 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001015 SmallString<256> Msg;
1016 raw_svector_ostream OS(Msg);
1017 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1018 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001019 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001020
Chris Lattner996fe012002-12-24 00:01:05 +00001021 return Result;
1022}
1023
Duncan Sands1202d1b2007-12-14 19:38:31 +00001024/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1025/// with the integer held in IntVal.
1026static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1027 unsigned StoreBytes) {
1028 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001029 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001030
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001031 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001032 // Little-endian host - the source is ordered from LSB to MSB. Order the
1033 // destination from LSB to MSB: Do a straight copy.
1034 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001035 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001036 // Big-endian host - the source is an array of 64 bit words ordered from
1037 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1038 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1039 while (StoreBytes > sizeof(uint64_t)) {
1040 StoreBytes -= sizeof(uint64_t);
1041 // May not be aligned so use memcpy.
1042 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1043 Src += sizeof(uint64_t);
1044 }
1045
1046 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1047 }
1048}
1049
Evan Cheng09053e62008-11-04 06:10:31 +00001050void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001051 GenericValue *Ptr, Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001052 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001053
Reid Spencer87aa65f2007-03-06 03:04:04 +00001054 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001055 default:
1056 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1057 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001058 case Type::IntegerTyID:
1059 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001060 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001061 case Type::FloatTyID:
1062 *((float*)Ptr) = Val.FloatVal;
1063 break;
1064 case Type::DoubleTyID:
1065 *((double*)Ptr) = Val.DoubleVal;
1066 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001067 case Type::X86_FP80TyID:
1068 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1069 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001070 case Type::PointerTyID:
1071 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1072 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001073 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001074
Reid Spencer87aa65f2007-03-06 03:04:04 +00001075 *((PointerTy*)Ptr) = Val.PointerVal;
1076 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001077 case Type::VectorTyID:
1078 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1079 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1080 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1081 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1082 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1083 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1084 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1085 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1086 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1087 }
1088 }
1089 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001090 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001091
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001092 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001093 // Host and target are different endian - reverse the stored bytes.
1094 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1095}
1096
1097/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1098/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1099static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1100 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001101 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1102 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001103
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001104 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001105 // Little-endian host - the destination must be ordered from LSB to MSB.
1106 // The source is ordered from LSB to MSB: Do a straight copy.
1107 memcpy(Dst, Src, LoadBytes);
1108 else {
1109 // Big-endian - the destination is an array of 64 bit words ordered from
1110 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1111 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1112 // a word.
1113 while (LoadBytes > sizeof(uint64_t)) {
1114 LoadBytes -= sizeof(uint64_t);
1115 // May not be aligned so use memcpy.
1116 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1117 Dst += sizeof(uint64_t);
1118 }
1119
1120 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1121 }
Chris Lattner996fe012002-12-24 00:01:05 +00001122}
1123
Misha Brukman857c21b2003-10-10 17:45:12 +00001124/// FIXME: document
1125///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001126void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001127 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001128 Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001129 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001130
Duncan Sands1202d1b2007-12-14 19:38:31 +00001131 switch (Ty->getTypeID()) {
1132 case Type::IntegerTyID:
1133 // An APInt with all words initially zero.
1134 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1135 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1136 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001137 case Type::FloatTyID:
1138 Result.FloatVal = *((float*)Ptr);
1139 break;
1140 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001141 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001142 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001143 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001144 Result.PointerVal = *((PointerTy*)Ptr);
1145 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001146 case Type::X86_FP80TyID: {
1147 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001148 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001149 uint64_t y[2];
1150 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001151 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001152 break;
1153 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001154 case Type::VectorTyID: {
Craig Toppere3dcce92015-08-01 22:20:21 +00001155 auto *VT = cast<VectorType>(Ty);
1156 Type *ElemT = VT->getElementType();
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001157 const unsigned numElems = VT->getNumElements();
1158 if (ElemT->isFloatTy()) {
1159 Result.AggregateVal.resize(numElems);
1160 for (unsigned i = 0; i < numElems; ++i)
1161 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1162 }
1163 if (ElemT->isDoubleTy()) {
1164 Result.AggregateVal.resize(numElems);
1165 for (unsigned i = 0; i < numElems; ++i)
1166 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1167 }
1168 if (ElemT->isIntegerTy()) {
1169 GenericValue intZero;
1170 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1171 intZero.IntVal = APInt(elemBitWidth, 0);
1172 Result.AggregateVal.resize(numElems, intZero);
1173 for (unsigned i = 0; i < numElems; ++i)
1174 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1175 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1176 }
1177 break;
1178 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001179 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001180 SmallString<256> Msg;
1181 raw_svector_ostream OS(Msg);
1182 OS << "Cannot load value of type " << *Ty << "!";
1183 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001184 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001185}
1186
Chris Lattner996fe012002-12-24 00:01:05 +00001187void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001188 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001189 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001190 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001191 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001192
1193 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001194 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001195 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001196 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1197 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1198 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001199 }
1200
1201 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001202 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001203 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001204 }
1205
1206 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001207 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001208 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001209 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1210 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1211 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001212 }
1213
1214 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001215 const StructLayout *SL =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001216 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001217 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1218 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1219 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001220 }
1221
1222 if (const ConstantDataSequential *CDS =
1223 dyn_cast<ConstantDataSequential>(Init)) {
1224 // CDS is already laid out in host memory order.
1225 StringRef Data = CDS->getRawDataValues();
1226 memcpy(Addr, Data.data(), Data.size());
1227 return;
1228 }
1229
1230 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001231 GenericValue Val = getConstantValue(Init);
1232 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1233 return;
1234 }
1235
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001236 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001237 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001238}
1239
Chris Lattner996fe012002-12-24 00:01:05 +00001240/// EmitGlobals - Emit all of the global variables to memory, storing their
1241/// addresses into GlobalAddress. This must make sure to copy the contents of
1242/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001243void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001244 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001245 // to hold them. If there is more than one module, do a prepass over globals
1246 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001247 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001248 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001249
Chris Lattner0621cae2006-08-16 01:24:12 +00001250 if (Modules.size() != 1) {
1251 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001252 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001253 for (const auto &GV : M.globals()) {
1254 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1255 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001256 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001257
1258 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001259 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001260
1261 // If this is the first time we've seen this global, it is the canonical
1262 // version.
1263 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001264 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001265 continue;
1266 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001267
Chris Lattner0621cae2006-08-16 01:24:12 +00001268 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001269 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001270 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001271
Chris Lattner0621cae2006-08-16 01:24:12 +00001272 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001273 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001274 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1275 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001276 }
Chris Lattner996fe012002-12-24 00:01:05 +00001277 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001278 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001279
Chris Lattner0621cae2006-08-16 01:24:12 +00001280 std::vector<const GlobalValue*> NonCanonicalGlobals;
1281 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001282 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001283 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001284 // In the multi-module case, see what this global maps to.
1285 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001286 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001287 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001288 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001289 if (GVEntry != &GV) {
1290 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001291 continue;
1292 }
1293 }
1294 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001295
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001296 if (!GV.isDeclaration()) {
1297 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001298 } else {
1299 // External variable reference. Try to use the dynamic loader to
1300 // get a pointer to it.
1301 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001302 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1303 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001304 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001305 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001306 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001307 }
1308 }
1309 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001310
Chris Lattner0621cae2006-08-16 01:24:12 +00001311 // If there are multiple modules, map the non-canonical globals to their
1312 // canonical location.
1313 if (!NonCanonicalGlobals.empty()) {
1314 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1315 const GlobalValue *GV = NonCanonicalGlobals[i];
1316 const GlobalValue *CGV =
1317 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1318 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1319 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001320 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001321 }
1322 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001323
1324 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001325 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001326 for (const auto &GV : M.globals()) {
1327 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001328 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001329 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001330 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1331 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001332 continue;
1333 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001334 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001335 }
1336 }
1337 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001338}
1339
1340// EmitGlobalVariable - This method emits the specified global variable to the
1341// address specified in GlobalAddresses, or allocates new memory if it's not
1342// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001343void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001344 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001345
Craig Topper2617dcc2014-04-15 06:32:26 +00001346 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001347 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001348 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001349
1350 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001351 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001352
Chris Lattner748e8572003-12-31 20:21:04 +00001353 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001354 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001355
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001356 // Don't initialize if it's thread local, let the client do it.
1357 if (!GV->isThreadLocal())
1358 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001359
Chris Lattner229907c2011-07-18 04:54:35 +00001360 Type *ElTy = GV->getType()->getElementType();
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001361 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001362 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001363 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001364}