blob: 67b843737cd2b6abadd969d48f270ccb96b26c8f [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.
Jeffrey Yasskina4044332010-03-27 04:53:56 +000098class GVMemoryBlock : public CallbackVH {
99 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) {
192 MutexGuard locked(lock);
Rafael Espindolac233f742015-06-23 13:59:29 +0000193 Mangler Mang;
Lang Hames3dac3f72015-03-31 20:31:14 +0000194 SmallString<128> FullName;
Rafael Espindolac233f742015-06-23 13:59:29 +0000195 Mang.getNameWithPrefix(FullName, GV, false);
Lang Hames3dac3f72015-03-31 20:31:14 +0000196 return FullName.str();
197}
198
Chris Lattner6d8dd182006-05-08 22:00:52 +0000199void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000200 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000201 addGlobalMapping(getMangledName(GV), (uint64_t) Addr);
202}
Evan Cheng5cc53c32008-09-18 07:54:21 +0000203
Lang Hames3dac3f72015-03-31 20:31:14 +0000204void ExecutionEngine::addGlobalMapping(StringRef Name, uint64_t Addr) {
205 MutexGuard locked(lock);
206
207 assert(!Name.empty() && "Empty GlobalMapping symbol name!");
208
209 DEBUG(dbgs() << "JIT: Map \'" << Name << "\' to [" << Addr << "]\n";);
210 uint64_t &CurVal = EEState.getGlobalAddressMap()[Name];
Craig Topper2617dcc2014-04-15 06:32:26 +0000211 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattner6d8dd182006-05-08 22:00:52 +0000212 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000213
214 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000215 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000216 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
217 assert((!V.empty() || !Name.empty()) &&
218 "GlobalMapping already established!");
219 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000220 }
221}
222
Chris Lattner6d8dd182006-05-08 22:00:52 +0000223void ExecutionEngine::clearAllGlobalMappings() {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000224 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000225
Zachary Turner2f825df2014-06-16 20:54:28 +0000226 EEState.getGlobalAddressMap().clear();
227 EEState.getGlobalAddressReverseMap().clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000228}
229
Nate Begeman8f83fc42008-05-21 16:34:48 +0000230void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000231 MutexGuard locked(lock);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000232
233 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000234 EEState.RemoveMapping(getMangledName(FI));
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000235 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
236 GI != GE; ++GI)
Lang Hames3dac3f72015-03-31 20:31:14 +0000237 EEState.RemoveMapping(getMangledName(GI));
Nate Begeman8f83fc42008-05-21 16:34:48 +0000238}
239
Lang Hames3dac3f72015-03-31 20:31:14 +0000240uint64_t ExecutionEngine::updateGlobalMapping(const GlobalValue *GV,
241 void *Addr) {
242 MutexGuard locked(lock);
243 return updateGlobalMapping(getMangledName(GV), (uint64_t) Addr);
244}
245
246uint64_t ExecutionEngine::updateGlobalMapping(StringRef Name, uint64_t Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000247 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000248
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000249 ExecutionEngineState::GlobalAddressMapTy &Map =
Zachary Turner2f825df2014-06-16 20:54:28 +0000250 EEState.getGlobalAddressMap();
Chris Lattneree181732008-04-04 04:47:41 +0000251
Chris Lattner6d8dd182006-05-08 22:00:52 +0000252 // Deleting from the mapping?
Craig Topper2617dcc2014-04-15 06:32:26 +0000253 if (!Addr)
Lang Hames3dac3f72015-03-31 20:31:14 +0000254 return EEState.RemoveMapping(Name);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000255
Lang Hames3dac3f72015-03-31 20:31:14 +0000256 uint64_t &CurVal = Map[Name];
257 uint64_t OldVal = CurVal;
Chris Lattneree181732008-04-04 04:47:41 +0000258
Zachary Turner2f825df2014-06-16 20:54:28 +0000259 if (CurVal && !EEState.getGlobalAddressReverseMap().empty())
260 EEState.getGlobalAddressReverseMap().erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000261 CurVal = Addr;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000262
263 // If we are using the reverse mapping, add it too.
Zachary Turner2f825df2014-06-16 20:54:28 +0000264 if (!EEState.getGlobalAddressReverseMap().empty()) {
Lang Hames3dac3f72015-03-31 20:31:14 +0000265 std::string &V = EEState.getGlobalAddressReverseMap()[CurVal];
266 assert((!V.empty() || !Name.empty()) &&
267 "GlobalMapping already established!");
268 V = Name;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000269 }
Chris Lattneree181732008-04-04 04:47:41 +0000270 return OldVal;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000271}
272
Lang Hames3dac3f72015-03-31 20:31:14 +0000273uint64_t ExecutionEngine::getAddressToGlobalIfAvailable(StringRef S) {
274 MutexGuard locked(lock);
275 uint64_t Address = 0;
276 ExecutionEngineState::GlobalAddressMapTy::iterator I =
277 EEState.getGlobalAddressMap().find(S);
278 if (I != EEState.getGlobalAddressMap().end())
279 Address = I->second;
280 return Address;
281}
282
283
284void *ExecutionEngine::getPointerToGlobalIfAvailable(StringRef S) {
285 MutexGuard locked(lock);
286 if (void* Address = (void *) getAddressToGlobalIfAvailable(S))
287 return Address;
288 return nullptr;
289}
290
Chris Lattner6d8dd182006-05-08 22:00:52 +0000291void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000292 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000293 return getPointerToGlobalIfAvailable(getMangledName(GV));
Chris Lattner6d8dd182006-05-08 22:00:52 +0000294}
295
Chris Lattner748e8572003-12-31 20:21:04 +0000296const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Zachary Turnerc04b8922014-06-20 21:07:14 +0000297 MutexGuard locked(lock);
Reid Spencer79876f52005-07-12 15:51:55 +0000298
Chris Lattner748e8572003-12-31 20:21:04 +0000299 // If we haven't computed the reverse mapping yet, do so first.
Zachary Turner2f825df2014-06-16 20:54:28 +0000300 if (EEState.getGlobalAddressReverseMap().empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000301 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Lang Hames3dac3f72015-03-31 20:31:14 +0000302 I = EEState.getGlobalAddressMap().begin(),
303 E = EEState.getGlobalAddressMap().end(); I != E; ++I) {
304 StringRef Name = I->first();
305 uint64_t Addr = I->second;
Zachary Turner2f825df2014-06-16 20:54:28 +0000306 EEState.getGlobalAddressReverseMap().insert(std::make_pair(
Lang Hames3dac3f72015-03-31 20:31:14 +0000307 Addr, Name));
308 }
Chris Lattner748e8572003-12-31 20:21:04 +0000309 }
310
Lang Hames3dac3f72015-03-31 20:31:14 +0000311 std::map<uint64_t, std::string>::iterator I =
312 EEState.getGlobalAddressReverseMap().find((uint64_t) Addr);
313
314 if (I != EEState.getGlobalAddressReverseMap().end()) {
315 StringRef Name = I->second;
316 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
317 if (GlobalValue *GV = Modules[i]->getNamedValue(Name))
318 return GV;
319 }
320 return nullptr;
Chris Lattner748e8572003-12-31 20:21:04 +0000321}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000322
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000323namespace {
324class ArgvArray {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000325 std::unique_ptr<char[]> Array;
326 std::vector<std::unique_ptr<char[]>> Values;
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000327public:
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000328 /// Turn a vector of strings into a nice argv style array of pointers to null
329 /// terminated strings.
330 void *reset(LLVMContext &C, ExecutionEngine *EE,
331 const std::vector<std::string> &InputArgv);
332};
333} // anonymous namespace
334void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
335 const std::vector<std::string> &InputArgv) {
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000336 Values.clear(); // Free the old contents.
337 Values.reserve(InputArgv.size());
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000338 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000339 Array = make_unique<char[]>((InputArgv.size()+1)*PtrSize);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000340
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000341 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array.get() << "\n");
Chris Lattner229907c2011-07-18 04:54:35 +0000342 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000343
344 for (unsigned i = 0; i != InputArgv.size(); ++i) {
345 unsigned Size = InputArgv[i].size()+1;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000346 auto Dest = make_unique<char[]>(Size);
347 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest.get() << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000348
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000349 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest.get());
Chris Lattner5a0d4822003-12-26 06:50:30 +0000350 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000351
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000352 // Endian safe: Array[i] = (PointerTy)Dest;
Dylan Noblesmith4b535d12014-08-26 02:03:28 +0000353 EE->StoreValueToMemory(PTOGV(Dest.get()),
354 (GenericValue*)(&Array[i*PtrSize]), SBytePtr);
355 Values.push_back(std::move(Dest));
Chris Lattner5a0d4822003-12-26 06:50:30 +0000356 }
357
358 // Null terminate it
Craig Topper2617dcc2014-04-15 06:32:26 +0000359 EE->StoreValueToMemory(PTOGV(nullptr),
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000360 (GenericValue*)(&Array[InputArgv.size()*PtrSize]),
Chris Lattner5a0d4822003-12-26 06:50:30 +0000361 SBytePtr);
Dylan Noblesmithc4a99422014-08-25 00:58:18 +0000362 return Array.get();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000363}
364
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000365void ExecutionEngine::runStaticConstructorsDestructors(Module &module,
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000366 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000367 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000368 GlobalVariable *GV = module.getNamedGlobal(Name);
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000369
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000370 // If this global has internal linkage, or if it has a use, then it must be
371 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
372 // this is the case, don't execute any of the global ctors, __main will do
373 // it.
374 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
375
Nick Lewycky0cbfcb22011-04-06 20:38:44 +0000376 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000377 // the init priority, which we ignore.
Chris Lattner00245f42012-01-24 13:41:11 +0000378 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Craig Topper2617dcc2014-04-15 06:32:26 +0000379 if (!InitList)
Nick Lewycky0f857892011-04-11 22:11:20 +0000380 return;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000381 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner00245f42012-01-24 13:41:11 +0000382 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Craig Topper2617dcc2014-04-15 06:32:26 +0000383 if (!CS) continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000384
385 Constant *FP = CS->getOperand(1);
386 if (FP->isNullValue())
Nick Lewycky0f857892011-04-11 22:11:20 +0000387 continue; // Found a sentinal value, ignore.
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000388
389 // Strip off constant expression casts.
390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
391 if (CE->isCast())
392 FP = CE->getOperand(0);
393
394 // Execute the ctor/dtor function!
395 if (Function *F = dyn_cast<Function>(FP))
Benjamin Kramerbd7b1c82015-06-13 19:50:29 +0000396 runFunction(F, None);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000397
398 // FIXME: It is marginally lame that we just do nothing here if we see an
399 // entry we don't recognize. It might not be unreasonable for the verifier
400 // to not even allow this and just assert here.
401 }
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000402}
403
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000404void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
405 // Execute global ctors/dtors for each module in the program.
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000406 for (std::unique_ptr<Module> &M : Modules)
407 runStaticConstructorsDestructors(*M, isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000408}
409
Dan Gohmancf3e3012008-08-26 01:38:29 +0000410#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000411/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
412static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000413 unsigned PtrSize = EE->getDataLayout().getPointerSize();
Duncan Sands1202d1b2007-12-14 19:38:31 +0000414 for (unsigned i = 0; i < PtrSize; ++i)
415 if (*(i + (uint8_t*)Loc))
416 return false;
417 return true;
418}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000419#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000420
Chris Lattner5a0d4822003-12-26 06:50:30 +0000421int ExecutionEngine::runFunctionAsMain(Function *Fn,
422 const std::vector<std::string> &argv,
423 const char * const * envp) {
424 std::vector<GenericValue> GVArgs;
425 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000426 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000427
428 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000429 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattner229907c2011-07-18 04:54:35 +0000430 FunctionType *FTy = Fn->getFunctionType();
431 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000432
433 // Check the argument types.
434 if (NumArgs > 3)
435 report_fatal_error("Invalid number of arguments of main() supplied");
436 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
437 report_fatal_error("Invalid type for third argument of main() supplied");
438 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
439 report_fatal_error("Invalid type for second argument of main() supplied");
440 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
441 report_fatal_error("Invalid type for first argument of main() supplied");
442 if (!FTy->getReturnType()->isIntegerTy() &&
443 !FTy->getReturnType()->isVoidTy())
444 report_fatal_error("Invalid return type of main() supplied");
445
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000446 ArgvArray CArgv;
447 ArgvArray CEnv;
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000448 if (NumArgs) {
449 GVArgs.push_back(GVArgc); // Arg #0 = argc.
450 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000451 // Arg #1 = argv.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000452 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000453 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000454 "argv[0] was null after CreateArgv");
455 if (NumArgs > 2) {
456 std::vector<std::string> EnvVars;
457 for (unsigned i = 0; envp[i]; ++i)
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000458 EnvVars.emplace_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000459 // Arg #2 = envp.
Jeffrey Yasskinbfd38ab2010-03-26 00:59:12 +0000460 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000461 }
462 }
463 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000464
Reid Spencer87aa65f2007-03-06 03:04:04 +0000465 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000466}
467
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000468EngineBuilder::EngineBuilder() : EngineBuilder(nullptr) {}
Lang Hames93de2a12015-01-23 21:25:00 +0000469
Lang Hames4a5697e2014-12-03 00:51:19 +0000470EngineBuilder::EngineBuilder(std::unique_ptr<Module> M)
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000471 : M(std::move(M)), WhichEngine(EngineKind::Either), ErrorStr(nullptr),
Lang Hames633fe142015-03-30 03:37:06 +0000472 OptLevel(CodeGenOpt::Default), MemMgr(nullptr), Resolver(nullptr),
473 RelocModel(Reloc::Default), CMModel(CodeModel::JITDefault),
474 UseOrcMCJITReplacement(false) {
Alp Toker322db9e2014-05-31 21:26:17 +0000475// IR module verification is enabled by default in debug builds, and disabled
476// by default in release builds.
477#ifndef NDEBUG
478 VerifyModules = true;
479#else
480 VerifyModules = false;
481#endif
482}
483
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000484EngineBuilder::~EngineBuilder() = default;
485
486EngineBuilder &EngineBuilder::setMCJITMemoryManager(
487 std::unique_ptr<RTDyldMemoryManager> mcjmm) {
Lang Hames633fe142015-03-30 03:37:06 +0000488 auto SharedMM = std::shared_ptr<RTDyldMemoryManager>(std::move(mcjmm));
489 MemMgr = SharedMM;
490 Resolver = SharedMM;
491 return *this;
492}
493
494EngineBuilder&
495EngineBuilder::setMemoryManager(std::unique_ptr<MCJITMemoryManager> MM) {
496 MemMgr = std::shared_ptr<MCJITMemoryManager>(std::move(MM));
497 return *this;
498}
499
500EngineBuilder&
501EngineBuilder::setSymbolResolver(std::unique_ptr<RuntimeDyld::SymbolResolver> SR) {
502 Resolver = std::shared_ptr<RuntimeDyld::SymbolResolver>(std::move(SR));
Benjamin Kramer298a3a02015-03-06 16:21:15 +0000503 return *this;
504}
505
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000506ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Ahmed Charles56440fd2014-03-06 05:51:42 +0000507 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000508
Nick Lewyckya53414f2008-03-08 02:49:45 +0000509 // Make sure we can resolve symbols in the program as well. The zero arg
510 // to the function tells DynamicLibrary to load the program, not a library.
Craig Topper2617dcc2014-04-15 06:32:26 +0000511 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
512 return nullptr;
Filip Pizlo9bc53e82013-05-14 19:29:00 +0000513
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000514 // If the user specified a memory manager but didn't specify which engine to
515 // create, we assume they only want the JIT, and we fail if they only want
516 // the interpreter.
Lang Hames633fe142015-03-30 03:37:06 +0000517 if (MemMgr) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000518 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000519 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000520 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000521 if (ErrorStr)
522 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000523 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000524 }
525 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000526
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000527 // Unless the interpreter was explicitly selected or the JIT is not linked,
528 // try making a JIT.
Benjamin Kramer25a3d812012-04-08 14:53:14 +0000529 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000530 Triple TT(M->getTargetTriple());
Owen Andersonadd6f1d2012-03-23 17:40:56 +0000531 if (!TM->getTarget().hasJIT()) {
532 errs() << "WARNING: This target JIT is not designed for the host"
533 << " you are running. If bad things happen, please choose"
534 << " a different -march switch.\n";
535 }
Dylan Noblesmith7f262462011-12-12 04:20:36 +0000536
Lang Hamesbc876012014-04-18 06:48:23 +0000537 ExecutionEngine *EE = nullptr;
Lang Hames93de2a12015-01-23 21:25:00 +0000538 if (ExecutionEngine::OrcMCJITReplacementCtor && UseOrcMCJITReplacement) {
Lang Hames633fe142015-03-30 03:37:06 +0000539 EE = ExecutionEngine::OrcMCJITReplacementCtor(ErrorStr, std::move(MemMgr),
540 std::move(Resolver),
Lang Hames93de2a12015-01-23 21:25:00 +0000541 std::move(TheTM));
542 EE->addModule(std::move(M));
543 } else if (ExecutionEngine::MCJITCtor)
Lang Hames633fe142015-03-30 03:37:06 +0000544 EE = ExecutionEngine::MCJITCtor(std::move(M), ErrorStr, std::move(MemMgr),
545 std::move(Resolver), std::move(TheTM));
Lang Hames93de2a12015-01-23 21:25:00 +0000546
Lang Hamesbc876012014-04-18 06:48:23 +0000547 if (EE) {
548 EE->setVerifyModules(VerifyModules);
549 return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000550 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000551 }
552
553 // If we can't make a JIT and we didn't request one specifically, try making
554 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000555 if (WhichEngine & EngineKind::Interpreter) {
556 if (ExecutionEngine::InterpCtor)
Rafael Espindola2a8a2792014-08-19 04:04:25 +0000557 return ExecutionEngine::InterpCtor(std::move(M), ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000558 if (ErrorStr)
559 *ErrorStr = "Interpreter has not been linked in.";
Craig Topper2617dcc2014-04-15 06:32:26 +0000560 return nullptr;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000561 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000562
Eric Christopher79cc1e32014-09-02 22:28:02 +0000563 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::MCJITCtor) {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000564 if (ErrorStr)
565 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000566 }
567
Craig Topper2617dcc2014-04-15 06:32:26 +0000568 return nullptr;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000569}
570
Chris Lattner996fe012002-12-24 00:01:05 +0000571void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000572 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000573 return getPointerToFunction(F);
574
Zachary Turnerc04b8922014-06-20 21:07:14 +0000575 MutexGuard locked(lock);
Lang Hames3dac3f72015-03-31 20:31:14 +0000576 if (void* P = getPointerToGlobalIfAvailable(GV))
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000577 return P;
Jeff Cohen69e849012006-02-07 05:11:57 +0000578
579 // Global variable might have been added since interpreter started.
580 if (GlobalVariable *GVar =
581 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
582 EmitGlobalVariable(GVar);
583 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000584 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000585
Lang Hames3dac3f72015-03-31 20:31:14 +0000586 return getPointerToGlobalIfAvailable(GV);
Chris Lattner996fe012002-12-24 00:01:05 +0000587}
588
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000589/// \brief Converts a Constant* into a GenericValue, including handling of
590/// ConstantExpr values.
Chris Lattner996fe012002-12-24 00:01:05 +0000591GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000592 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000593 if (isa<UndefValue>(C)) {
594 GenericValue Result;
595 switch (C->getType()->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000596 default:
597 break;
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000598 case Type::IntegerTyID:
599 case Type::X86_FP80TyID:
600 case Type::FP128TyID:
601 case Type::PPC_FP128TyID:
602 // Although the value is undefined, we still have to construct an APInt
603 // with the correct bit width.
604 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
605 break;
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000606 case Type::StructTyID: {
607 // if the whole struct is 'undef' just reserve memory for the value.
608 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
609 unsigned int elemNum = STy->getNumElements();
610 Result.AggregateVal.resize(elemNum);
611 for (unsigned int i = 0; i < elemNum; ++i) {
612 Type *ElemTy = STy->getElementType(i);
613 if (ElemTy->isIntegerTy())
614 Result.AggregateVal[i].IntVal =
615 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
616 else if (ElemTy->isAggregateType()) {
617 const Constant *ElemUndef = UndefValue::get(ElemTy);
618 Result.AggregateVal[i] = getConstantValue(ElemUndef);
619 }
620 }
621 }
622 }
623 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000624 case Type::VectorTyID:
625 // if the whole vector is 'undef' just reserve memory for the value.
626 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
627 const Type *ElemTy = VTy->getElementType();
628 unsigned int elemNum = VTy->getNumElements();
629 Result.AggregateVal.resize(elemNum);
630 if (ElemTy->isIntegerTy())
631 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky8e97f012013-09-12 10:48:23 +0000632 Result.AggregateVal[i].IntVal =
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000633 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000634 break;
635 }
636 return Result;
637 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000638
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000639 // Otherwise, if the value is a ConstantExpr...
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000640 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000641 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000642 switch (CE->getOpcode()) {
643 case Instruction::GetElementPtr: {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000644 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000645 GenericValue Result = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000646 APInt Offset(DL.getPointerSizeInBits(), 0);
647 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, Offset);
Misha Brukman835702a2005-04-21 22:36:52 +0000648
Reid Spencer87aa65f2007-03-06 03:04:04 +0000649 char* tmp = (char*) Result.PointerVal;
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000650 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattner9de0d142003-04-23 19:01:49 +0000651 return Result;
652 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000653 case Instruction::Trunc: {
654 GenericValue GV = getConstantValue(Op0);
655 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
656 GV.IntVal = GV.IntVal.trunc(BitWidth);
657 return GV;
658 }
659 case Instruction::ZExt: {
660 GenericValue GV = getConstantValue(Op0);
661 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
662 GV.IntVal = GV.IntVal.zext(BitWidth);
663 return GV;
664 }
665 case Instruction::SExt: {
666 GenericValue GV = getConstantValue(Op0);
667 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
668 GV.IntVal = GV.IntVal.sext(BitWidth);
669 return GV;
670 }
671 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000672 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000673 GenericValue GV = getConstantValue(Op0);
674 GV.FloatVal = float(GV.DoubleVal);
675 return GV;
676 }
677 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000678 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000679 GenericValue GV = getConstantValue(Op0);
680 GV.DoubleVal = double(GV.FloatVal);
681 return GV;
682 }
683 case Instruction::UIToFP: {
684 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000685 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000686 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000687 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000688 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000689 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000690 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000691 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000692 false,
693 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000694 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000695 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000696 return GV;
697 }
698 case Instruction::SIToFP: {
699 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000700 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000701 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000702 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000703 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000704 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer31920b02010-12-04 15:28:22 +0000705 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000706 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohmanca24fd92008-02-29 01:27:13 +0000707 true,
708 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000709 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000710 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000711 return GV;
712 }
713 case Instruction::FPToUI: // double->APInt conversion handles sign
714 case Instruction::FPToSI: {
715 GenericValue GV = getConstantValue(Op0);
716 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000717 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000718 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000719 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000720 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000721 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover29178a32013-01-22 09:46:31 +0000722 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000723 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000724 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000725 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000726 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000727 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000728 GV.IntVal = v; // endian?
729 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000730 return GV;
731 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000732 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000733 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000734 uint32_t PtrWidth = DL.getTypeSizeInBits(Op0->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000735 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000736 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000737 uint32_t IntWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000738 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000739 return GV;
740 }
741 case Instruction::IntToPtr: {
742 GenericValue GV = getConstantValue(Op0);
Mehdi Aminia3fcefb2015-07-16 16:34:23 +0000743 uint32_t PtrWidth = DL.getTypeSizeInBits(CE->getType());
Eli Friedmanfc1f2cd2012-10-30 22:21:55 +0000744 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000745 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
746 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000747 return GV;
748 }
749 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000750 GenericValue GV = getConstantValue(Op0);
Chris Lattner229907c2011-07-18 04:54:35 +0000751 Type* DestTy = CE->getType();
Reid Spencer4fd528f2007-03-06 22:23:15 +0000752 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000753 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000754 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000755 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000756 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000757 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000758 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000759 GV.DoubleVal = GV.IntVal.bitsToDouble();
760 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000761 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000762 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000763 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000764 break;
765 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000766 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foad3447fb02010-11-28 21:04:48 +0000767 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencer4fd528f2007-03-06 22:23:15 +0000768 break;
769 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000770 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000771 break; // getConstantValue(Op0) above already converted it
772 }
773 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000774 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000775 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000776 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000777 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000778 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000779 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000780 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000781 case Instruction::UDiv:
782 case Instruction::SDiv:
783 case Instruction::URem:
784 case Instruction::SRem:
785 case Instruction::And:
786 case Instruction::Or:
787 case Instruction::Xor: {
788 GenericValue LHS = getConstantValue(Op0);
789 GenericValue RHS = getConstantValue(CE->getOperand(1));
790 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000791 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000792 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000793 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000794 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000795 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000796 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
797 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
798 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
799 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
800 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
801 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
802 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
803 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
804 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
805 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
806 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000807 break;
808 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000809 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000810 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000811 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000812 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000813 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000814 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000815 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000816 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000817 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000818 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000819 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000820 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000821 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000822 break;
823 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000824 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000825 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000826 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000827 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000828 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000829 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000830 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000831 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000832 case Instruction::FDiv:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000833 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000834 case Instruction::FRem:
Chris Lattner93cd0f1c2010-05-15 17:10:24 +0000835 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencer4fd528f2007-03-06 22:23:15 +0000836 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000837 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000838 case Type::X86_FP80TyID:
839 case Type::PPC_FP128TyID:
840 case Type::FP128TyID: {
Tim Northover29178a32013-01-22 09:46:31 +0000841 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
842 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000843 switch (CE->getOpcode()) {
Daniel Dunbare4f47432010-11-13 00:55:42 +0000844 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000845 case Instruction::FAdd:
Tim Northover29178a32013-01-22 09:46:31 +0000846 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000847 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000848 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000849 case Instruction::FSub:
Tim Northover29178a32013-01-22 09:46:31 +0000850 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
851 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000852 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000853 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000854 case Instruction::FMul:
Tim Northover29178a32013-01-22 09:46:31 +0000855 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
856 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000857 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000858 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000859 case Instruction::FDiv:
Tim Northover29178a32013-01-22 09:46:31 +0000860 apfLHS.divide(APFloat(Sem, RHS.IntVal),
861 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000862 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000863 break;
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000864 case Instruction::FRem:
Tim Northover29178a32013-01-22 09:46:31 +0000865 apfLHS.mod(APFloat(Sem, RHS.IntVal),
866 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000867 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000868 break;
869 }
870 }
871 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000872 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000873 return GV;
874 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000875 default:
876 break;
877 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000878
879 SmallString<256> Msg;
880 raw_svector_ostream OS(Msg);
881 OS << "ConstantExpr not handled: " << *CE;
882 report_fatal_error(OS.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000883 }
Misha Brukman835702a2005-04-21 22:36:52 +0000884
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000885 // Otherwise, we have a simple constant.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000886 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000887 switch (C->getType()->getTypeID()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +0000888 case Type::FloatTyID:
889 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000890 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000891 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000892 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000893 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000894 case Type::X86_FP80TyID:
895 case Type::FP128TyID:
896 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000897 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000898 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000899 case Type::IntegerTyID:
900 Result.IntVal = cast<ConstantInt>(C)->getValue();
901 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000902 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000903 if (isa<ConstantPointerNull>(C))
Craig Topper2617dcc2014-04-15 06:32:26 +0000904 Result.PointerVal = nullptr;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000905 else if (const Function *F = dyn_cast<Function>(C))
906 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000907 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000908 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
909 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000910 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000911 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +0000912 case Type::VectorTyID: {
913 unsigned elemNum;
914 Type* ElemTy;
915 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
916 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
917 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
918
919 if (CDV) {
920 elemNum = CDV->getNumElements();
921 ElemTy = CDV->getElementType();
922 } else if (CV || CAZ) {
923 VectorType* VTy = dyn_cast<VectorType>(C->getType());
924 elemNum = VTy->getNumElements();
925 ElemTy = VTy->getElementType();
926 } else {
927 llvm_unreachable("Unknown constant vector type!");
928 }
929
930 Result.AggregateVal.resize(elemNum);
931 // Check if vector holds floats.
932 if(ElemTy->isFloatTy()) {
933 if (CAZ) {
934 GenericValue floatZero;
935 floatZero.FloatVal = 0.f;
936 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
937 floatZero);
938 break;
939 }
940 if(CV) {
941 for (unsigned i = 0; i < elemNum; ++i)
942 if (!isa<UndefValue>(CV->getOperand(i)))
943 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
944 CV->getOperand(i))->getValueAPF().convertToFloat();
945 break;
946 }
947 if(CDV)
948 for (unsigned i = 0; i < elemNum; ++i)
949 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
950
951 break;
952 }
953 // Check if vector holds doubles.
954 if (ElemTy->isDoubleTy()) {
955 if (CAZ) {
956 GenericValue doubleZero;
957 doubleZero.DoubleVal = 0.0;
958 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
959 doubleZero);
960 break;
961 }
962 if(CV) {
963 for (unsigned i = 0; i < elemNum; ++i)
964 if (!isa<UndefValue>(CV->getOperand(i)))
965 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
966 CV->getOperand(i))->getValueAPF().convertToDouble();
967 break;
968 }
969 if(CDV)
970 for (unsigned i = 0; i < elemNum; ++i)
971 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
972
973 break;
974 }
975 // Check if vector holds integers.
976 if (ElemTy->isIntegerTy()) {
977 if (CAZ) {
978 GenericValue intZero;
979 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
980 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
981 intZero);
982 break;
983 }
984 if(CV) {
985 for (unsigned i = 0; i < elemNum; ++i)
986 if (!isa<UndefValue>(CV->getOperand(i)))
987 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
988 CV->getOperand(i))->getValue();
989 else {
990 Result.AggregateVal[i].IntVal =
991 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
992 }
993 break;
994 }
995 if(CDV)
996 for (unsigned i = 0; i < elemNum; ++i)
997 Result.AggregateVal[i].IntVal = APInt(
998 CDV->getElementType()->getPrimitiveSizeInBits(),
999 CDV->getElementAsInteger(i));
1000
1001 break;
1002 }
1003 llvm_unreachable("Unknown constant pointer type!");
1004 }
1005 break;
1006
Chris Lattner996fe012002-12-24 00:01:05 +00001007 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001008 SmallString<256> Msg;
1009 raw_svector_ostream OS(Msg);
1010 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
1011 report_fatal_error(OS.str());
Chris Lattner996fe012002-12-24 00:01:05 +00001012 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001013
Chris Lattner996fe012002-12-24 00:01:05 +00001014 return Result;
1015}
1016
Duncan Sands1202d1b2007-12-14 19:38:31 +00001017/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
1018/// with the integer held in IntVal.
1019static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
1020 unsigned StoreBytes) {
1021 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divackyad06cee2012-09-05 22:26:57 +00001022 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands1202d1b2007-12-14 19:38:31 +00001023
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001024 if (sys::IsLittleEndianHost) {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001025 // Little-endian host - the source is ordered from LSB to MSB. Order the
1026 // destination from LSB to MSB: Do a straight copy.
1027 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001028 } else {
Duncan Sands1202d1b2007-12-14 19:38:31 +00001029 // Big-endian host - the source is an array of 64 bit words ordered from
1030 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
1031 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
1032 while (StoreBytes > sizeof(uint64_t)) {
1033 StoreBytes -= sizeof(uint64_t);
1034 // May not be aligned so use memcpy.
1035 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1036 Src += sizeof(uint64_t);
1037 }
1038
1039 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1040 }
1041}
1042
Evan Cheng09053e62008-11-04 06:10:31 +00001043void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattner229907c2011-07-18 04:54:35 +00001044 GenericValue *Ptr, Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001045 const unsigned StoreBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001046
Reid Spencer87aa65f2007-03-06 03:04:04 +00001047 switch (Ty->getTypeID()) {
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001048 default:
1049 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1050 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001051 case Type::IntegerTyID:
1052 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001053 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001054 case Type::FloatTyID:
1055 *((float*)Ptr) = Val.FloatVal;
1056 break;
1057 case Type::DoubleTyID:
1058 *((double*)Ptr) = Val.DoubleVal;
1059 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001060 case Type::X86_FP80TyID:
1061 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1062 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001063 case Type::PointerTyID:
1064 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1065 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth93da3c82011-04-28 08:37:18 +00001066 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands1202d1b2007-12-14 19:38:31 +00001067
Reid Spencer87aa65f2007-03-06 03:04:04 +00001068 *((PointerTy*)Ptr) = Val.PointerVal;
1069 break;
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001070 case Type::VectorTyID:
1071 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1072 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1073 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1074 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1075 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1076 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1077 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1078 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1079 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1080 }
1081 }
1082 break;
Chris Lattner996fe012002-12-24 00:01:05 +00001083 }
Duncan Sands1202d1b2007-12-14 19:38:31 +00001084
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001085 if (sys::IsLittleEndianHost != getDataLayout().isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +00001086 // Host and target are different endian - reverse the stored bytes.
1087 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1088}
1089
1090/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1091/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1092static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1093 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greene82b63572013-01-14 21:04:45 +00001094 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1095 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands1202d1b2007-12-14 19:38:31 +00001096
Rafael Espindola41cb64f2013-04-15 14:44:24 +00001097 if (sys::IsLittleEndianHost)
Duncan Sands1202d1b2007-12-14 19:38:31 +00001098 // Little-endian host - the destination must be ordered from LSB to MSB.
1099 // The source is ordered from LSB to MSB: Do a straight copy.
1100 memcpy(Dst, Src, LoadBytes);
1101 else {
1102 // Big-endian - the destination is an array of 64 bit words ordered from
1103 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1104 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1105 // a word.
1106 while (LoadBytes > sizeof(uint64_t)) {
1107 LoadBytes -= sizeof(uint64_t);
1108 // May not be aligned so use memcpy.
1109 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1110 Dst += sizeof(uint64_t);
1111 }
1112
1113 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1114 }
Chris Lattner996fe012002-12-24 00:01:05 +00001115}
1116
Misha Brukman857c21b2003-10-10 17:45:12 +00001117/// FIXME: document
1118///
Duncan Sands1202d1b2007-12-14 19:38:31 +00001119void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +00001120 GenericValue *Ptr,
Chris Lattner229907c2011-07-18 04:54:35 +00001121 Type *Ty) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001122 const unsigned LoadBytes = getDataLayout().getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +00001123
Duncan Sands1202d1b2007-12-14 19:38:31 +00001124 switch (Ty->getTypeID()) {
1125 case Type::IntegerTyID:
1126 // An APInt with all words initially zero.
1127 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1128 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1129 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +00001130 case Type::FloatTyID:
1131 Result.FloatVal = *((float*)Ptr);
1132 break;
1133 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +00001134 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +00001135 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +00001136 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +00001137 Result.PointerVal = *((PointerTy*)Ptr);
1138 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +00001139 case Type::X86_FP80TyID: {
1140 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +00001141 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +00001142 uint64_t y[2];
1143 memcpy(y, Ptr, 10);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00001144 Result.IntVal = APInt(80, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +00001145 break;
1146 }
Nadav Rotembe79a7a2013-04-01 15:53:30 +00001147 case Type::VectorTyID: {
1148 const VectorType *VT = cast<VectorType>(Ty);
1149 const Type *ElemT = VT->getElementType();
1150 const unsigned numElems = VT->getNumElements();
1151 if (ElemT->isFloatTy()) {
1152 Result.AggregateVal.resize(numElems);
1153 for (unsigned i = 0; i < numElems; ++i)
1154 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1155 }
1156 if (ElemT->isDoubleTy()) {
1157 Result.AggregateVal.resize(numElems);
1158 for (unsigned i = 0; i < numElems; ++i)
1159 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1160 }
1161 if (ElemT->isIntegerTy()) {
1162 GenericValue intZero;
1163 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1164 intZero.IntVal = APInt(elemBitWidth, 0);
1165 Result.AggregateVal.resize(numElems, intZero);
1166 for (unsigned i = 0; i < numElems; ++i)
1167 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1168 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1169 }
1170 break;
1171 }
Reid Spencer87aa65f2007-03-06 03:04:04 +00001172 default:
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001173 SmallString<256> Msg;
1174 raw_svector_ostream OS(Msg);
1175 OS << "Cannot load value of type " << *Ty << "!";
1176 report_fatal_error(OS.str());
Chris Lattner7f389e82003-05-08 16:52:16 +00001177 }
Chris Lattner7f389e82003-05-08 16:52:16 +00001178}
1179
Chris Lattner996fe012002-12-24 00:01:05 +00001180void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +00001181 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +00001182 DEBUG(Init->dump());
Chris Lattner00245f42012-01-24 13:41:11 +00001183 if (isa<UndefValue>(Init))
Chris Lattner61753bf2004-10-16 18:19:26 +00001184 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001185
1186 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +00001187 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001188 getDataLayout().getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +00001189 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1190 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1191 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001192 }
1193
1194 if (isa<ConstantAggregateZero>(Init)) {
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001195 memset(Addr, 0, (size_t)getDataLayout().getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +00001196 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001197 }
1198
1199 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001200 unsigned ElementSize =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001201 getDataLayout().getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001202 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1203 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1204 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001205 }
1206
1207 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001208 const StructLayout *SL =
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001209 getDataLayout().getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman69ddfbf2008-05-20 03:20:09 +00001210 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1211 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1212 return;
Chris Lattner00245f42012-01-24 13:41:11 +00001213 }
1214
1215 if (const ConstantDataSequential *CDS =
1216 dyn_cast<ConstantDataSequential>(Init)) {
1217 // CDS is already laid out in host memory order.
1218 StringRef Data = CDS->getRawDataValues();
1219 memcpy(Addr, Data.data(), Data.size());
1220 return;
1221 }
1222
1223 if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +00001224 GenericValue Val = getConstantValue(Init);
1225 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1226 return;
1227 }
1228
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001229 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinfbcc6632009-07-14 16:55:14 +00001230 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +00001231}
1232
Chris Lattner996fe012002-12-24 00:01:05 +00001233/// EmitGlobals - Emit all of the global variables to memory, storing their
1234/// addresses into GlobalAddress. This must make sure to copy the contents of
1235/// their initializers into the memory.
Chris Lattner996fe012002-12-24 00:01:05 +00001236void ExecutionEngine::emitGlobals() {
Chris Lattner996fe012002-12-24 00:01:05 +00001237 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +00001238 // to hold them. If there is more than one module, do a prepass over globals
1239 // to figure out how the different modules should link together.
Chris Lattner229907c2011-07-18 04:54:35 +00001240 std::map<std::pair<std::string, Type*>,
Chris Lattner0621cae2006-08-16 01:24:12 +00001241 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +00001242
Chris Lattner0621cae2006-08-16 01:24:12 +00001243 if (Modules.size() != 1) {
1244 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001245 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001246 for (const auto &GV : M.globals()) {
1247 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1248 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattner0621cae2006-08-16 01:24:12 +00001249 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001250
1251 const GlobalValue *&GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001252 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattner0621cae2006-08-16 01:24:12 +00001253
1254 // If this is the first time we've seen this global, it is the canonical
1255 // version.
1256 if (!GVEntry) {
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001257 GVEntry = &GV;
Chris Lattner0621cae2006-08-16 01:24:12 +00001258 continue;
1259 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001260
Chris Lattner0621cae2006-08-16 01:24:12 +00001261 // If the existing global is strong, never replace it.
Nico Rieck7157bb72014-01-14 15:22:47 +00001262 if (GVEntry->hasExternalLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +00001263 continue;
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001264
Chris Lattner0621cae2006-08-16 01:24:12 +00001265 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +00001266 // symbol. FIXME is this right for common?
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001267 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1268 GVEntry = &GV;
Chris Lattner9de0d142003-04-23 19:01:49 +00001269 }
Chris Lattner996fe012002-12-24 00:01:05 +00001270 }
Chris Lattner0621cae2006-08-16 01:24:12 +00001271 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001272
Chris Lattner0621cae2006-08-16 01:24:12 +00001273 std::vector<const GlobalValue*> NonCanonicalGlobals;
1274 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00001275 Module &M = *Modules[m];
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001276 for (const auto &GV : M.globals()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001277 // In the multi-module case, see what this global maps to.
1278 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001279 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001280 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001281 // If something else is the canonical global, ignore this one.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001282 if (GVEntry != &GV) {
1283 NonCanonicalGlobals.push_back(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001284 continue;
1285 }
1286 }
1287 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001288
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001289 if (!GV.isDeclaration()) {
1290 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattner0621cae2006-08-16 01:24:12 +00001291 } else {
1292 // External variable reference. Try to use the dynamic loader to
1293 // get a pointer to it.
1294 if (void *SymAddr =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001295 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1296 addGlobalMapping(&GV, SymAddr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001297 else {
Chris Lattner2104b8d2010-04-07 22:58:41 +00001298 report_fatal_error("Could not resolve external global address: "
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001299 +GV.getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001300 }
1301 }
1302 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001303
Chris Lattner0621cae2006-08-16 01:24:12 +00001304 // If there are multiple modules, map the non-canonical globals to their
1305 // canonical location.
1306 if (!NonCanonicalGlobals.empty()) {
1307 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1308 const GlobalValue *GV = NonCanonicalGlobals[i];
1309 const GlobalValue *CGV =
1310 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1311 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1312 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001313 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001314 }
1315 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001316
1317 // Now that all of the globals are set up in memory, loop through them all
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001318 // and initialize their contents.
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001319 for (const auto &GV : M.globals()) {
1320 if (!GV.isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001321 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001322 if (const GlobalValue *GVEntry =
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001323 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1324 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattner0621cae2006-08-16 01:24:12 +00001325 continue;
1326 }
Rafael Espindola49bb65a2014-05-08 18:17:44 +00001327 EmitGlobalVariable(&GV);
Chris Lattner0621cae2006-08-16 01:24:12 +00001328 }
1329 }
1330 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001331}
1332
1333// EmitGlobalVariable - This method emits the specified global variable to the
1334// address specified in GlobalAddresses, or allocates new memory if it's not
1335// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001336void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001337 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001338
Craig Topper2617dcc2014-04-15 06:32:26 +00001339 if (!GA) {
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001340 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001341 GA = getMemoryForGV(GV);
Andrew Kaylor3b442372013-11-15 17:52:54 +00001342
1343 // If we failed to allocate memory for this global, return.
Craig Topper2617dcc2014-04-15 06:32:26 +00001344 if (!GA) return;
Andrew Kaylor3b442372013-11-15 17:52:54 +00001345
Chris Lattner748e8572003-12-31 20:21:04 +00001346 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001347 }
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001348
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001349 // Don't initialize if it's thread local, let the client do it.
1350 if (!GV->isThreadLocal())
1351 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar868e3f02010-11-13 02:48:57 +00001352
Chris Lattner229907c2011-07-18 04:54:35 +00001353 Type *ElTy = GV->getType()->getElementType();
Mehdi Aminia3fcefb2015-07-16 16:34:23 +00001354 size_t GVSize = (size_t)getDataLayout().getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001355 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001356 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001357}