blob: 6766ef1512a0841040c8bbf16923a220a61a50f6 [file] [log] [blame]
Misha Brukman4afac182003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00009//
Chris Lattnerbd199fb2002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000015#include "llvm/ExecutionEngine/ExecutionEngine.h"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000016#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000017#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ExecutionEngine/GenericValue.h"
Stephen Hines36b56882014-04-23 16:57:46 -070019#include "llvm/ExecutionEngine/JITMemoryManager.h"
20#include "llvm/ExecutionEngine/ObjectCache.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Operator.h"
Stephen Hines36b56882014-04-23 16:57:46 -070026#include "llvm/IR/ValueHandle.h"
Stephen Hinesdce4a402014-05-29 02:49:00 -070027#include "llvm/Object/ObjectFile.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000029#include "llvm/Support/DynamicLibrary.h"
Torok Edwin31e24662009-07-07 17:32:34 +000030#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000031#include "llvm/Support/Host.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000032#include "llvm/Support/MutexGuard.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/TargetRegistry.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000034#include "llvm/Support/raw_ostream.h"
Dylan Noblesmithc5b28582011-05-13 21:51:29 +000035#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000036#include <cmath>
37#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000038using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000039
Stephen Hinesdce4a402014-05-29 02:49:00 -070040#define DEBUG_TYPE "jit"
41
Chris Lattner36343732006-12-19 22:43:32 +000042STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
43STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000044
Juergen Ributzka35436252013-11-19 00:57:56 +000045// Pin the vtable to this file.
46void ObjectCache::anchor() {}
47void ObjectBuffer::anchor() {}
48void ObjectBufferStream::anchor() {}
49
Jeffrey Yasskin46882612010-02-05 16:19:36 +000050ExecutionEngine *(*ExecutionEngine::JITCtor)(
51 Module *M,
52 std::string *ErrorStr,
53 JITMemoryManager *JMM,
Jeffrey Yasskin46882612010-02-05 16:19:36 +000054 bool GVsWithCode,
Stephen Hinesdce4a402014-05-29 02:49:00 -070055 TargetMachine *TM) = nullptr;
Daniel Dunbar6d135972010-11-17 16:06:37 +000056ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
57 Module *M,
58 std::string *ErrorStr,
Filip Pizlo13a3cf12013-05-14 19:29:00 +000059 RTDyldMemoryManager *MCJMM,
Daniel Dunbar6d135972010-11-17 16:06:37 +000060 bool GVsWithCode,
Stephen Hinesdce4a402014-05-29 02:49:00 -070061 TargetMachine *TM) = nullptr;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000062ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Stephen Hinesdce4a402014-05-29 02:49:00 -070063 std::string *ErrorStr) =nullptr;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000064
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000065ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000066 : EEState(*this),
Stephen Hinesdce4a402014-05-29 02:49:00 -070067 LazyFunctionCreator(nullptr) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000068 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000069 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000070 SymbolSearchingDisabled = false;
Stephen Hinesdce4a402014-05-29 02:49:00 -070071
72 // IR module verification is enabled by default in debug builds, and disabled
73 // by default in release builds.
74#ifndef NDEBUG
75 VerifyModules = true;
76#else
77 VerifyModules = false;
78#endif
79
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000080 Modules.push_back(M);
81 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000082}
83
Brian Gaeke8e539482003-09-04 22:57:27 +000084ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000085 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000086 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
87 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000088}
89
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000090namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000091/// \brief Helper class which uses a value handler to automatically deletes the
92/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000093class GVMemoryBlock : public CallbackVH {
94 GVMemoryBlock(const GlobalVariable *GV)
95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
96
97public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000098 /// \brief Returns the address the GlobalVariable should be written into. The
99 /// GVMemoryBlock object prefixes that.
Micah Villmow3574eca2012-10-08 16:38:25 +0000100 static char *Create(const GlobalVariable *GV, const DataLayout& TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000101 Type *ElTy = GV->getType()->getElementType();
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
103 void *RawMemory = ::operator new(
Micah Villmow3574eca2012-10-08 16:38:25 +0000104 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock),
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000105 TD.getPreferredAlignment(GV))
106 + GVSize);
107 new(RawMemory) GVMemoryBlock(GV);
108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
109 }
110
Stephen Hines36b56882014-04-23 16:57:46 -0700111 void deleted() override {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000112 // We allocated with operator new and with some extra memory hanging off the
113 // end, so don't just delete this. I'm not sure if this is actually
114 // required.
115 this->~GVMemoryBlock();
116 ::operator delete(this);
117 }
118};
119} // anonymous namespace
120
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000121char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Micah Villmow3574eca2012-10-08 16:38:25 +0000122 return GVMemoryBlock::Create(GV, *getDataLayout());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000123}
124
Stephen Hinesdce4a402014-05-29 02:49:00 -0700125void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) {
126 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile.");
127}
128
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000129bool ExecutionEngine::removeModule(Module *M) {
Craig Topper6227d5c2013-07-04 01:31:24 +0000130 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000131 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000132 Module *Found = *I;
133 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000134 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000135 clearGlobalMappingsFromModule(M);
136 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000137 }
138 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000139 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000140}
141
Chris Lattnerfe854032006-08-16 01:24:12 +0000142Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
143 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000144 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000145 return F;
146 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700147 return nullptr;
Chris Lattnerfe854032006-08-16 01:24:12 +0000148}
149
150
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000151void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
152 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000153 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000154 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000155
156 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
157 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000158 if (I == GlobalAddressMap.end())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700159 OldVal = nullptr;
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000160 else {
161 OldVal = I->second;
162 GlobalAddressMap.erase(I);
163 }
164
165 GlobalAddressReverseMap.erase(OldVal);
166 return OldVal;
167}
168
Chris Lattnere7fd5532006-05-08 22:00:52 +0000169void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
170 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000171
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000172 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000173 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000174 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700175 assert((!CurVal || !Addr) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000176 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000177
178 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000179 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000180 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000181 EEState.getGlobalAddressReverseMap(locked)[Addr];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700182 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000183 V = GV;
184 }
185}
186
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187void ExecutionEngine::clearAllGlobalMappings() {
188 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000189
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000190 EEState.getGlobalAddressMap(locked).clear();
191 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000192}
193
Nate Begemanf049e072008-05-21 16:34:48 +0000194void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
195 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000196
197 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000198 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000199 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
200 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000201 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000202}
203
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000204void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000205 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000206
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000207 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000208 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000209
Chris Lattnere7fd5532006-05-08 22:00:52 +0000210 // Deleting from the mapping?
Stephen Hinesdce4a402014-05-29 02:49:00 -0700211 if (!Addr)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000212 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000213
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000214 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000215 void *OldVal = CurVal;
216
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000217 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
218 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000219 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000220
221 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000222 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000223 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000224 EEState.getGlobalAddressReverseMap(locked)[Addr];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700225 assert((!V || !GV) && "GlobalMapping already established!");
Chris Lattnere7fd5532006-05-08 22:00:52 +0000226 V = GV;
227 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000228 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000229}
230
Chris Lattnere7fd5532006-05-08 22:00:52 +0000231void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
232 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000233
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000234 ExecutionEngineState::GlobalAddressMapTy::iterator I =
235 EEState.getGlobalAddressMap(locked).find(GV);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700236 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : nullptr;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000237}
238
Chris Lattner55d86482003-12-31 20:21:04 +0000239const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000240 MutexGuard locked(lock);
241
Chris Lattner55d86482003-12-31 20:21:04 +0000242 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000243 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000244 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000245 I = EEState.getGlobalAddressMap(locked).begin(),
246 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000247 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
248 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000249 }
250
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000251 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000252 EEState.getGlobalAddressReverseMap(locked).find(Addr);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700253 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : nullptr;
Chris Lattner55d86482003-12-31 20:21:04 +0000254}
Chris Lattner87f03102003-12-26 06:50:30 +0000255
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000256namespace {
257class ArgvArray {
258 char *Array;
259 std::vector<char*> Values;
260public:
Stephen Hinesdce4a402014-05-29 02:49:00 -0700261 ArgvArray() : Array(nullptr) {}
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000262 ~ArgvArray() { clear(); }
263 void clear() {
264 delete[] Array;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700265 Array = nullptr;
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000266 for (size_t I = 0, E = Values.size(); I != E; ++I) {
267 delete[] Values[I];
268 }
269 Values.clear();
270 }
271 /// Turn a vector of strings into a nice argv style array of pointers to null
272 /// terminated strings.
273 void *reset(LLVMContext &C, ExecutionEngine *EE,
274 const std::vector<std::string> &InputArgv);
275};
276} // anonymous namespace
277void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
278 const std::vector<std::string> &InputArgv) {
279 clear(); // Free the old contents.
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000280 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000281 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000282
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000283 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000284 Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000285
286 for (unsigned i = 0; i != InputArgv.size(); ++i) {
287 unsigned Size = InputArgv[i].size()+1;
288 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000289 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000290 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000291
Chris Lattner87f03102003-12-26 06:50:30 +0000292 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
293 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000294
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000295 // Endian safe: Array[i] = (PointerTy)Dest;
296 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000297 SBytePtr);
298 }
299
300 // Null terminate it
Stephen Hinesdce4a402014-05-29 02:49:00 -0700301 EE->StoreValueToMemory(PTOGV(nullptr),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000302 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000303 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000304 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000305}
306
Chris Lattnerfbd39762009-09-23 01:46:04 +0000307void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
308 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000309 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000310 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000311
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000312 // If this global has internal linkage, or if it has a use, then it must be
313 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
314 // this is the case, don't execute any of the global ctors, __main will do
315 // it.
316 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
317
Nick Lewyckya040d472011-04-06 20:38:44 +0000318 // Should be an array of '{ i32, void ()* }' structs. The first value is
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000319 // the init priority, which we ignore.
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000320 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Stephen Hinesdce4a402014-05-29 02:49:00 -0700321 if (!InitList)
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000322 return;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000323 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +0000324 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
Stephen Hinesdce4a402014-05-29 02:49:00 -0700325 if (!CS) continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000326
327 Constant *FP = CS->getOperand(1);
328 if (FP->isNullValue())
Nick Lewycky5ea5c612011-04-11 22:11:20 +0000329 continue; // Found a sentinal value, ignore.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000330
331 // Strip off constant expression casts.
332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
333 if (CE->isCast())
334 FP = CE->getOperand(0);
335
336 // Execute the ctor/dtor function!
337 if (Function *F = dyn_cast<Function>(FP))
338 runFunction(F, std::vector<GenericValue>());
339
340 // FIXME: It is marginally lame that we just do nothing here if we see an
341 // entry we don't recognize. It might not be unreasonable for the verifier
342 // to not even allow this and just assert here.
343 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000344}
345
Evan Cheng18314dc2008-09-30 15:51:21 +0000346void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
347 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000348 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
349 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000350}
351
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000352#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000353/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
354static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000355 unsigned PtrSize = EE->getDataLayout()->getPointerSize();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000356 for (unsigned i = 0; i < PtrSize; ++i)
357 if (*(i + (uint8_t*)Loc))
358 return false;
359 return true;
360}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000361#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000362
Chris Lattner87f03102003-12-26 06:50:30 +0000363int ExecutionEngine::runFunctionAsMain(Function *Fn,
364 const std::vector<std::string> &argv,
365 const char * const * envp) {
366 std::vector<GenericValue> GVArgs;
367 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000368 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000369
370 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000371 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000372 FunctionType *FTy = Fn->getFunctionType();
373 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000374
375 // Check the argument types.
376 if (NumArgs > 3)
377 report_fatal_error("Invalid number of arguments of main() supplied");
378 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
379 report_fatal_error("Invalid type for third argument of main() supplied");
380 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
381 report_fatal_error("Invalid type for second argument of main() supplied");
382 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
383 report_fatal_error("Invalid type for first argument of main() supplied");
384 if (!FTy->getReturnType()->isIntegerTy() &&
385 !FTy->getReturnType()->isVoidTy())
386 report_fatal_error("Invalid return type of main() supplied");
387
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000388 ArgvArray CArgv;
389 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000390 if (NumArgs) {
391 GVArgs.push_back(GVArgc); // Arg #0 = argc.
392 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000393 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000394 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000395 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000396 "argv[0] was null after CreateArgv");
397 if (NumArgs > 2) {
398 std::vector<std::string> EnvVars;
399 for (unsigned i = 0; envp[i]; ++i)
400 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000401 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000402 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000403 }
404 }
405 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000406
Reid Spencer8fb0f192007-03-06 03:04:04 +0000407 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000408}
409
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000410ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000411 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000412 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000413 CodeGenOpt::Level OptLevel,
414 bool GVsWithCode) {
Owen Anderson8e1fc562012-03-23 17:40:56 +0000415 EngineBuilder EB = EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000416 .setEngineKind(ForceInterpreter
417 ? EngineKind::Interpreter
418 : EngineKind::JIT)
419 .setErrorStr(ErrorStr)
420 .setOptLevel(OptLevel)
Owen Anderson8e1fc562012-03-23 17:40:56 +0000421 .setAllocateGVsWithCode(GVsWithCode);
422
423 return EB.create();
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000424}
Brian Gaeke82d82772003-09-03 20:34:19 +0000425
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000426/// createJIT - This is the factory method for creating a JIT for the current
427/// machine, it does not fall back to the interpreter. This takes ownership
428/// of the module.
429ExecutionEngine *ExecutionEngine::createJIT(Module *M,
430 std::string *ErrorStr,
431 JITMemoryManager *JMM,
Dylan Noblesmithd95e67d2011-12-01 21:49:21 +0000432 CodeGenOpt::Level OL,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000433 bool GVsWithCode,
Evan Cheng43966132011-07-19 06:37:02 +0000434 Reloc::Model RM,
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000435 CodeModel::Model CMM) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700436 if (!ExecutionEngine::JITCtor) {
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000437 if (ErrorStr)
438 *ErrorStr = "JIT has not been linked in.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700439 return nullptr;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000440 }
441
442 // Use the defaults for extra parameters. Users can use EngineBuilder to
443 // set them.
Owen Anderson8e1fc562012-03-23 17:40:56 +0000444 EngineBuilder EB(M);
445 EB.setEngineKind(EngineKind::JIT);
446 EB.setErrorStr(ErrorStr);
447 EB.setRelocationModel(RM);
448 EB.setCodeModel(CMM);
449 EB.setAllocateGVsWithCode(GVsWithCode);
450 EB.setOptLevel(OL);
451 EB.setJITMemoryManager(JMM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000452
Peter Collingbourned40e1032011-12-07 23:58:57 +0000453 // TODO: permit custom TargetOptions here
Owen Anderson8e1fc562012-03-23 17:40:56 +0000454 TargetMachine *TM = EB.selectTarget();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700455 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr;
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000456
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000457 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM);
Dylan Noblesmithf5895e92011-05-13 22:02:53 +0000458}
459
Owen Anderson8e1fc562012-03-23 17:40:56 +0000460ExecutionEngine *EngineBuilder::create(TargetMachine *TM) {
Stephen Hines36b56882014-04-23 16:57:46 -0700461 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000462
Nick Lewycky6456d862008-03-08 02:49:45 +0000463 // Make sure we can resolve symbols in the program as well. The zero arg
464 // to the function tells DynamicLibrary to load the program, not a library.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700465 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr))
466 return nullptr;
Nick Lewycky6456d862008-03-08 02:49:45 +0000467
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000468 assert(!(JMM && MCJMM));
469
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000470 // If the user specified a memory manager but didn't specify which engine to
471 // create, we assume they only want the JIT, and we fail if they only want
472 // the interpreter.
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000473 if (JMM || MCJMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000474 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000475 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000476 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000477 if (ErrorStr)
478 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700479 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000480 }
481 }
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000482
483 if (MCJMM && ! UseMCJIT) {
484 if (ErrorStr)
485 *ErrorStr =
486 "Cannot create a legacy JIT with a runtime dyld memory "
487 "manager.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700488 return nullptr;
Filip Pizlo13a3cf12013-05-14 19:29:00 +0000489 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000490
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000491 // Unless the interpreter was explicitly selected or the JIT is not linked,
492 // try making a JIT.
Benjamin Kramer0f554492012-04-08 14:53:14 +0000493 if ((WhichEngine & EngineKind::JIT) && TheTM) {
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000494 Triple TT(M->getTargetTriple());
Owen Anderson8e1fc562012-03-23 17:40:56 +0000495 if (!TM->getTarget().hasJIT()) {
496 errs() << "WARNING: This target JIT is not designed for the host"
497 << " you are running. If bad things happen, please choose"
498 << " a different -march switch.\n";
499 }
Dylan Noblesmith9ea47172011-12-12 04:20:36 +0000500
Stephen Hinesdce4a402014-05-29 02:49:00 -0700501 ExecutionEngine *EE = nullptr;
502 if (UseMCJIT && ExecutionEngine::MCJITCtor)
503 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM,
504 AllocateGVsWithCode, TheTM.release());
505 else if (ExecutionEngine::JITCtor)
506 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM,
507 AllocateGVsWithCode, TheTM.release());
508
509 if (EE) {
510 EE->setVerifyModules(VerifyModules);
511 return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000512 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000513 }
514
515 // If we can't make a JIT and we didn't request one specifically, try making
516 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000517 if (WhichEngine & EngineKind::Interpreter) {
518 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000519 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000520 if (ErrorStr)
521 *ErrorStr = "Interpreter has not been linked in.";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700522 return nullptr;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000523 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000524
Stephen Hinesdce4a402014-05-29 02:49:00 -0700525 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor &&
526 !ExecutionEngine::MCJITCtor) {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000527 if (ErrorStr)
528 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000529 }
530
Stephen Hinesdce4a402014-05-29 02:49:00 -0700531 return nullptr;
Brian Gaeke82d82772003-09-03 20:34:19 +0000532}
533
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000534void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000535 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000536 return getPointerToFunction(F);
537
Reid Spenceree448632005-07-12 15:51:55 +0000538 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000539 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
540 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000541
542 // Global variable might have been added since interpreter started.
543 if (GlobalVariable *GVar =
544 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
545 EmitGlobalVariable(GVar);
546 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000547 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000548
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000549 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000550}
551
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000552/// \brief Converts a Constant* into a GenericValue, including handling of
553/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000554GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000555 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000556 if (isa<UndefValue>(C)) {
557 GenericValue Result;
558 switch (C->getType()->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +0000559 default:
560 break;
Jay Foad5b370122010-01-15 08:32:58 +0000561 case Type::IntegerTyID:
562 case Type::X86_FP80TyID:
563 case Type::FP128TyID:
564 case Type::PPC_FP128TyID:
565 // Although the value is undefined, we still have to construct an APInt
566 // with the correct bit width.
567 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
568 break;
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000569 case Type::StructTyID: {
570 // if the whole struct is 'undef' just reserve memory for the value.
571 if(StructType *STy = dyn_cast<StructType>(C->getType())) {
572 unsigned int elemNum = STy->getNumElements();
573 Result.AggregateVal.resize(elemNum);
574 for (unsigned int i = 0; i < elemNum; ++i) {
575 Type *ElemTy = STy->getElementType(i);
576 if (ElemTy->isIntegerTy())
577 Result.AggregateVal[i].IntVal =
578 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
579 else if (ElemTy->isAggregateType()) {
580 const Constant *ElemUndef = UndefValue::get(ElemTy);
581 Result.AggregateVal[i] = getConstantValue(ElemUndef);
582 }
583 }
584 }
585 }
586 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000587 case Type::VectorTyID:
588 // if the whole vector is 'undef' just reserve memory for the value.
589 const VectorType* VTy = dyn_cast<VectorType>(C->getType());
590 const Type *ElemTy = VTy->getElementType();
591 unsigned int elemNum = VTy->getNumElements();
592 Result.AggregateVal.resize(elemNum);
593 if (ElemTy->isIntegerTy())
594 for (unsigned int i = 0; i < elemNum; ++i)
Elena Demikhovsky3c5ce292013-09-12 10:48:23 +0000595 Result.AggregateVal[i].IntVal =
Nadav Rotem953783e2013-04-01 15:53:30 +0000596 APInt(ElemTy->getPrimitiveSizeInBits(), 0);
Jay Foad5b370122010-01-15 08:32:58 +0000597 break;
598 }
599 return Result;
600 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000601
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000602 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000603 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000604 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000605 switch (CE->getOpcode()) {
606 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000607 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000608 GenericValue Result = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700609 APInt Offset(DL->getPointerSizeInBits(), 0);
610 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000611
Reid Spencer8fb0f192007-03-06 03:04:04 +0000612 char* tmp = (char*) Result.PointerVal;
Nuno Lopes98281a22012-12-30 16:25:48 +0000613 Result = PTOGV(tmp + Offset.getSExtValue());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000614 return Result;
615 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000616 case Instruction::Trunc: {
617 GenericValue GV = getConstantValue(Op0);
618 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
619 GV.IntVal = GV.IntVal.trunc(BitWidth);
620 return GV;
621 }
622 case Instruction::ZExt: {
623 GenericValue GV = getConstantValue(Op0);
624 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
625 GV.IntVal = GV.IntVal.zext(BitWidth);
626 return GV;
627 }
628 case Instruction::SExt: {
629 GenericValue GV = getConstantValue(Op0);
630 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
631 GV.IntVal = GV.IntVal.sext(BitWidth);
632 return GV;
633 }
634 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000635 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000636 GenericValue GV = getConstantValue(Op0);
637 GV.FloatVal = float(GV.DoubleVal);
638 return GV;
639 }
640 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000641 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000642 GenericValue GV = getConstantValue(Op0);
643 GV.DoubleVal = double(GV.FloatVal);
644 return GV;
645 }
646 case Instruction::UIToFP: {
647 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000648 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000649 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000650 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000651 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000652 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000653 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000654 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000655 false,
656 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000657 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000658 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000659 return GV;
660 }
661 case Instruction::SIToFP: {
662 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000663 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000664 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000665 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000666 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000667 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000668 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000669 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000670 true,
671 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000672 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000673 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000674 return GV;
675 }
676 case Instruction::FPToUI: // double->APInt conversion handles sign
677 case Instruction::FPToSI: {
678 GenericValue GV = getConstantValue(Op0);
679 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000680 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000681 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000682 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000683 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000684 else if (Op0->getType()->isX86_FP80Ty()) {
Tim Northover0a29cb02013-01-22 09:46:31 +0000685 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000686 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000687 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000688 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000689 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000690 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000691 GV.IntVal = v; // endian?
692 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000693 return GV;
694 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000695 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000696 GenericValue GV = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700697 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000698 assert(PtrWidth <= 64 && "Bad pointer width");
Reid Spencerbce30f12007-03-06 22:23:15 +0000699 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
Stephen Hines36b56882014-04-23 16:57:46 -0700700 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000701 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000702 return GV;
703 }
704 case Instruction::IntToPtr: {
705 GenericValue GV = getConstantValue(Op0);
Stephen Hines36b56882014-04-23 16:57:46 -0700706 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType());
Eli Friedmanbbc6e672012-10-30 22:21:55 +0000707 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
Reid Spencerbce30f12007-03-06 22:23:15 +0000708 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
709 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000710 return GV;
711 }
712 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000713 GenericValue GV = getConstantValue(Op0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000714 Type* DestTy = CE->getType();
Reid Spencerbce30f12007-03-06 22:23:15 +0000715 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000716 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000717 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000718 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000719 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000720 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000721 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000722 GV.DoubleVal = GV.IntVal.bitsToDouble();
723 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000724 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000725 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000726 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000727 break;
728 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000729 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000730 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000731 break;
732 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000733 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000734 break; // getConstantValue(Op0) above already converted it
735 }
736 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000737 }
Chris Lattner9a231222003-05-14 17:51:49 +0000738 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000739 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000740 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000741 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000742 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000743 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000744 case Instruction::UDiv:
745 case Instruction::SDiv:
746 case Instruction::URem:
747 case Instruction::SRem:
748 case Instruction::And:
749 case Instruction::Or:
750 case Instruction::Xor: {
751 GenericValue LHS = getConstantValue(Op0);
752 GenericValue RHS = getConstantValue(CE->getOperand(1));
753 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000754 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000755 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000756 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000757 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000758 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000759 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
760 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
761 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
762 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
763 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
764 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
765 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
766 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
767 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
768 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
769 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000770 break;
771 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000772 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000773 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000774 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000775 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000776 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000777 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000778 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000779 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000780 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000781 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000782 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000783 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000784 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000785 break;
786 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000787 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000788 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000789 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000790 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000791 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000792 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000793 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000794 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000795 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000796 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000797 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000798 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000799 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000800 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000801 case Type::X86_FP80TyID:
802 case Type::PPC_FP128TyID:
803 case Type::FP128TyID: {
Tim Northover0a29cb02013-01-22 09:46:31 +0000804 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics();
805 APFloat apfLHS = APFloat(Sem, LHS.IntVal);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000806 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000807 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000808 case Instruction::FAdd:
Tim Northover0a29cb02013-01-22 09:46:31 +0000809 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000810 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000811 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000812 case Instruction::FSub:
Tim Northover0a29cb02013-01-22 09:46:31 +0000813 apfLHS.subtract(APFloat(Sem, RHS.IntVal),
814 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000815 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000816 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000817 case Instruction::FMul:
Tim Northover0a29cb02013-01-22 09:46:31 +0000818 apfLHS.multiply(APFloat(Sem, RHS.IntVal),
819 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000820 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000821 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000822 case Instruction::FDiv:
Tim Northover0a29cb02013-01-22 09:46:31 +0000823 apfLHS.divide(APFloat(Sem, RHS.IntVal),
824 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000825 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000826 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000827 case Instruction::FRem:
Tim Northover0a29cb02013-01-22 09:46:31 +0000828 apfLHS.mod(APFloat(Sem, RHS.IntVal),
829 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000830 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000831 break;
832 }
833 }
834 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000835 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000836 return GV;
837 }
Chris Lattner9a231222003-05-14 17:51:49 +0000838 default:
839 break;
840 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000841
842 SmallString<256> Msg;
843 raw_svector_ostream OS(Msg);
844 OS << "ConstantExpr not handled: " << *CE;
845 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000846 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000847
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000848 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000849 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000850 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000851 case Type::FloatTyID:
852 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000853 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000854 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000855 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000856 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000857 case Type::X86_FP80TyID:
858 case Type::FP128TyID:
859 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000860 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000861 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000862 case Type::IntegerTyID:
863 Result.IntVal = cast<ConstantInt>(C)->getValue();
864 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000865 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000866 if (isa<ConstantPointerNull>(C))
Stephen Hinesdce4a402014-05-29 02:49:00 -0700867 Result.PointerVal = nullptr;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000868 else if (const Function *F = dyn_cast<Function>(C))
869 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000870 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000871 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000872 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
873 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
874 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000875 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000876 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000877 break;
Nadav Rotem953783e2013-04-01 15:53:30 +0000878 case Type::VectorTyID: {
879 unsigned elemNum;
880 Type* ElemTy;
881 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
882 const ConstantVector *CV = dyn_cast<ConstantVector>(C);
883 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C);
884
885 if (CDV) {
886 elemNum = CDV->getNumElements();
887 ElemTy = CDV->getElementType();
888 } else if (CV || CAZ) {
889 VectorType* VTy = dyn_cast<VectorType>(C->getType());
890 elemNum = VTy->getNumElements();
891 ElemTy = VTy->getElementType();
892 } else {
893 llvm_unreachable("Unknown constant vector type!");
894 }
895
896 Result.AggregateVal.resize(elemNum);
897 // Check if vector holds floats.
898 if(ElemTy->isFloatTy()) {
899 if (CAZ) {
900 GenericValue floatZero;
901 floatZero.FloatVal = 0.f;
902 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
903 floatZero);
904 break;
905 }
906 if(CV) {
907 for (unsigned i = 0; i < elemNum; ++i)
908 if (!isa<UndefValue>(CV->getOperand(i)))
909 Result.AggregateVal[i].FloatVal = cast<ConstantFP>(
910 CV->getOperand(i))->getValueAPF().convertToFloat();
911 break;
912 }
913 if(CDV)
914 for (unsigned i = 0; i < elemNum; ++i)
915 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i);
916
917 break;
918 }
919 // Check if vector holds doubles.
920 if (ElemTy->isDoubleTy()) {
921 if (CAZ) {
922 GenericValue doubleZero;
923 doubleZero.DoubleVal = 0.0;
924 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
925 doubleZero);
926 break;
927 }
928 if(CV) {
929 for (unsigned i = 0; i < elemNum; ++i)
930 if (!isa<UndefValue>(CV->getOperand(i)))
931 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>(
932 CV->getOperand(i))->getValueAPF().convertToDouble();
933 break;
934 }
935 if(CDV)
936 for (unsigned i = 0; i < elemNum; ++i)
937 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i);
938
939 break;
940 }
941 // Check if vector holds integers.
942 if (ElemTy->isIntegerTy()) {
943 if (CAZ) {
944 GenericValue intZero;
945 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull);
946 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(),
947 intZero);
948 break;
949 }
950 if(CV) {
951 for (unsigned i = 0; i < elemNum; ++i)
952 if (!isa<UndefValue>(CV->getOperand(i)))
953 Result.AggregateVal[i].IntVal = cast<ConstantInt>(
954 CV->getOperand(i))->getValue();
955 else {
956 Result.AggregateVal[i].IntVal =
957 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0);
958 }
959 break;
960 }
961 if(CDV)
962 for (unsigned i = 0; i < elemNum; ++i)
963 Result.AggregateVal[i].IntVal = APInt(
964 CDV->getElementType()->getPrimitiveSizeInBits(),
965 CDV->getElementAsInteger(i));
966
967 break;
968 }
969 llvm_unreachable("Unknown constant pointer type!");
970 }
971 break;
972
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000973 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000974 SmallString<256> Msg;
975 raw_svector_ostream OS(Msg);
976 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
977 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000978 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000979
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000980 return Result;
981}
982
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000983/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
984/// with the integer held in IntVal.
985static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
986 unsigned StoreBytes) {
987 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
Roman Divacky59324292012-09-05 22:26:57 +0000988 const uint8_t *Src = (const uint8_t *)IntVal.getRawData();
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000989
Rafael Espindola21a01d12013-04-15 14:44:24 +0000990 if (sys::IsLittleEndianHost) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000991 // Little-endian host - the source is ordered from LSB to MSB. Order the
992 // destination from LSB to MSB: Do a straight copy.
993 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000994 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000995 // Big-endian host - the source is an array of 64 bit words ordered from
996 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
997 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
998 while (StoreBytes > sizeof(uint64_t)) {
999 StoreBytes -= sizeof(uint64_t);
1000 // May not be aligned so use memcpy.
1001 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
1002 Src += sizeof(uint64_t);
1003 }
1004
1005 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
1006 }
1007}
1008
Evan Cheng89687e32008-11-04 06:10:31 +00001009void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001010 GenericValue *Ptr, Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001011 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001012
Reid Spencer8fb0f192007-03-06 03:04:04 +00001013 switch (Ty->getTypeID()) {
Nadav Rotem953783e2013-04-01 15:53:30 +00001014 default:
1015 dbgs() << "Cannot store value of type " << *Ty << "!\n";
1016 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001017 case Type::IntegerTyID:
1018 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001019 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001020 case Type::FloatTyID:
1021 *((float*)Ptr) = Val.FloatVal;
1022 break;
1023 case Type::DoubleTyID:
1024 *((double*)Ptr) = Val.DoubleVal;
1025 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001026 case Type::X86_FP80TyID:
1027 memcpy(Ptr, Val.IntVal.getRawData(), 10);
1028 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001029 case Type::PointerTyID:
1030 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
1031 if (StoreBytes != sizeof(PointerTy))
Chandler Carruth80d9e072011-04-28 08:37:18 +00001032 memset(&(Ptr->PointerVal), 0, StoreBytes);
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001033
Reid Spencer8fb0f192007-03-06 03:04:04 +00001034 *((PointerTy*)Ptr) = Val.PointerVal;
1035 break;
Nadav Rotem953783e2013-04-01 15:53:30 +00001036 case Type::VectorTyID:
1037 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) {
1038 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy())
1039 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal;
1040 if (cast<VectorType>(Ty)->getElementType()->isFloatTy())
1041 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal;
1042 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) {
1043 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8;
1044 StoreIntToMemory(Val.AggregateVal[i].IntVal,
1045 (uint8_t*)Ptr + numOfBytes*i, numOfBytes);
1046 }
1047 }
1048 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001049 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001050
Rafael Espindola21a01d12013-04-15 14:44:24 +00001051 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001052 // Host and target are different endian - reverse the stored bytes.
1053 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
1054}
1055
1056/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
1057/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
1058static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
1059 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
David Greenec2680be2013-01-14 21:04:45 +00001060 uint8_t *Dst = reinterpret_cast<uint8_t *>(
1061 const_cast<uint64_t *>(IntVal.getRawData()));
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001062
Rafael Espindola21a01d12013-04-15 14:44:24 +00001063 if (sys::IsLittleEndianHost)
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001064 // Little-endian host - the destination must be ordered from LSB to MSB.
1065 // The source is ordered from LSB to MSB: Do a straight copy.
1066 memcpy(Dst, Src, LoadBytes);
1067 else {
1068 // Big-endian - the destination is an array of 64 bit words ordered from
1069 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
1070 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
1071 // a word.
1072 while (LoadBytes > sizeof(uint64_t)) {
1073 LoadBytes -= sizeof(uint64_t);
1074 // May not be aligned so use memcpy.
1075 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
1076 Dst += sizeof(uint64_t);
1077 }
1078
1079 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
1080 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001081}
1082
Misha Brukman4afac182003-10-10 17:45:12 +00001083/// FIXME: document
1084///
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001085void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +00001086 GenericValue *Ptr,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001087 Type *Ty) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001088 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +00001089
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001090 switch (Ty->getTypeID()) {
1091 case Type::IntegerTyID:
1092 // An APInt with all words initially zero.
1093 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
1094 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
1095 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +00001096 case Type::FloatTyID:
1097 Result.FloatVal = *((float*)Ptr);
1098 break;
1099 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001100 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +00001101 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +00001102 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +00001103 Result.PointerVal = *((PointerTy*)Ptr);
1104 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001105 case Type::X86_FP80TyID: {
1106 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +00001107 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +00001108 uint64_t y[2];
1109 memcpy(y, Ptr, 10);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00001110 Result.IntVal = APInt(80, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +00001111 break;
1112 }
Nadav Rotem953783e2013-04-01 15:53:30 +00001113 case Type::VectorTyID: {
1114 const VectorType *VT = cast<VectorType>(Ty);
1115 const Type *ElemT = VT->getElementType();
1116 const unsigned numElems = VT->getNumElements();
1117 if (ElemT->isFloatTy()) {
1118 Result.AggregateVal.resize(numElems);
1119 for (unsigned i = 0; i < numElems; ++i)
1120 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i);
1121 }
1122 if (ElemT->isDoubleTy()) {
1123 Result.AggregateVal.resize(numElems);
1124 for (unsigned i = 0; i < numElems; ++i)
1125 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i);
1126 }
1127 if (ElemT->isIntegerTy()) {
1128 GenericValue intZero;
1129 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth();
1130 intZero.IntVal = APInt(elemBitWidth, 0);
1131 Result.AggregateVal.resize(numElems, intZero);
1132 for (unsigned i = 0; i < numElems; ++i)
1133 LoadIntFromMemory(Result.AggregateVal[i].IntVal,
1134 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8);
1135 }
1136 break;
1137 }
Reid Spencer8fb0f192007-03-06 03:04:04 +00001138 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001139 SmallString<256> Msg;
1140 raw_svector_ostream OS(Msg);
1141 OS << "Cannot load value of type " << *Ty << "!";
1142 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001143 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +00001144}
1145
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001146void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +00001147 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +00001148 DEBUG(Init->dump());
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001149 if (isa<UndefValue>(Init))
Chris Lattnerbd1d3822004-10-16 18:19:26 +00001150 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001151
1152 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001153 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001154 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +00001155 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1156 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
1157 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001158 }
1159
1160 if (isa<ConstantAggregateZero>(Init)) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001161 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +00001162 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001163 }
1164
1165 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001166 unsigned ElementSize =
Micah Villmow3574eca2012-10-08 16:38:25 +00001167 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +00001168 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
1169 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
1170 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001171 }
1172
1173 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
Dan Gohman638e3782008-05-20 03:20:09 +00001174 const StructLayout *SL =
Micah Villmow3574eca2012-10-08 16:38:25 +00001175 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType()));
Dan Gohman638e3782008-05-20 03:20:09 +00001176 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
1177 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
1178 return;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001179 }
1180
1181 if (const ConstantDataSequential *CDS =
1182 dyn_cast<ConstantDataSequential>(Init)) {
1183 // CDS is already laid out in host memory order.
1184 StringRef Data = CDS->getRawDataValues();
1185 memcpy(Addr, Data.data(), Data.size());
1186 return;
1187 }
1188
1189 if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001190 GenericValue Val = getConstantValue(Init);
1191 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
1192 return;
1193 }
1194
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001195 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +00001196 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001197}
1198
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001199/// EmitGlobals - Emit all of the global variables to memory, storing their
1200/// addresses into GlobalAddress. This must make sure to copy the contents of
1201/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001202void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001203 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +00001204 // to hold them. If there is more than one module, do a prepass over globals
1205 // to figure out how the different modules should link together.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001206 std::map<std::pair<std::string, Type*>,
Chris Lattnerfe854032006-08-16 01:24:12 +00001207 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001208
Chris Lattnerfe854032006-08-16 01:24:12 +00001209 if (Modules.size() != 1) {
1210 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001211 Module &M = *Modules[m];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001212 for (const auto &GV : M.globals()) {
1213 if (GV.hasLocalLinkage() || GV.isDeclaration() ||
1214 GV.hasAppendingLinkage() || !GV.hasName())
Chris Lattnerfe854032006-08-16 01:24:12 +00001215 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001216
1217 const GlobalValue *&GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001218 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())];
Chris Lattnerfe854032006-08-16 01:24:12 +00001219
1220 // If this is the first time we've seen this global, it is the canonical
1221 // version.
1222 if (!GVEntry) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001223 GVEntry = &GV;
Chris Lattnerfe854032006-08-16 01:24:12 +00001224 continue;
1225 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001226
Chris Lattnerfe854032006-08-16 01:24:12 +00001227 // If the existing global is strong, never replace it.
Stephen Hines36b56882014-04-23 16:57:46 -07001228 if (GVEntry->hasExternalLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001229 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001230
Chris Lattnerfe854032006-08-16 01:24:12 +00001231 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001232 // symbol. FIXME is this right for common?
Stephen Hinesdce4a402014-05-29 02:49:00 -07001233 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
1234 GVEntry = &GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001235 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001236 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001237 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001238
Chris Lattnerfe854032006-08-16 01:24:12 +00001239 std::vector<const GlobalValue*> NonCanonicalGlobals;
1240 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001241 Module &M = *Modules[m];
Stephen Hinesdce4a402014-05-29 02:49:00 -07001242 for (const auto &GV : M.globals()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001243 // In the multi-module case, see what this global maps to.
1244 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001245 if (const GlobalValue *GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001246 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001247 // If something else is the canonical global, ignore this one.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001248 if (GVEntry != &GV) {
1249 NonCanonicalGlobals.push_back(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001250 continue;
1251 }
1252 }
1253 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001254
Stephen Hinesdce4a402014-05-29 02:49:00 -07001255 if (!GV.isDeclaration()) {
1256 addGlobalMapping(&GV, getMemoryForGV(&GV));
Chris Lattnerfe854032006-08-16 01:24:12 +00001257 } else {
1258 // External variable reference. Try to use the dynamic loader to
1259 // get a pointer to it.
1260 if (void *SymAddr =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001261 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName()))
1262 addGlobalMapping(&GV, SymAddr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001263 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001264 report_fatal_error("Could not resolve external global address: "
Stephen Hinesdce4a402014-05-29 02:49:00 -07001265 +GV.getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001266 }
1267 }
1268 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001269
Chris Lattnerfe854032006-08-16 01:24:12 +00001270 // If there are multiple modules, map the non-canonical globals to their
1271 // canonical location.
1272 if (!NonCanonicalGlobals.empty()) {
1273 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1274 const GlobalValue *GV = NonCanonicalGlobals[i];
1275 const GlobalValue *CGV =
1276 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1277 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1278 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001279 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001280 }
1281 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001282
1283 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001284 // and initialize their contents.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001285 for (const auto &GV : M.globals()) {
1286 if (!GV.isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001287 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001288 if (const GlobalValue *GVEntry =
Stephen Hinesdce4a402014-05-29 02:49:00 -07001289 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())])
1290 if (GVEntry != &GV) // Not the canonical variable.
Chris Lattnerfe854032006-08-16 01:24:12 +00001291 continue;
1292 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001293 EmitGlobalVariable(&GV);
Chris Lattnerfe854032006-08-16 01:24:12 +00001294 }
1295 }
1296 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001297}
1298
1299// EmitGlobalVariable - This method emits the specified global variable to the
1300// address specified in GlobalAddresses, or allocates new memory if it's not
1301// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001302void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001303 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001304
Stephen Hinesdce4a402014-05-29 02:49:00 -07001305 if (!GA) {
Chris Lattner24b0a182003-12-20 02:45:37 +00001306 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001307 GA = getMemoryForGV(GV);
Andrew Kaylor48079e02013-11-15 17:52:54 +00001308
1309 // If we failed to allocate memory for this global, return.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001310 if (!GA) return;
Andrew Kaylor48079e02013-11-15 17:52:54 +00001311
Chris Lattner55d86482003-12-31 20:21:04 +00001312 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001313 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001314
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001315 // Don't initialize if it's thread local, let the client do it.
1316 if (!GV->isThreadLocal())
1317 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001318
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001319 Type *ElTy = GV->getType()->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00001320 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001321 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001322 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001323}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001324
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001325ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1326 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001327}
1328
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001329sys::Mutex *
1330ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001331 return &EES->EE.lock;
1332}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001333
1334void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1335 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001336 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1337 EES->GlobalAddressReverseMap.erase(OldVal);
1338}
1339
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001340void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1341 const GlobalValue *,
1342 const GlobalValue *) {
Craig Topper85814382012-02-07 05:05:23 +00001343 llvm_unreachable("The ExecutionEngine doesn't know how to handle a"
1344 " RAUW on a value it has a global mapping for.");
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001345}