blob: fc5cb926e3b24d9f97181789b136451efbb38f11 [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
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/Module.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Daniel Dunbar48dd8752010-11-13 02:48:57 +000022#include "llvm/ADT/SmallString.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000023#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Torok Edwin31e24662009-07-07 17:32:34 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000026#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000027#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/raw_ostream.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000029#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000030#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000031#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000032#include <cmath>
33#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000034using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner36343732006-12-19 22:43:32 +000036STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
37STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000038
Jeffrey Yasskin46882612010-02-05 16:19:36 +000039ExecutionEngine *(*ExecutionEngine::JITCtor)(
40 Module *M,
41 std::string *ErrorStr,
42 JITMemoryManager *JMM,
43 CodeGenOpt::Level OptLevel,
44 bool GVsWithCode,
45 CodeModel::Model CMM,
46 StringRef MArch,
47 StringRef MCPU,
48 const SmallVectorImpl<std::string>& MAttrs) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000049ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000050 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000051
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000052ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000053 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000054 LazyFunctionCreator(0),
Daniel Dunbar48dd8752010-11-13 02:48:57 +000055 ExceptionTableRegister(0),
Duncan Sandsb35fd442010-10-21 08:57:29 +000056 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000057 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000058 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000059 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000060 Modules.push_back(M);
61 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000062}
63
Brian Gaeke8e539482003-09-04 22:57:27 +000064ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000065 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000066 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
67 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000068}
69
Duncan Sandsb35fd442010-10-21 08:57:29 +000070void ExecutionEngine::DeregisterAllTables() {
71 if (ExceptionTableDeregister) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000072 for (std::vector<void*>::iterator it = AllExceptionTables.begin(),
73 ie = AllExceptionTables.end(); it != ie; ++it)
Duncan Sandsb35fd442010-10-21 08:57:29 +000074 ExceptionTableDeregister(*it);
75 AllExceptionTables.clear();
76 }
77}
78
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000079namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000080/// \brief Helper class which uses a value handler to automatically deletes the
81/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000082class GVMemoryBlock : public CallbackVH {
83 GVMemoryBlock(const GlobalVariable *GV)
84 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
85
86public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000087 /// \brief Returns the address the GlobalVariable should be written into. The
88 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000089 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
90 const Type *ElTy = GV->getType()->getElementType();
91 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
92 void *RawMemory = ::operator new(
93 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
94 TD.getPreferredAlignment(GV))
95 + GVSize);
96 new(RawMemory) GVMemoryBlock(GV);
97 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
98 }
99
100 virtual void deleted() {
101 // We allocated with operator new and with some extra memory hanging off the
102 // end, so don't just delete this. I'm not sure if this is actually
103 // required.
104 this->~GVMemoryBlock();
105 ::operator delete(this);
106 }
107};
108} // anonymous namespace
109
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000110char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000111 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000112}
113
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000114bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000115 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000116 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000117 Module *Found = *I;
118 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000119 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000120 clearGlobalMappingsFromModule(M);
121 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000122 }
123 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000124 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000125}
126
Chris Lattnerfe854032006-08-16 01:24:12 +0000127Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
128 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000129 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000130 return F;
131 }
132 return 0;
133}
134
135
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000136void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
137 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000138 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000139 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000140
141 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
142 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000143 if (I == GlobalAddressMap.end())
144 OldVal = 0;
145 else {
146 OldVal = I->second;
147 GlobalAddressMap.erase(I);
148 }
149
150 GlobalAddressReverseMap.erase(OldVal);
151 return OldVal;
152}
153
Chris Lattnere7fd5532006-05-08 22:00:52 +0000154void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
155 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000156
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000157 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000158 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000159 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000160 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
161 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000162
163 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000164 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000165 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000166 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000167 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
168 V = GV;
169 }
170}
171
Chris Lattnere7fd5532006-05-08 22:00:52 +0000172void ExecutionEngine::clearAllGlobalMappings() {
173 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000174
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000175 EEState.getGlobalAddressMap(locked).clear();
176 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000177}
178
Nate Begemanf049e072008-05-21 16:34:48 +0000179void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
180 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000181
182 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000183 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000184 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
185 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000186 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000187}
188
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000189void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000190 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000191
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000192 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000193 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000194
Chris Lattnere7fd5532006-05-08 22:00:52 +0000195 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000196 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000197 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000198
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000199 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000200 void *OldVal = CurVal;
201
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000202 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
203 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000204 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000205
206 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000207 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000208 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000209 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000210 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
211 V = GV;
212 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000213 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000214}
215
Chris Lattnere7fd5532006-05-08 22:00:52 +0000216void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
217 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000218
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000219 ExecutionEngineState::GlobalAddressMapTy::iterator I =
220 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000221 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000222}
223
Chris Lattner55d86482003-12-31 20:21:04 +0000224const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000225 MutexGuard locked(lock);
226
Chris Lattner55d86482003-12-31 20:21:04 +0000227 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000228 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000229 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000230 I = EEState.getGlobalAddressMap(locked).begin(),
231 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000232 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
233 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000234 }
235
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000236 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000237 EEState.getGlobalAddressReverseMap(locked).find(Addr);
238 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000239}
Chris Lattner87f03102003-12-26 06:50:30 +0000240
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000241namespace {
242class ArgvArray {
243 char *Array;
244 std::vector<char*> Values;
245public:
246 ArgvArray() : Array(NULL) {}
247 ~ArgvArray() { clear(); }
248 void clear() {
249 delete[] Array;
250 Array = NULL;
251 for (size_t I = 0, E = Values.size(); I != E; ++I) {
252 delete[] Values[I];
253 }
254 Values.clear();
255 }
256 /// Turn a vector of strings into a nice argv style array of pointers to null
257 /// terminated strings.
258 void *reset(LLVMContext &C, ExecutionEngine *EE,
259 const std::vector<std::string> &InputArgv);
260};
261} // anonymous namespace
262void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
263 const std::vector<std::string> &InputArgv) {
264 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000265 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000266 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000267
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000268 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000269 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000270
271 for (unsigned i = 0; i != InputArgv.size(); ++i) {
272 unsigned Size = InputArgv[i].size()+1;
273 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000274 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000275 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000276
Chris Lattner87f03102003-12-26 06:50:30 +0000277 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
278 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000279
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000280 // Endian safe: Array[i] = (PointerTy)Dest;
281 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000282 SBytePtr);
283 }
284
285 // Null terminate it
286 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000287 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000288 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000289 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000290}
291
Chris Lattnerfbd39762009-09-23 01:46:04 +0000292void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
293 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000294 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000295 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000296
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000297 // If this global has internal linkage, or if it has a use, then it must be
298 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
299 // this is the case, don't execute any of the global ctors, __main will do
300 // it.
301 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
302
303 // Should be an array of '{ int, void ()* }' structs. The first value is
304 // the init priority, which we ignore.
305 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
306 if (!InitList) return;
307 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
308 ConstantStruct *CS =
309 dyn_cast<ConstantStruct>(InitList->getOperand(i));
310 if (!CS) continue;
311 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
312
313 Constant *FP = CS->getOperand(1);
314 if (FP->isNullValue())
315 break; // Found a null terminator, exit.
316
317 // Strip off constant expression casts.
318 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
319 if (CE->isCast())
320 FP = CE->getOperand(0);
321
322 // Execute the ctor/dtor function!
323 if (Function *F = dyn_cast<Function>(FP))
324 runFunction(F, std::vector<GenericValue>());
325
326 // FIXME: It is marginally lame that we just do nothing here if we see an
327 // entry we don't recognize. It might not be unreasonable for the verifier
328 // to not even allow this and just assert here.
329 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000330}
331
Evan Cheng18314dc2008-09-30 15:51:21 +0000332void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
333 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000334 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
335 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000336}
337
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000338#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000339/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
340static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
341 unsigned PtrSize = EE->getTargetData()->getPointerSize();
342 for (unsigned i = 0; i < PtrSize; ++i)
343 if (*(i + (uint8_t*)Loc))
344 return false;
345 return true;
346}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000347#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000348
Chris Lattner87f03102003-12-26 06:50:30 +0000349int ExecutionEngine::runFunctionAsMain(Function *Fn,
350 const std::vector<std::string> &argv,
351 const char * const * envp) {
352 std::vector<GenericValue> GVArgs;
353 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000354 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000355
356 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000357 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000358 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000359 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000360
361 // Check the argument types.
362 if (NumArgs > 3)
363 report_fatal_error("Invalid number of arguments of main() supplied");
364 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
365 report_fatal_error("Invalid type for third argument of main() supplied");
366 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
367 report_fatal_error("Invalid type for second argument of main() supplied");
368 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
369 report_fatal_error("Invalid type for first argument of main() supplied");
370 if (!FTy->getReturnType()->isIntegerTy() &&
371 !FTy->getReturnType()->isVoidTy())
372 report_fatal_error("Invalid return type of main() supplied");
373
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000374 ArgvArray CArgv;
375 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000376 if (NumArgs) {
377 GVArgs.push_back(GVArgc); // Arg #0 = argc.
378 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000379 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000380 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000381 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000382 "argv[0] was null after CreateArgv");
383 if (NumArgs > 2) {
384 std::vector<std::string> EnvVars;
385 for (unsigned i = 0; envp[i]; ++i)
386 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000387 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000388 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000389 }
390 }
391 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000392
Reid Spencer8fb0f192007-03-06 03:04:04 +0000393 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000394}
395
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000396ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000397 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000398 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000399 CodeGenOpt::Level OptLevel,
400 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000401 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000402 .setEngineKind(ForceInterpreter
403 ? EngineKind::Interpreter
404 : EngineKind::JIT)
405 .setErrorStr(ErrorStr)
406 .setOptLevel(OptLevel)
407 .setAllocateGVsWithCode(GVsWithCode)
408 .create();
409}
Brian Gaeke82d82772003-09-03 20:34:19 +0000410
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000411ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000412 // Make sure we can resolve symbols in the program as well. The zero arg
413 // to the function tells DynamicLibrary to load the program, not a library.
414 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
415 return 0;
416
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000417 // If the user specified a memory manager but didn't specify which engine to
418 // create, we assume they only want the JIT, and we fail if they only want
419 // the interpreter.
420 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000421 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000422 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000423 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000424 if (ErrorStr)
425 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000426 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000427 }
428 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000429
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000430 // Unless the interpreter was explicitly selected or the JIT is not linked,
431 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000432 if (WhichEngine & EngineKind::JIT) {
433 if (ExecutionEngine::JITCtor) {
434 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000435 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000436 AllocateGVsWithCode, CMModel,
437 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000438 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000439 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000440 }
441
442 // If we can't make a JIT and we didn't request one specifically, try making
443 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000444 if (WhichEngine & EngineKind::Interpreter) {
445 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000446 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000447 if (ErrorStr)
448 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000449 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000450 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000451
452 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
453 if (ErrorStr)
454 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000455 }
456
Chris Lattnerfbd39762009-09-23 01:46:04 +0000457 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000458}
459
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000460void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000461 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000462 return getPointerToFunction(F);
463
Reid Spenceree448632005-07-12 15:51:55 +0000464 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000465 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
466 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000467
468 // Global variable might have been added since interpreter started.
469 if (GlobalVariable *GVar =
470 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
471 EmitGlobalVariable(GVar);
472 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000473 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000474
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000475 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000476}
477
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000478/// \brief Converts a Constant* into a GenericValue, including handling of
479/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000480GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000481 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000482 if (isa<UndefValue>(C)) {
483 GenericValue Result;
484 switch (C->getType()->getTypeID()) {
485 case Type::IntegerTyID:
486 case Type::X86_FP80TyID:
487 case Type::FP128TyID:
488 case Type::PPC_FP128TyID:
489 // Although the value is undefined, we still have to construct an APInt
490 // with the correct bit width.
491 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
492 break;
493 default:
494 break;
495 }
496 return Result;
497 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000498
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000499 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000500 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000501 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000502 switch (CE->getOpcode()) {
503 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000504 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000505 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000506 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000507 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000508 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000509
Reid Spencer8fb0f192007-03-06 03:04:04 +0000510 char* tmp = (char*) Result.PointerVal;
511 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000512 return Result;
513 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000514 case Instruction::Trunc: {
515 GenericValue GV = getConstantValue(Op0);
516 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
517 GV.IntVal = GV.IntVal.trunc(BitWidth);
518 return GV;
519 }
520 case Instruction::ZExt: {
521 GenericValue GV = getConstantValue(Op0);
522 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
523 GV.IntVal = GV.IntVal.zext(BitWidth);
524 return GV;
525 }
526 case Instruction::SExt: {
527 GenericValue GV = getConstantValue(Op0);
528 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
529 GV.IntVal = GV.IntVal.sext(BitWidth);
530 return GV;
531 }
532 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000533 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000534 GenericValue GV = getConstantValue(Op0);
535 GV.FloatVal = float(GV.DoubleVal);
536 return GV;
537 }
538 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000539 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000540 GenericValue GV = getConstantValue(Op0);
541 GV.DoubleVal = double(GV.FloatVal);
542 return GV;
543 }
544 case Instruction::UIToFP: {
545 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000546 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000547 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000548 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000549 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000550 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000551 const uint64_t zero[] = {0, 0};
552 APFloat apf = APFloat(APInt(80, 2, zero));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000553 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000554 false,
555 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000556 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000557 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000558 return GV;
559 }
560 case Instruction::SIToFP: {
561 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000562 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000563 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000564 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000565 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000566 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000567 const uint64_t zero[] = { 0, 0};
568 APFloat apf = APFloat(APInt(80, 2, zero));
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000569 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000570 true,
571 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000572 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000573 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000574 return GV;
575 }
576 case Instruction::FPToUI: // double->APInt conversion handles sign
577 case Instruction::FPToSI: {
578 GenericValue GV = getConstantValue(Op0);
579 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000580 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000581 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000582 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000583 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000584 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000585 APFloat apf = APFloat(GV.IntVal);
586 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000587 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000588 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000589 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000590 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000591 GV.IntVal = v; // endian?
592 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000593 return GV;
594 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000595 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000596 GenericValue GV = getConstantValue(Op0);
597 uint32_t PtrWidth = TD->getPointerSizeInBits();
598 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
599 return GV;
600 }
601 case Instruction::IntToPtr: {
602 GenericValue GV = getConstantValue(Op0);
603 uint32_t PtrWidth = TD->getPointerSizeInBits();
604 if (PtrWidth != GV.IntVal.getBitWidth())
605 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
606 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
607 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000608 return GV;
609 }
610 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000611 GenericValue GV = getConstantValue(Op0);
612 const Type* DestTy = CE->getType();
613 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000614 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000615 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000616 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000617 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000618 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000619 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000620 GV.DoubleVal = GV.IntVal.bitsToDouble();
621 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000622 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000623 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000624 GV.IntVal.floatToBits(GV.FloatVal);
625 break;
626 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000627 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000628 GV.IntVal.doubleToBits(GV.DoubleVal);
629 break;
630 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000631 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000632 break; // getConstantValue(Op0) above already converted it
633 }
634 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000635 }
Chris Lattner9a231222003-05-14 17:51:49 +0000636 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000637 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000638 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000639 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000640 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000641 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000642 case Instruction::UDiv:
643 case Instruction::SDiv:
644 case Instruction::URem:
645 case Instruction::SRem:
646 case Instruction::And:
647 case Instruction::Or:
648 case Instruction::Xor: {
649 GenericValue LHS = getConstantValue(Op0);
650 GenericValue RHS = getConstantValue(CE->getOperand(1));
651 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000652 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000653 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000654 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000655 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000656 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000657 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
658 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
659 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
660 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
661 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
662 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
663 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
664 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
665 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
666 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
667 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000668 break;
669 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000670 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000671 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000672 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000673 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000674 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000675 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000676 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000677 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000678 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000679 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000680 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000681 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000682 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000683 break;
684 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000685 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000686 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000687 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000688 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000689 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000690 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000691 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000692 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000693 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000694 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000695 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000696 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000697 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000698 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000699 case Type::X86_FP80TyID:
700 case Type::PPC_FP128TyID:
701 case Type::FP128TyID: {
702 APFloat apfLHS = APFloat(LHS.IntVal);
703 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000704 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000705 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000706 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000707 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000708 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000709 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000710 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000711 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000712 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000713 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000714 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000715 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000716 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000717 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000718 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000719 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000720 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000721 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000722 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000723 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000724 break;
725 }
726 }
727 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000728 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000729 return GV;
730 }
Chris Lattner9a231222003-05-14 17:51:49 +0000731 default:
732 break;
733 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000734
735 SmallString<256> Msg;
736 raw_svector_ostream OS(Msg);
737 OS << "ConstantExpr not handled: " << *CE;
738 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000739 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000740
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000741 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000742 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000743 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000744 case Type::FloatTyID:
745 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000746 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000747 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000748 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000749 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000750 case Type::X86_FP80TyID:
751 case Type::FP128TyID:
752 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000753 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000754 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000755 case Type::IntegerTyID:
756 Result.IntVal = cast<ConstantInt>(C)->getValue();
757 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000758 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000759 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000760 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000761 else if (const Function *F = dyn_cast<Function>(C))
762 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000763 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000764 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000765 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
766 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
767 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000768 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000769 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000770 break;
771 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000772 SmallString<256> Msg;
773 raw_svector_ostream OS(Msg);
774 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
775 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000776 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000777
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000778 return Result;
779}
780
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000781/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
782/// with the integer held in IntVal.
783static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
784 unsigned StoreBytes) {
785 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
786 uint8_t *Src = (uint8_t *)IntVal.getRawData();
787
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000788 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000789 // Little-endian host - the source is ordered from LSB to MSB. Order the
790 // destination from LSB to MSB: Do a straight copy.
791 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000792 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000793 // Big-endian host - the source is an array of 64 bit words ordered from
794 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
795 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
796 while (StoreBytes > sizeof(uint64_t)) {
797 StoreBytes -= sizeof(uint64_t);
798 // May not be aligned so use memcpy.
799 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
800 Src += sizeof(uint64_t);
801 }
802
803 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
804 }
805}
806
Evan Cheng89687e32008-11-04 06:10:31 +0000807void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
808 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000809 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
810
Reid Spencer8fb0f192007-03-06 03:04:04 +0000811 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000812 case Type::IntegerTyID:
813 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000814 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000815 case Type::FloatTyID:
816 *((float*)Ptr) = Val.FloatVal;
817 break;
818 case Type::DoubleTyID:
819 *((double*)Ptr) = Val.DoubleVal;
820 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000821 case Type::X86_FP80TyID:
822 memcpy(Ptr, Val.IntVal.getRawData(), 10);
823 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000824 case Type::PointerTyID:
825 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
826 if (StoreBytes != sizeof(PointerTy))
827 memset(Ptr, 0, StoreBytes);
828
Reid Spencer8fb0f192007-03-06 03:04:04 +0000829 *((PointerTy*)Ptr) = Val.PointerVal;
830 break;
831 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000832 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000833 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000834
Chris Lattnerb67c9582009-01-22 19:53:00 +0000835 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000836 // Host and target are different endian - reverse the stored bytes.
837 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
838}
839
840/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
841/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
842static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
843 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
844 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
845
Chris Lattnerb67c9582009-01-22 19:53:00 +0000846 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000847 // Little-endian host - the destination must be ordered from LSB to MSB.
848 // The source is ordered from LSB to MSB: Do a straight copy.
849 memcpy(Dst, Src, LoadBytes);
850 else {
851 // Big-endian - the destination is an array of 64 bit words ordered from
852 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
853 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
854 // a word.
855 while (LoadBytes > sizeof(uint64_t)) {
856 LoadBytes -= sizeof(uint64_t);
857 // May not be aligned so use memcpy.
858 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
859 Dst += sizeof(uint64_t);
860 }
861
862 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
863 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000864}
865
Misha Brukman4afac182003-10-10 17:45:12 +0000866/// FIXME: document
867///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000868void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000869 GenericValue *Ptr,
870 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000871 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000872
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000873 switch (Ty->getTypeID()) {
874 case Type::IntegerTyID:
875 // An APInt with all words initially zero.
876 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
877 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
878 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000879 case Type::FloatTyID:
880 Result.FloatVal = *((float*)Ptr);
881 break;
882 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000883 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000884 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000885 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000886 Result.PointerVal = *((PointerTy*)Ptr);
887 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000888 case Type::X86_FP80TyID: {
889 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000890 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000891 uint64_t y[2];
892 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000893 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000894 break;
895 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000896 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000897 SmallString<256> Msg;
898 raw_svector_ostream OS(Msg);
899 OS << "Cannot load value of type " << *Ty << "!";
900 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000901 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000902}
903
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000904void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000905 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000906 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000907 if (isa<UndefValue>(Init)) {
908 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000909 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000910 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000911 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000912 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
913 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
914 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000915 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000916 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000917 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000918 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
919 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000920 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000921 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
922 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
923 return;
924 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
925 const StructLayout *SL =
926 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
927 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
928 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
929 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000930 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000931 GenericValue Val = getConstantValue(Init);
932 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
933 return;
934 }
935
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000936 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +0000937 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000938}
939
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000940/// EmitGlobals - Emit all of the global variables to memory, storing their
941/// addresses into GlobalAddress. This must make sure to copy the contents of
942/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000943void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000944 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000945 // to hold them. If there is more than one module, do a prepass over globals
946 // to figure out how the different modules should link together.
Chris Lattnerfe854032006-08-16 01:24:12 +0000947 std::map<std::pair<std::string, const Type*>,
948 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000949
Chris Lattnerfe854032006-08-16 01:24:12 +0000950 if (Modules.size() != 1) {
951 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000952 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000953 for (Module::const_global_iterator I = M.global_begin(),
954 E = M.global_end(); I != E; ++I) {
955 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000956 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000957 GV->hasAppendingLinkage() || !GV->hasName())
958 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000959
960 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +0000961 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
962
963 // If this is the first time we've seen this global, it is the canonical
964 // version.
965 if (!GVEntry) {
966 GVEntry = GV;
967 continue;
968 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000969
Chris Lattnerfe854032006-08-16 01:24:12 +0000970 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000971 if (GVEntry->hasExternalLinkage() ||
972 GVEntry->hasDLLImportLinkage() ||
973 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000974 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000975
Chris Lattnerfe854032006-08-16 01:24:12 +0000976 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000977 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000978 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000979 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000980 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000981 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000982 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000983
Chris Lattnerfe854032006-08-16 01:24:12 +0000984 std::vector<const GlobalValue*> NonCanonicalGlobals;
985 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000986 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000987 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
988 I != E; ++I) {
989 // In the multi-module case, see what this global maps to.
990 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000991 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +0000992 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
993 // If something else is the canonical global, ignore this one.
994 if (GVEntry != &*I) {
995 NonCanonicalGlobals.push_back(I);
996 continue;
997 }
998 }
999 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001000
Reid Spencer5cbf9852007-01-30 20:08:39 +00001001 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001002 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001003 } else {
1004 // External variable reference. Try to use the dynamic loader to
1005 // get a pointer to it.
1006 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001007 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001008 addGlobalMapping(I, SymAddr);
1009 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001010 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001011 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001012 }
1013 }
1014 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001015
Chris Lattnerfe854032006-08-16 01:24:12 +00001016 // If there are multiple modules, map the non-canonical globals to their
1017 // canonical location.
1018 if (!NonCanonicalGlobals.empty()) {
1019 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1020 const GlobalValue *GV = NonCanonicalGlobals[i];
1021 const GlobalValue *CGV =
1022 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1023 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1024 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001025 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001026 }
1027 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001028
1029 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001030 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001031 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1032 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001033 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001034 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001035 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001036 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1037 if (GVEntry != &*I) // Not the canonical variable.
1038 continue;
1039 }
1040 EmitGlobalVariable(I);
1041 }
1042 }
1043 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001044}
1045
1046// EmitGlobalVariable - This method emits the specified global variable to the
1047// address specified in GlobalAddresses, or allocates new memory if it's not
1048// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001049void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001050 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001051
Chris Lattner24b0a182003-12-20 02:45:37 +00001052 if (GA == 0) {
1053 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001054 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001055 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001056 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001057
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001058 // Don't initialize if it's thread local, let the client do it.
1059 if (!GV->isThreadLocal())
1060 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001061
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001062 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001063 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001064 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001065 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001066}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001067
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001068ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1069 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001070}
1071
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001072sys::Mutex *
1073ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001074 return &EES->EE.lock;
1075}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001076
1077void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1078 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001079 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1080 EES->GlobalAddressReverseMap.erase(OldVal);
1081}
1082
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001083void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1084 const GlobalValue *,
1085 const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001086 assert(false && "The ExecutionEngine doesn't know how to handle a"
1087 " RAUW on a value it has a global mapping for.");
1088}