blob: f28697530b3d1f66d5439fc647998db6a2301ee4 [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"
Michael J. Spencer1f6efa32010-11-29 18:16:10 +000029#include "llvm/Support/DynamicLibrary.h"
30#include "llvm/Support/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;
Daniel Dunbar6d135972010-11-17 16:06:37 +000049ExecutionEngine *(*ExecutionEngine::MCJITCtor)(
50 Module *M,
51 std::string *ErrorStr,
52 JITMemoryManager *JMM,
53 CodeGenOpt::Level OptLevel,
54 bool GVsWithCode,
55 CodeModel::Model CMM,
56 StringRef MArch,
57 StringRef MCPU,
58 const SmallVectorImpl<std::string>& MAttrs) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000059ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000060 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000061
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000062ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000063 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000064 LazyFunctionCreator(0),
Daniel Dunbar48dd8752010-11-13 02:48:57 +000065 ExceptionTableRegister(0),
Duncan Sandsb35fd442010-10-21 08:57:29 +000066 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000067 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000068 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000069 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000070 Modules.push_back(M);
71 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000072}
73
Brian Gaeke8e539482003-09-04 22:57:27 +000074ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000075 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000076 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
77 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000078}
79
Duncan Sandsb35fd442010-10-21 08:57:29 +000080void ExecutionEngine::DeregisterAllTables() {
81 if (ExceptionTableDeregister) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000082 for (std::vector<void*>::iterator it = AllExceptionTables.begin(),
83 ie = AllExceptionTables.end(); it != ie; ++it)
Duncan Sandsb35fd442010-10-21 08:57:29 +000084 ExceptionTableDeregister(*it);
85 AllExceptionTables.clear();
86 }
87}
88
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000089namespace {
Daniel Dunbar48dd8752010-11-13 02:48:57 +000090/// \brief Helper class which uses a value handler to automatically deletes the
91/// memory block when the GlobalVariable is destroyed.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000092class GVMemoryBlock : public CallbackVH {
93 GVMemoryBlock(const GlobalVariable *GV)
94 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
95
96public:
Daniel Dunbar48dd8752010-11-13 02:48:57 +000097 /// \brief Returns the address the GlobalVariable should be written into. The
98 /// GVMemoryBlock object prefixes that.
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000099 static char *Create(const GlobalVariable *GV, const TargetData& TD) {
100 const Type *ElTy = GV->getType()->getElementType();
101 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy);
102 void *RawMemory = ::operator new(
103 TargetData::RoundUpAlignment(sizeof(GVMemoryBlock),
104 TD.getPreferredAlignment(GV))
105 + GVSize);
106 new(RawMemory) GVMemoryBlock(GV);
107 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock);
108 }
109
110 virtual void deleted() {
111 // We allocated with operator new and with some extra memory hanging off the
112 // end, so don't just delete this. I'm not sure if this is actually
113 // required.
114 this->~GVMemoryBlock();
115 ::operator delete(this);
116 }
117};
118} // anonymous namespace
119
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000120char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) {
Jeffrey Yasskin47b71122010-03-27 04:53:56 +0000121 return GVMemoryBlock::Create(GV, *getTargetData());
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000122}
123
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000124bool ExecutionEngine::removeModule(Module *M) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000125 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000126 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000127 Module *Found = *I;
128 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000129 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000130 clearGlobalMappingsFromModule(M);
131 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000132 }
133 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000134 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000135}
136
Chris Lattnerfe854032006-08-16 01:24:12 +0000137Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
138 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000139 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000140 return F;
141 }
142 return 0;
143}
144
145
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000146void *ExecutionEngineState::RemoveMapping(const MutexGuard &,
147 const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000148 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000149 void *OldVal;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000150
151 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the
152 // GlobalAddressMap.
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000153 if (I == GlobalAddressMap.end())
154 OldVal = 0;
155 else {
156 OldVal = I->second;
157 GlobalAddressMap.erase(I);
158 }
159
160 GlobalAddressReverseMap.erase(OldVal);
161 return OldVal;
162}
163
Chris Lattnere7fd5532006-05-08 22:00:52 +0000164void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
165 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000166
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000167 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000168 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000169 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000170 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
171 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000172
173 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000174 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000175 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000176 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000177 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
178 V = GV;
179 }
180}
181
Chris Lattnere7fd5532006-05-08 22:00:52 +0000182void ExecutionEngine::clearAllGlobalMappings() {
183 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000184
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000185 EEState.getGlobalAddressMap(locked).clear();
186 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187}
188
Nate Begemanf049e072008-05-21 16:34:48 +0000189void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
190 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000191
192 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000193 EEState.RemoveMapping(locked, FI);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000194 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
195 GI != GE; ++GI)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000196 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000197}
198
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000199void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000200 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000201
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000202 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000203 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000204
Chris Lattnere7fd5532006-05-08 22:00:52 +0000205 // Deleting from the mapping?
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000206 if (Addr == 0)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000207 return EEState.RemoveMapping(locked, GV);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000208
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000209 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000210 void *OldVal = CurVal;
211
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000212 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
213 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000214 CurVal = Addr;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000215
216 // If we are using the reverse mapping, add it too.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000217 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000218 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000219 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000220 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
221 V = GV;
222 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000223 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000224}
225
Chris Lattnere7fd5532006-05-08 22:00:52 +0000226void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
227 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000228
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000229 ExecutionEngineState::GlobalAddressMapTy::iterator I =
230 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000231 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000232}
233
Chris Lattner55d86482003-12-31 20:21:04 +0000234const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000235 MutexGuard locked(lock);
236
Chris Lattner55d86482003-12-31 20:21:04 +0000237 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000238 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000239 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000240 I = EEState.getGlobalAddressMap(locked).begin(),
241 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
Daniel Dunbarab19da42010-11-13 00:55:42 +0000242 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(
243 I->second, I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000244 }
245
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000246 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000247 EEState.getGlobalAddressReverseMap(locked).find(Addr);
248 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000249}
Chris Lattner87f03102003-12-26 06:50:30 +0000250
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000251namespace {
252class ArgvArray {
253 char *Array;
254 std::vector<char*> Values;
255public:
256 ArgvArray() : Array(NULL) {}
257 ~ArgvArray() { clear(); }
258 void clear() {
259 delete[] Array;
260 Array = NULL;
261 for (size_t I = 0, E = Values.size(); I != E; ++I) {
262 delete[] Values[I];
263 }
264 Values.clear();
265 }
266 /// Turn a vector of strings into a nice argv style array of pointers to null
267 /// terminated strings.
268 void *reset(LLVMContext &C, ExecutionEngine *EE,
269 const std::vector<std::string> &InputArgv);
270};
271} // anonymous namespace
272void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
273 const std::vector<std::string> &InputArgv) {
274 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000275 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000276 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000277
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000278 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000279 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000280
281 for (unsigned i = 0; i != InputArgv.size(); ++i) {
282 unsigned Size = InputArgv[i].size()+1;
283 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000284 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000285 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000286
Chris Lattner87f03102003-12-26 06:50:30 +0000287 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
288 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000289
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000290 // Endian safe: Array[i] = (PointerTy)Dest;
291 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000292 SBytePtr);
293 }
294
295 // Null terminate it
296 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000297 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000298 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000299 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000300}
301
Chris Lattnerfbd39762009-09-23 01:46:04 +0000302void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
303 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000304 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000305 GlobalVariable *GV = module->getNamedGlobal(Name);
Evan Cheng18314dc2008-09-30 15:51:21 +0000306
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000307 // If this global has internal linkage, or if it has a use, then it must be
308 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
309 // this is the case, don't execute any of the global ctors, __main will do
310 // it.
311 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
312
313 // Should be an array of '{ int, void ()* }' structs. The first value is
314 // the init priority, which we ignore.
315 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
316 if (!InitList) return;
317 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
318 ConstantStruct *CS =
319 dyn_cast<ConstantStruct>(InitList->getOperand(i));
320 if (!CS) continue;
321 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
322
323 Constant *FP = CS->getOperand(1);
324 if (FP->isNullValue())
325 break; // Found a null terminator, exit.
326
327 // Strip off constant expression casts.
328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
329 if (CE->isCast())
330 FP = CE->getOperand(0);
331
332 // Execute the ctor/dtor function!
333 if (Function *F = dyn_cast<Function>(FP))
334 runFunction(F, std::vector<GenericValue>());
335
336 // FIXME: It is marginally lame that we just do nothing here if we see an
337 // entry we don't recognize. It might not be unreasonable for the verifier
338 // to not even allow this and just assert here.
339 }
Evan Cheng18314dc2008-09-30 15:51:21 +0000340}
341
Evan Cheng18314dc2008-09-30 15:51:21 +0000342void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
343 // Execute global ctors/dtors for each module in the program.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000344 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
345 runStaticConstructorsDestructors(Modules[i], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000346}
347
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000348#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000349/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
350static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
351 unsigned PtrSize = EE->getTargetData()->getPointerSize();
352 for (unsigned i = 0; i < PtrSize; ++i)
353 if (*(i + (uint8_t*)Loc))
354 return false;
355 return true;
356}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000357#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000358
Chris Lattner87f03102003-12-26 06:50:30 +0000359int ExecutionEngine::runFunctionAsMain(Function *Fn,
360 const std::vector<std::string> &argv,
361 const char * const * envp) {
362 std::vector<GenericValue> GVArgs;
363 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000364 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000365
366 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000367 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000368 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000369 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000370
371 // Check the argument types.
372 if (NumArgs > 3)
373 report_fatal_error("Invalid number of arguments of main() supplied");
374 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty)
375 report_fatal_error("Invalid type for third argument of main() supplied");
376 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty)
377 report_fatal_error("Invalid type for second argument of main() supplied");
378 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32))
379 report_fatal_error("Invalid type for first argument of main() supplied");
380 if (!FTy->getReturnType()->isIntegerTy() &&
381 !FTy->getReturnType()->isVoidTy())
382 report_fatal_error("Invalid return type of main() supplied");
383
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000384 ArgvArray CArgv;
385 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000386 if (NumArgs) {
387 GVArgs.push_back(GVArgc); // Arg #0 = argc.
388 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000389 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000390 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000391 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000392 "argv[0] was null after CreateArgv");
393 if (NumArgs > 2) {
394 std::vector<std::string> EnvVars;
395 for (unsigned i = 0; envp[i]; ++i)
396 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000397 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000398 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000399 }
400 }
401 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000402
Reid Spencer8fb0f192007-03-06 03:04:04 +0000403 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000404}
405
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000406ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000407 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000408 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000409 CodeGenOpt::Level OptLevel,
410 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000411 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000412 .setEngineKind(ForceInterpreter
413 ? EngineKind::Interpreter
414 : EngineKind::JIT)
415 .setErrorStr(ErrorStr)
416 .setOptLevel(OptLevel)
417 .setAllocateGVsWithCode(GVsWithCode)
418 .create();
419}
Brian Gaeke82d82772003-09-03 20:34:19 +0000420
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000421ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000422 // Make sure we can resolve symbols in the program as well. The zero arg
423 // to the function tells DynamicLibrary to load the program, not a library.
424 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
425 return 0;
426
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000427 // If the user specified a memory manager but didn't specify which engine to
428 // create, we assume they only want the JIT, and we fail if they only want
429 // the interpreter.
430 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000431 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000432 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000433 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000434 if (ErrorStr)
435 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000436 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000437 }
438 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000439
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000440 // Unless the interpreter was explicitly selected or the JIT is not linked,
441 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000442 if (WhichEngine & EngineKind::JIT) {
Daniel Dunbar6d135972010-11-17 16:06:37 +0000443 if (UseMCJIT && ExecutionEngine::MCJITCtor) {
444 ExecutionEngine *EE =
445 ExecutionEngine::MCJITCtor(M, ErrorStr, JMM, OptLevel,
446 AllocateGVsWithCode, CMModel,
447 MArch, MCPU, MAttrs);
448 if (EE) return EE;
449 } else if (ExecutionEngine::JITCtor) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000450 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000451 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000452 AllocateGVsWithCode, CMModel,
453 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000454 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000455 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000456 }
457
458 // If we can't make a JIT and we didn't request one specifically, try making
459 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000460 if (WhichEngine & EngineKind::Interpreter) {
461 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000462 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000463 if (ErrorStr)
464 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000465 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000466 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000467
468 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
469 if (ErrorStr)
470 *ErrorStr = "JIT has not been linked in.";
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000471 }
472
Chris Lattnerfbd39762009-09-23 01:46:04 +0000473 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000474}
475
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000476void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000477 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000478 return getPointerToFunction(F);
479
Reid Spenceree448632005-07-12 15:51:55 +0000480 MutexGuard locked(lock);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000481 if (void *P = EEState.getGlobalAddressMap(locked)[GV])
482 return P;
Jeff Cohen68835dd2006-02-07 05:11:57 +0000483
484 // Global variable might have been added since interpreter started.
485 if (GlobalVariable *GVar =
486 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
487 EmitGlobalVariable(GVar);
488 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000489 llvm_unreachable("Global hasn't had an address allocated yet!");
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000490
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000491 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000492}
493
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000494/// \brief Converts a Constant* into a GenericValue, including handling of
495/// ConstantExpr values.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000496GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000497 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000498 if (isa<UndefValue>(C)) {
499 GenericValue Result;
500 switch (C->getType()->getTypeID()) {
501 case Type::IntegerTyID:
502 case Type::X86_FP80TyID:
503 case Type::FP128TyID:
504 case Type::PPC_FP128TyID:
505 // Although the value is undefined, we still have to construct an APInt
506 // with the correct bit width.
507 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
508 break;
509 default:
510 break;
511 }
512 return Result;
513 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000514
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000515 // Otherwise, if the value is a ConstantExpr...
Reid Spencer3da59db2006-11-27 01:05:10 +0000516 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000517 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000518 switch (CE->getOpcode()) {
519 case Instruction::GetElementPtr: {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000520 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000521 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000522 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000523 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000524 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000525
Reid Spencer8fb0f192007-03-06 03:04:04 +0000526 char* tmp = (char*) Result.PointerVal;
527 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000528 return Result;
529 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000530 case Instruction::Trunc: {
531 GenericValue GV = getConstantValue(Op0);
532 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
533 GV.IntVal = GV.IntVal.trunc(BitWidth);
534 return GV;
535 }
536 case Instruction::ZExt: {
537 GenericValue GV = getConstantValue(Op0);
538 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
539 GV.IntVal = GV.IntVal.zext(BitWidth);
540 return GV;
541 }
542 case Instruction::SExt: {
543 GenericValue GV = getConstantValue(Op0);
544 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
545 GV.IntVal = GV.IntVal.sext(BitWidth);
546 return GV;
547 }
548 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000549 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000550 GenericValue GV = getConstantValue(Op0);
551 GV.FloatVal = float(GV.DoubleVal);
552 return GV;
553 }
554 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000555 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000556 GenericValue GV = getConstantValue(Op0);
557 GV.DoubleVal = double(GV.FloatVal);
558 return GV;
559 }
560 case Instruction::UIToFP: {
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.roundToDouble());
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.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000566 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000567 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000568 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000569 false,
570 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000571 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000572 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000573 return GV;
574 }
575 case Instruction::SIToFP: {
576 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000577 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000578 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000579 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000580 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000581 else if (CE->getType()->isX86_FP80Ty()) {
Benjamin Kramer3069cbf2010-12-04 15:28:22 +0000582 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000583 (void)apf.convertFromAPInt(GV.IntVal,
Dan Gohman62824062008-02-29 01:27:13 +0000584 true,
585 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000586 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000587 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000588 return GV;
589 }
590 case Instruction::FPToUI: // double->APInt conversion handles sign
591 case Instruction::FPToSI: {
592 GenericValue GV = getConstantValue(Op0);
593 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000594 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000595 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000596 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000597 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000598 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000599 APFloat apf = APFloat(GV.IntVal);
600 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000601 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000602 (void)apf.convertToInteger(&v, BitWidth,
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000603 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000604 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000605 GV.IntVal = v; // endian?
606 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000607 return GV;
608 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000609 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000610 GenericValue GV = getConstantValue(Op0);
611 uint32_t PtrWidth = TD->getPointerSizeInBits();
612 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
613 return GV;
614 }
615 case Instruction::IntToPtr: {
616 GenericValue GV = getConstantValue(Op0);
617 uint32_t PtrWidth = TD->getPointerSizeInBits();
618 if (PtrWidth != GV.IntVal.getBitWidth())
619 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
620 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
621 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000622 return GV;
623 }
624 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000625 GenericValue GV = getConstantValue(Op0);
626 const Type* DestTy = CE->getType();
627 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000628 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000629 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000630 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000631 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000632 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000633 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000634 GV.DoubleVal = GV.IntVal.bitsToDouble();
635 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000636 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000637 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000638 GV.IntVal = APInt::floatToBits(GV.FloatVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000639 break;
640 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000641 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Jay Foade4d19c92010-11-28 21:04:48 +0000642 GV.IntVal = APInt::doubleToBits(GV.DoubleVal);
Reid Spencerbce30f12007-03-06 22:23:15 +0000643 break;
644 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000645 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000646 break; // getConstantValue(Op0) above already converted it
647 }
648 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000649 }
Chris Lattner9a231222003-05-14 17:51:49 +0000650 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000651 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000652 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000653 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000654 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000655 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000656 case Instruction::UDiv:
657 case Instruction::SDiv:
658 case Instruction::URem:
659 case Instruction::SRem:
660 case Instruction::And:
661 case Instruction::Or:
662 case Instruction::Xor: {
663 GenericValue LHS = getConstantValue(Op0);
664 GenericValue RHS = getConstantValue(CE->getOperand(1));
665 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000666 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000667 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000668 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000669 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000670 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
672 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
673 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
674 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
675 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
676 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
677 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
678 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
679 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
680 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
681 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000682 break;
683 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000684 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000685 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000686 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000687 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000688 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000689 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000690 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000691 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000692 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000693 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000694 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000695 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000696 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000697 break;
698 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000699 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000700 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000701 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000702 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000703 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000704 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000705 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000706 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000707 case Instruction::FDiv:
Reid Spencerbce30f12007-03-06 22:23:15 +0000708 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000709 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000710 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000711 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000712 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000713 case Type::X86_FP80TyID:
714 case Type::PPC_FP128TyID:
715 case Type::FP128TyID: {
716 APFloat apfLHS = APFloat(LHS.IntVal);
717 switch (CE->getOpcode()) {
Daniel Dunbarab19da42010-11-13 00:55:42 +0000718 default: llvm_unreachable("Invalid long double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000719 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000720 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000721 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000722 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000723 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000724 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000725 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000726 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000727 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000728 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000729 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000730 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000731 case Instruction::FDiv:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000732 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000733 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000734 break;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000735 case Instruction::FRem:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000736 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000737 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000738 break;
739 }
740 }
741 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000742 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000743 return GV;
744 }
Chris Lattner9a231222003-05-14 17:51:49 +0000745 default:
746 break;
747 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000748
749 SmallString<256> Msg;
750 raw_svector_ostream OS(Msg);
751 OS << "ConstantExpr not handled: " << *CE;
752 report_fatal_error(OS.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000753 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000754
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000755 // Otherwise, we have a simple constant.
Reid Spencerbce30f12007-03-06 22:23:15 +0000756 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000757 switch (C->getType()->getTypeID()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000758 case Type::FloatTyID:
759 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000760 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000761 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000762 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000763 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000764 case Type::X86_FP80TyID:
765 case Type::FP128TyID:
766 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000767 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000768 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000769 case Type::IntegerTyID:
770 Result.IntVal = cast<ConstantInt>(C)->getValue();
771 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000772 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000773 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000774 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000775 else if (const Function *F = dyn_cast<Function>(C))
776 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000777 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000778 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000779 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
780 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
781 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000782 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000783 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000784 break;
785 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000786 SmallString<256> Msg;
787 raw_svector_ostream OS(Msg);
788 OS << "ERROR: Constant unimplemented for type: " << *C->getType();
789 report_fatal_error(OS.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000790 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000791
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000792 return Result;
793}
794
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000795/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
796/// with the integer held in IntVal.
797static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
798 unsigned StoreBytes) {
799 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
800 uint8_t *Src = (uint8_t *)IntVal.getRawData();
801
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000802 if (sys::isLittleEndianHost()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000803 // Little-endian host - the source is ordered from LSB to MSB. Order the
804 // destination from LSB to MSB: Do a straight copy.
805 memcpy(Dst, Src, StoreBytes);
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000806 } else {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000807 // Big-endian host - the source is an array of 64 bit words ordered from
808 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
809 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
810 while (StoreBytes > sizeof(uint64_t)) {
811 StoreBytes -= sizeof(uint64_t);
812 // May not be aligned so use memcpy.
813 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
814 Src += sizeof(uint64_t);
815 }
816
817 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
818 }
819}
820
Evan Cheng89687e32008-11-04 06:10:31 +0000821void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
822 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000823 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
824
Reid Spencer8fb0f192007-03-06 03:04:04 +0000825 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000826 case Type::IntegerTyID:
827 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000828 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000829 case Type::FloatTyID:
830 *((float*)Ptr) = Val.FloatVal;
831 break;
832 case Type::DoubleTyID:
833 *((double*)Ptr) = Val.DoubleVal;
834 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000835 case Type::X86_FP80TyID:
836 memcpy(Ptr, Val.IntVal.getRawData(), 10);
837 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000838 case Type::PointerTyID:
839 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
840 if (StoreBytes != sizeof(PointerTy))
841 memset(Ptr, 0, StoreBytes);
842
Reid Spencer8fb0f192007-03-06 03:04:04 +0000843 *((PointerTy*)Ptr) = Val.PointerVal;
844 break;
845 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000846 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000847 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000848
Chris Lattnerb67c9582009-01-22 19:53:00 +0000849 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000850 // Host and target are different endian - reverse the stored bytes.
851 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
852}
853
854/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
855/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
856static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
857 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
858 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
859
Chris Lattnerb67c9582009-01-22 19:53:00 +0000860 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000861 // Little-endian host - the destination must be ordered from LSB to MSB.
862 // The source is ordered from LSB to MSB: Do a straight copy.
863 memcpy(Dst, Src, LoadBytes);
864 else {
865 // Big-endian - the destination is an array of 64 bit words ordered from
866 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
867 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
868 // a word.
869 while (LoadBytes > sizeof(uint64_t)) {
870 LoadBytes -= sizeof(uint64_t);
871 // May not be aligned so use memcpy.
872 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
873 Dst += sizeof(uint64_t);
874 }
875
876 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
877 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000878}
879
Misha Brukman4afac182003-10-10 17:45:12 +0000880/// FIXME: document
881///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000882void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000883 GenericValue *Ptr,
884 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000885 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000886
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000887 switch (Ty->getTypeID()) {
888 case Type::IntegerTyID:
889 // An APInt with all words initially zero.
890 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
891 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
892 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000893 case Type::FloatTyID:
894 Result.FloatVal = *((float*)Ptr);
895 break;
896 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000897 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000898 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000899 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000900 Result.PointerVal = *((PointerTy*)Ptr);
901 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000902 case Type::X86_FP80TyID: {
903 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000904 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000905 uint64_t y[2];
906 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000907 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000908 break;
909 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000910 default:
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000911 SmallString<256> Msg;
912 raw_svector_ostream OS(Msg);
913 OS << "Cannot load value of type " << *Ty << "!";
914 report_fatal_error(OS.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000915 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000916}
917
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000918void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000919 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000920 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000921 if (isa<UndefValue>(Init)) {
922 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000923 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000924 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000925 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000926 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
927 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
928 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000929 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000930 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000931 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000932 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
933 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000934 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000935 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
936 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
937 return;
938 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
939 const StructLayout *SL =
940 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
941 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
942 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
943 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000944 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000945 GenericValue Val = getConstantValue(Init);
946 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
947 return;
948 }
949
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000950 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n");
Torok Edwinc23197a2009-07-14 16:55:14 +0000951 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000952}
953
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000954/// EmitGlobals - Emit all of the global variables to memory, storing their
955/// addresses into GlobalAddress. This must make sure to copy the contents of
956/// their initializers into the memory.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000957void ExecutionEngine::emitGlobals() {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000958 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000959 // to hold them. If there is more than one module, do a prepass over globals
960 // to figure out how the different modules should link together.
Chris Lattnerfe854032006-08-16 01:24:12 +0000961 std::map<std::pair<std::string, const Type*>,
962 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000963
Chris Lattnerfe854032006-08-16 01:24:12 +0000964 if (Modules.size() != 1) {
965 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000966 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000967 for (Module::const_global_iterator I = M.global_begin(),
968 E = M.global_end(); I != E; ++I) {
969 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000970 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000971 GV->hasAppendingLinkage() || !GV->hasName())
972 continue;// Ignore external globals and globals with internal linkage.
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000973
974 const GlobalValue *&GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +0000975 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
976
977 // If this is the first time we've seen this global, it is the canonical
978 // version.
979 if (!GVEntry) {
980 GVEntry = GV;
981 continue;
982 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000983
Chris Lattnerfe854032006-08-16 01:24:12 +0000984 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000985 if (GVEntry->hasExternalLinkage() ||
986 GVEntry->hasDLLImportLinkage() ||
987 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000988 continue;
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000989
Chris Lattnerfe854032006-08-16 01:24:12 +0000990 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000991 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000992 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000993 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000994 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000995 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000996 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +0000997
Chris Lattnerfe854032006-08-16 01:24:12 +0000998 std::vector<const GlobalValue*> NonCanonicalGlobals;
999 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001000 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001001 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1002 I != E; ++I) {
1003 // In the multi-module case, see what this global maps to.
1004 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001005 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001006 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1007 // If something else is the canonical global, ignore this one.
1008 if (GVEntry != &*I) {
1009 NonCanonicalGlobals.push_back(I);
1010 continue;
1011 }
1012 }
1013 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001014
Reid Spencer5cbf9852007-01-30 20:08:39 +00001015 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001016 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001017 } else {
1018 // External variable reference. Try to use the dynamic loader to
1019 // get a pointer to it.
1020 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001021 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001022 addGlobalMapping(I, SymAddr);
1023 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001024 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001025 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001026 }
1027 }
1028 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001029
Chris Lattnerfe854032006-08-16 01:24:12 +00001030 // If there are multiple modules, map the non-canonical globals to their
1031 // canonical location.
1032 if (!NonCanonicalGlobals.empty()) {
1033 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1034 const GlobalValue *GV = NonCanonicalGlobals[i];
1035 const GlobalValue *CGV =
1036 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1037 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1038 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001039 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001040 }
1041 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001042
1043 // Now that all of the globals are set up in memory, loop through them all
Reid Spencera54b7cb2007-01-12 07:05:14 +00001044 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001045 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1046 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001047 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001048 if (!LinkedGlobalsMap.empty()) {
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001049 if (const GlobalValue *GVEntry =
Chris Lattnerfe854032006-08-16 01:24:12 +00001050 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1051 if (GVEntry != &*I) // Not the canonical variable.
1052 continue;
1053 }
1054 EmitGlobalVariable(I);
1055 }
1056 }
1057 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001058}
1059
1060// EmitGlobalVariable - This method emits the specified global variable to the
1061// address specified in GlobalAddresses, or allocates new memory if it's not
1062// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001063void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001064 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001065
Chris Lattner24b0a182003-12-20 02:45:37 +00001066 if (GA == 0) {
1067 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001068 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001069 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001070 }
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001071
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001072 // Don't initialize if it's thread local, let the client do it.
1073 if (!GV->isThreadLocal())
1074 InitializeMemory(GV->getInitializer(), GA);
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001075
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001076 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001077 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001078 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001079 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001080}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001081
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001082ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1083 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001084}
1085
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001086sys::Mutex *
1087ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001088 return &EES->EE.lock;
1089}
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001090
1091void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES,
1092 const GlobalValue *Old) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001093 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1094 EES->GlobalAddressReverseMap.erase(OldVal);
1095}
1096
Daniel Dunbar48dd8752010-11-13 02:48:57 +00001097void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *,
1098 const GlobalValue *,
1099 const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001100 assert(false && "The ExecutionEngine doesn't know how to handle a"
1101 " RAUW on a value it has a global mapping for.");
1102}