blob: 77082c4d04190d92433360e186dea694386e9411 [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"
Chris Lattner9f3ff922009-08-23 22:49:13 +000022#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Torok Edwin31e24662009-07-07 17:32:34 +000024#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000026#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000027#include "llvm/Support/raw_ostream.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000028#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000029#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000030#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000031#include <cmath>
32#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000033using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000034
Chris Lattner36343732006-12-19 22:43:32 +000035STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
36STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000037
Jeffrey Yasskin46882612010-02-05 16:19:36 +000038ExecutionEngine *(*ExecutionEngine::JITCtor)(
39 Module *M,
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
42 CodeGenOpt::Level OptLevel,
43 bool GVsWithCode,
44 CodeModel::Model CMM,
45 StringRef MArch,
46 StringRef MCPU,
47 const SmallVectorImpl<std::string>& MAttrs) = 0;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000048ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Kleckner4b1511b2009-07-18 00:42:18 +000049 std::string *ErrorStr) = 0;
Chris Lattner2fe4bb02006-03-22 06:07:50 +000050
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000051ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000052 : EEState(*this),
Duncan Sandsb35fd442010-10-21 08:57:29 +000053 LazyFunctionCreator(0),
54 ExceptionTableRegister(0),
55 ExceptionTableDeregister(0) {
Jeffrey Yasskindc857242009-10-27 20:30:28 +000056 CompilingLazily = false;
Evan Cheng446531e2008-09-24 16:25:55 +000057 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000058 SymbolSearchingDisabled = false;
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000059 Modules.push_back(M);
60 assert(M && "Module is null?");
Misha Brukman19684162003-10-16 21:18:05 +000061}
62
Brian Gaeke8e539482003-09-04 22:57:27 +000063ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000064 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000065 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
66 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000067}
68
Duncan Sandsb35fd442010-10-21 08:57:29 +000069void ExecutionEngine::DeregisterAllTables() {
70 if (ExceptionTableDeregister) {
71 std::vector<void*>::iterator it = AllExceptionTables.begin();
72 std::vector<void*>::iterator ite = AllExceptionTables.end();
73 for (; it != ite; ++it)
74 ExceptionTableDeregister(*it);
75 AllExceptionTables.clear();
76 }
77}
78
Jeffrey Yasskin47b71122010-03-27 04:53:56 +000079namespace {
80// This class automatically deletes the memory block when the GlobalVariable is
81// destroyed.
82class GVMemoryBlock : public CallbackVH {
83 GVMemoryBlock(const GlobalVariable *GV)
84 : CallbackVH(const_cast<GlobalVariable*>(GV)) {}
85
86public:
87 // Returns the address the GlobalVariable should be written into. The
88 // GVMemoryBlock object prefixes that.
89 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
Nicolas Geoffray46fa1392008-10-25 15:41:43 +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 +0000114/// removeModule - Remove a Module from the list of modules.
115bool ExecutionEngine::removeModule(Module *M) {
116 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +0000117 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000118 Module *Found = *I;
119 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +0000120 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000121 clearGlobalMappingsFromModule(M);
122 return true;
Devang Patel73d0e212007-10-15 19:56:32 +0000123 }
124 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000125 return false;
Nate Begeman60789e42009-01-23 19:27:28 +0000126}
127
Chris Lattnerfe854032006-08-16 01:24:12 +0000128/// FindFunctionNamed - Search all of the active modules to find the one that
129/// defines FnName. This is very slow operation and shouldn't be used for
130/// general code.
131Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
132 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000133 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000134 return F;
135 }
136 return 0;
137}
138
139
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000140void *ExecutionEngineState::RemoveMapping(
141 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000142 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000143 void *OldVal;
144 if (I == GlobalAddressMap.end())
145 OldVal = 0;
146 else {
147 OldVal = I->second;
148 GlobalAddressMap.erase(I);
149 }
150
151 GlobalAddressReverseMap.erase(OldVal);
152 return OldVal;
153}
154
Chris Lattnere7fd5532006-05-08 22:00:52 +0000155/// addGlobalMapping - Tell the execution engine that the specified global is
156/// at the specified location. This is used internally as functions are JIT'd
157/// and as global variables are laid out in memory. It can and should also be
158/// used by clients of the EE that want to have an LLVM global overlay
159/// existing data in memory.
160void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
161 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000162
David Greeneae7c59a2010-01-05 01:27:39 +0000163 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000164 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000165 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000166 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
167 CurVal = Addr;
168
169 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000170 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000171 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000172 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000173 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
174 V = GV;
175 }
176}
177
178/// clearAllGlobalMappings - Clear all global mappings and start over again
179/// use in dynamic compilation scenarios when you want to move globals
180void ExecutionEngine::clearAllGlobalMappings() {
181 MutexGuard locked(lock);
182
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000183 EEState.getGlobalAddressMap(locked).clear();
184 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000185}
186
Nate Begemanf049e072008-05-21 16:34:48 +0000187/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
188/// particular module, because it has been removed from the JIT.
189void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
190 MutexGuard locked(lock);
191
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);
Nate Begemanf049e072008-05-21 16:34:48 +0000194 }
195 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
196 GI != GE; ++GI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000197 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000198 }
199}
200
Chris Lattnere7fd5532006-05-08 22:00:52 +0000201/// updateGlobalMapping - Replace an existing mapping for GV with a new
202/// address. This updates both maps as required. If "Addr" is null, the
203/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000204void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000205 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000206
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000207 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000208 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000209
Chris Lattnere7fd5532006-05-08 22:00:52 +0000210 // Deleting from the mapping?
211 if (Addr == 0) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000212 return EEState.RemoveMapping(locked, GV);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000213 }
214
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000215 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000216 void *OldVal = CurVal;
217
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000218 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
219 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000220 CurVal = Addr;
221
222 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000223 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000224 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000225 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000226 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
227 V = GV;
228 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000229 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000230}
231
232/// getPointerToGlobalIfAvailable - This returns the address of the specified
233/// global value if it is has already been codegen'd, otherwise it returns null.
234///
235void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
236 MutexGuard locked(lock);
237
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000238 ExecutionEngineState::GlobalAddressMapTy::iterator I =
239 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000240 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000241}
242
Chris Lattner55d86482003-12-31 20:21:04 +0000243/// getGlobalValueAtAddress - Return the LLVM global value object that starts
244/// at the specified address.
245///
246const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000247 MutexGuard locked(lock);
248
Chris Lattner55d86482003-12-31 20:21:04 +0000249 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000250 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000251 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000252 I = EEState.getGlobalAddressMap(locked).begin(),
253 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
254 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
Chris Lattnere7fd5532006-05-08 22:00:52 +0000255 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000256 }
257
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000258 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000259 EEState.getGlobalAddressReverseMap(locked).find(Addr);
260 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000261}
Chris Lattner87f03102003-12-26 06:50:30 +0000262
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000263namespace {
264class ArgvArray {
265 char *Array;
266 std::vector<char*> Values;
267public:
268 ArgvArray() : Array(NULL) {}
269 ~ArgvArray() { clear(); }
270 void clear() {
271 delete[] Array;
272 Array = NULL;
273 for (size_t I = 0, E = Values.size(); I != E; ++I) {
274 delete[] Values[I];
275 }
276 Values.clear();
277 }
278 /// Turn a vector of strings into a nice argv style array of pointers to null
279 /// terminated strings.
280 void *reset(LLVMContext &C, ExecutionEngine *EE,
281 const std::vector<std::string> &InputArgv);
282};
283} // anonymous namespace
284void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
285 const std::vector<std::string> &InputArgv) {
286 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000287 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000288 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000289
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000290 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000291 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000292
293 for (unsigned i = 0; i != InputArgv.size(); ++i) {
294 unsigned Size = InputArgv[i].size()+1;
295 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000296 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000297 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000298
Chris Lattner87f03102003-12-26 06:50:30 +0000299 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
300 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000301
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000302 // Endian safe: Array[i] = (PointerTy)Dest;
303 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000304 SBytePtr);
305 }
306
307 // Null terminate it
308 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000309 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000310 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000311 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000312}
313
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000314
315/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng18314dc2008-09-30 15:51:21 +0000316/// the static constructors or destructors for a module, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000317/// value of isDtors.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000318void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
319 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000320 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000321
Chris Lattnerfe854032006-08-16 01:24:12 +0000322 // Execute global ctors/dtors for each module in the program.
Chris Lattnerfe854032006-08-16 01:24:12 +0000323
Evan Cheng18314dc2008-09-30 15:51:21 +0000324 GlobalVariable *GV = module->getNamedGlobal(Name);
325
326 // If this global has internal linkage, or if it has a use, then it must be
327 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
328 // this is the case, don't execute any of the global ctors, __main will do
329 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000330 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng18314dc2008-09-30 15:51:21 +0000331
332 // Should be an array of '{ int, void ()* }' structs. The first value is
333 // the init priority, which we ignore.
334 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
335 if (!InitList) return;
336 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
337 if (ConstantStruct *CS =
338 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
339 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
340
341 Constant *FP = CS->getOperand(1);
342 if (FP->isNullValue())
343 break; // Found a null terminator, exit.
344
345 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
346 if (CE->isCast())
347 FP = CE->getOperand(0);
348 if (Function *F = dyn_cast<Function>(FP)) {
349 // Execute the ctor/dtor function!
350 runFunction(F, std::vector<GenericValue>());
351 }
352 }
353}
354
355/// runStaticConstructorsDestructors - This method is used to execute all of
356/// the static constructors or destructors for a program, depending on the
357/// value of isDtors.
358void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
359 // Execute global ctors/dtors for each module in the program.
360 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000361 runStaticConstructorsDestructors(Modules[m], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000362}
363
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000364#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000365/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
366static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
367 unsigned PtrSize = EE->getTargetData()->getPointerSize();
368 for (unsigned i = 0; i < PtrSize; ++i)
369 if (*(i + (uint8_t*)Loc))
370 return false;
371 return true;
372}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000373#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000374
Chris Lattner87f03102003-12-26 06:50:30 +0000375/// runFunctionAsMain - This is a helper function which wraps runFunction to
376/// handle the common task of starting up main with the specified argc, argv,
377/// and envp parameters.
378int ExecutionEngine::runFunctionAsMain(Function *Fn,
379 const std::vector<std::string> &argv,
380 const char * const * envp) {
381 std::vector<GenericValue> GVArgs;
382 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000383 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000384
385 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000386 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000387 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000388 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000389 switch (NumArgs) {
390 case 3:
391 if (FTy->getParamType(2) != PPInt8Ty) {
Chris Lattner75361b62010-04-07 22:58:41 +0000392 report_fatal_error("Invalid type for third argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000393 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000394 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000395 case 2:
396 if (FTy->getParamType(1) != PPInt8Ty) {
Chris Lattner75361b62010-04-07 22:58:41 +0000397 report_fatal_error("Invalid type for second argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000398 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000399 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000400 case 1:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000401 if (!FTy->getParamType(0)->isIntegerTy(32)) {
Chris Lattner75361b62010-04-07 22:58:41 +0000402 report_fatal_error("Invalid type for first argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000403 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000404 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000405 case 0:
Duncan Sands1df98592010-02-16 11:11:14 +0000406 if (!FTy->getReturnType()->isIntegerTy() &&
Benjamin Kramerf0127052010-01-05 13:12:22 +0000407 !FTy->getReturnType()->isVoidTy()) {
Chris Lattner75361b62010-04-07 22:58:41 +0000408 report_fatal_error("Invalid return type of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000409 }
410 break;
411 default:
Chris Lattner75361b62010-04-07 22:58:41 +0000412 report_fatal_error("Invalid number of arguments of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000413 }
414
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000415 ArgvArray CArgv;
416 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000417 if (NumArgs) {
418 GVArgs.push_back(GVArgc); // Arg #0 = argc.
419 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000420 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000421 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000422 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000423 "argv[0] was null after CreateArgv");
424 if (NumArgs > 2) {
425 std::vector<std::string> EnvVars;
426 for (unsigned i = 0; envp[i]; ++i)
427 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000428 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000429 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000430 }
431 }
432 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000433 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000434}
435
Misha Brukman19684162003-10-16 21:18:05 +0000436/// If possible, create a JIT, unless the caller specifically requests an
437/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000438/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000439///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000440ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000441 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000442 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000443 CodeGenOpt::Level OptLevel,
444 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000445 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000446 .setEngineKind(ForceInterpreter
447 ? EngineKind::Interpreter
448 : EngineKind::JIT)
449 .setErrorStr(ErrorStr)
450 .setOptLevel(OptLevel)
451 .setAllocateGVsWithCode(GVsWithCode)
452 .create();
453}
Brian Gaeke82d82772003-09-03 20:34:19 +0000454
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000455ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000456 // Make sure we can resolve symbols in the program as well. The zero arg
457 // to the function tells DynamicLibrary to load the program, not a library.
458 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
459 return 0;
460
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000461 // If the user specified a memory manager but didn't specify which engine to
462 // create, we assume they only want the JIT, and we fail if they only want
463 // the interpreter.
464 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000465 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000466 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000467 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000468 if (ErrorStr)
469 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000470 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000471 }
472 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000473
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000474 // Unless the interpreter was explicitly selected or the JIT is not linked,
475 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000476 if (WhichEngine & EngineKind::JIT) {
477 if (ExecutionEngine::JITCtor) {
478 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000479 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000480 AllocateGVsWithCode, CMModel,
481 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000482 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000483 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000484 }
485
486 // If we can't make a JIT and we didn't request one specifically, try making
487 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000488 if (WhichEngine & EngineKind::Interpreter) {
489 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000490 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000491 if (ErrorStr)
492 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000493 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000494 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000495
496 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
497 if (ErrorStr)
498 *ErrorStr = "JIT has not been linked in.";
499 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000500 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000501}
502
Misha Brukman4afac182003-10-10 17:45:12 +0000503/// getPointerToGlobal - This returns the address of the specified global
504/// value. This may involve code generation if it's a function.
505///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000506void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000507 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000508 return getPointerToFunction(F);
509
Reid Spenceree448632005-07-12 15:51:55 +0000510 MutexGuard locked(lock);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000511 void *p = EEState.getGlobalAddressMap(locked)[GV];
Jeff Cohen68835dd2006-02-07 05:11:57 +0000512 if (p)
513 return p;
514
515 // Global variable might have been added since interpreter started.
516 if (GlobalVariable *GVar =
517 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
518 EmitGlobalVariable(GVar);
519 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000520 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000521 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000522}
523
Reid Spencer3da59db2006-11-27 01:05:10 +0000524/// This function converts a Constant* into a GenericValue. The interesting
525/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000526/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000527GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000528 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000529 if (isa<UndefValue>(C)) {
530 GenericValue Result;
531 switch (C->getType()->getTypeID()) {
532 case Type::IntegerTyID:
533 case Type::X86_FP80TyID:
534 case Type::FP128TyID:
535 case Type::PPC_FP128TyID:
536 // Although the value is undefined, we still have to construct an APInt
537 // with the correct bit width.
538 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
539 break;
540 default:
541 break;
542 }
543 return Result;
544 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000545
Reid Spencer3da59db2006-11-27 01:05:10 +0000546 // If the value is a ConstantExpr
547 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000548 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000549 switch (CE->getOpcode()) {
550 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000551 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000552 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000553 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000554 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000555 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000556
Reid Spencer8fb0f192007-03-06 03:04:04 +0000557 char* tmp = (char*) Result.PointerVal;
558 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000559 return Result;
560 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000561 case Instruction::Trunc: {
562 GenericValue GV = getConstantValue(Op0);
563 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
564 GV.IntVal = GV.IntVal.trunc(BitWidth);
565 return GV;
566 }
567 case Instruction::ZExt: {
568 GenericValue GV = getConstantValue(Op0);
569 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
570 GV.IntVal = GV.IntVal.zext(BitWidth);
571 return GV;
572 }
573 case Instruction::SExt: {
574 GenericValue GV = getConstantValue(Op0);
575 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
576 GV.IntVal = GV.IntVal.sext(BitWidth);
577 return GV;
578 }
579 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000580 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000581 GenericValue GV = getConstantValue(Op0);
582 GV.FloatVal = float(GV.DoubleVal);
583 return GV;
584 }
585 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000586 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000587 GenericValue GV = getConstantValue(Op0);
588 GV.DoubleVal = double(GV.FloatVal);
589 return GV;
590 }
591 case Instruction::UIToFP: {
592 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000593 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000594 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000595 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000596 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000597 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000598 const uint64_t zero[] = {0, 0};
599 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000600 (void)apf.convertFromAPInt(GV.IntVal,
601 false,
602 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000603 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000604 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000605 return GV;
606 }
607 case Instruction::SIToFP: {
608 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000609 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000610 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000611 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000612 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000613 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000614 const uint64_t zero[] = { 0, 0};
615 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000616 (void)apf.convertFromAPInt(GV.IntVal,
617 true,
618 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000619 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000620 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000621 return GV;
622 }
623 case Instruction::FPToUI: // double->APInt conversion handles sign
624 case Instruction::FPToSI: {
625 GenericValue GV = getConstantValue(Op0);
626 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000627 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000628 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000629 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000630 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000631 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000632 APFloat apf = APFloat(GV.IntVal);
633 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000634 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000635 (void)apf.convertToInteger(&v, BitWidth,
636 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000637 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000638 GV.IntVal = v; // endian?
639 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000640 return GV;
641 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000642 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000643 GenericValue GV = getConstantValue(Op0);
644 uint32_t PtrWidth = TD->getPointerSizeInBits();
645 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
646 return GV;
647 }
648 case Instruction::IntToPtr: {
649 GenericValue GV = getConstantValue(Op0);
650 uint32_t PtrWidth = TD->getPointerSizeInBits();
651 if (PtrWidth != GV.IntVal.getBitWidth())
652 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
653 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
654 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000655 return GV;
656 }
657 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000658 GenericValue GV = getConstantValue(Op0);
659 const Type* DestTy = CE->getType();
660 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000661 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000662 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000663 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000664 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000665 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000666 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000667 GV.DoubleVal = GV.IntVal.bitsToDouble();
668 break;
669 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000670 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 GV.IntVal.floatToBits(GV.FloatVal);
672 break;
673 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000674 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000675 GV.IntVal.doubleToBits(GV.DoubleVal);
676 break;
677 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000678 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000679 break; // getConstantValue(Op0) above already converted it
680 }
681 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000682 }
Chris Lattner9a231222003-05-14 17:51:49 +0000683 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000684 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000685 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000686 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000687 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000688 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000689 case Instruction::UDiv:
690 case Instruction::SDiv:
691 case Instruction::URem:
692 case Instruction::SRem:
693 case Instruction::And:
694 case Instruction::Or:
695 case Instruction::Xor: {
696 GenericValue LHS = getConstantValue(Op0);
697 GenericValue RHS = getConstantValue(CE->getOperand(1));
698 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000699 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000700 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000701 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000702 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000703 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000704 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
705 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
706 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
707 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
708 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
709 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
710 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
711 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
712 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
713 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
714 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000715 break;
716 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000717 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000718 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000719 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000720 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000721 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000722 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000723 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000724 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
725 case Instruction::FDiv:
726 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
727 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000728 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000729 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000730 break;
731 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000732 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000733 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000734 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000735 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000736 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000737 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000738 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000739 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
740 case Instruction::FDiv:
741 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
742 case Instruction::FRem:
Chris Lattner87565c12010-05-15 17:10:24 +0000743 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
Reid Spencerbce30f12007-03-06 22:23:15 +0000744 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000745 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000746 case Type::X86_FP80TyID:
747 case Type::PPC_FP128TyID:
748 case Type::FP128TyID: {
749 APFloat apfLHS = APFloat(LHS.IntVal);
750 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000751 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000752 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000753 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000754 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000755 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000756 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000757 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000758 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000759 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000760 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000761 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000762 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000763 break;
764 case Instruction::FDiv:
765 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000766 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000767 break;
768 case Instruction::FRem:
769 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000770 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000771 break;
772 }
773 }
774 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000775 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000776 return GV;
777 }
Chris Lattner9a231222003-05-14 17:51:49 +0000778 default:
779 break;
780 }
Torok Edwin7d696d82009-07-11 13:10:19 +0000781 std::string msg;
782 raw_string_ostream Msg(msg);
783 Msg << "ConstantExpr not handled: " << *CE;
Chris Lattner75361b62010-04-07 22:58:41 +0000784 report_fatal_error(Msg.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000785 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000786
Reid Spencerbce30f12007-03-06 22:23:15 +0000787 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000788 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000789 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000790 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000791 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000792 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000793 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000794 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000795 case Type::X86_FP80TyID:
796 case Type::FP128TyID:
797 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000798 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000799 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000800 case Type::IntegerTyID:
801 Result.IntVal = cast<ConstantInt>(C)->getValue();
802 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000803 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000804 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000805 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000806 else if (const Function *F = dyn_cast<Function>(C))
807 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000808 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000809 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000810 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
811 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
812 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000813 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000814 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000815 break;
816 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000817 std::string msg;
818 raw_string_ostream Msg(msg);
819 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
Chris Lattner75361b62010-04-07 22:58:41 +0000820 report_fatal_error(Msg.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000821 }
822 return Result;
823}
824
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000825/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
826/// with the integer held in IntVal.
827static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
828 unsigned StoreBytes) {
829 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
830 uint8_t *Src = (uint8_t *)IntVal.getRawData();
831
Chris Lattnerb67c9582009-01-22 19:53:00 +0000832 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000833 // Little-endian host - the source is ordered from LSB to MSB. Order the
834 // destination from LSB to MSB: Do a straight copy.
835 memcpy(Dst, Src, StoreBytes);
836 else {
837 // Big-endian host - the source is an array of 64 bit words ordered from
838 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
839 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
840 while (StoreBytes > sizeof(uint64_t)) {
841 StoreBytes -= sizeof(uint64_t);
842 // May not be aligned so use memcpy.
843 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
844 Src += sizeof(uint64_t);
845 }
846
847 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
848 }
849}
850
Nate Begeman37efe672006-04-22 18:53:45 +0000851/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
852/// is the address of the memory at which to store Val, cast to GenericValue *.
853/// It is not a pointer to a GenericValue containing the address at which to
854/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000855void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
856 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000857 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
858
Reid Spencer8fb0f192007-03-06 03:04:04 +0000859 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000860 case Type::IntegerTyID:
861 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000862 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000863 case Type::FloatTyID:
864 *((float*)Ptr) = Val.FloatVal;
865 break;
866 case Type::DoubleTyID:
867 *((double*)Ptr) = Val.DoubleVal;
868 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000869 case Type::X86_FP80TyID:
870 memcpy(Ptr, Val.IntVal.getRawData(), 10);
871 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000872 case Type::PointerTyID:
873 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
874 if (StoreBytes != sizeof(PointerTy))
875 memset(Ptr, 0, StoreBytes);
876
Reid Spencer8fb0f192007-03-06 03:04:04 +0000877 *((PointerTy*)Ptr) = Val.PointerVal;
878 break;
879 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000880 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000881 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000882
Chris Lattnerb67c9582009-01-22 19:53:00 +0000883 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000884 // Host and target are different endian - reverse the stored bytes.
885 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
886}
887
888/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
889/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
890static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
891 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
892 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
893
Chris Lattnerb67c9582009-01-22 19:53:00 +0000894 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000895 // Little-endian host - the destination must be ordered from LSB to MSB.
896 // The source is ordered from LSB to MSB: Do a straight copy.
897 memcpy(Dst, Src, LoadBytes);
898 else {
899 // Big-endian - the destination is an array of 64 bit words ordered from
900 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
901 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
902 // a word.
903 while (LoadBytes > sizeof(uint64_t)) {
904 LoadBytes -= sizeof(uint64_t);
905 // May not be aligned so use memcpy.
906 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
907 Dst += sizeof(uint64_t);
908 }
909
910 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
911 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000912}
913
Misha Brukman4afac182003-10-10 17:45:12 +0000914/// FIXME: document
915///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000916void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000917 GenericValue *Ptr,
918 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000919 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000920
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000921 switch (Ty->getTypeID()) {
922 case Type::IntegerTyID:
923 // An APInt with all words initially zero.
924 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
925 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
926 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000927 case Type::FloatTyID:
928 Result.FloatVal = *((float*)Ptr);
929 break;
930 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000931 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000932 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000933 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000934 Result.PointerVal = *((PointerTy*)Ptr);
935 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000936 case Type::X86_FP80TyID: {
937 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000938 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000939 uint64_t y[2];
940 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000941 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000942 break;
943 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000944 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000945 std::string msg;
946 raw_string_ostream Msg(msg);
947 Msg << "Cannot load value of type " << *Ty << "!";
Chris Lattner75361b62010-04-07 22:58:41 +0000948 report_fatal_error(Msg.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000949 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000950}
951
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000952// InitializeMemory - Recursive function to apply a Constant value into the
953// specified memory location...
954//
955void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000956 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000957 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000958 if (isa<UndefValue>(Init)) {
959 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000960 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000961 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000962 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000963 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
964 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
965 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000966 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000967 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000968 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000969 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
970 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000971 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000972 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
973 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
974 return;
975 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
976 const StructLayout *SL =
977 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
978 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
979 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
980 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000981 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000982 GenericValue Val = getConstantValue(Init);
983 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
984 return;
985 }
986
David Greeneae7c59a2010-01-05 01:27:39 +0000987 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000988 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000989}
990
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000991/// EmitGlobals - Emit all of the global variables to memory, storing their
992/// addresses into GlobalAddress. This must make sure to copy the contents of
993/// their initializers into the memory.
994///
995void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000996
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000997 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000998 // to hold them. If there is more than one module, do a prepass over globals
999 // to figure out how the different modules should link together.
1000 //
1001 std::map<std::pair<std::string, const Type*>,
1002 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +00001003
Chris Lattnerfe854032006-08-16 01:24:12 +00001004 if (Modules.size() != 1) {
1005 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001006 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001007 for (Module::const_global_iterator I = M.global_begin(),
1008 E = M.global_end(); I != E; ++I) {
1009 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +00001010 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +00001011 GV->hasAppendingLinkage() || !GV->hasName())
1012 continue;// Ignore external globals and globals with internal linkage.
1013
1014 const GlobalValue *&GVEntry =
1015 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1016
1017 // If this is the first time we've seen this global, it is the canonical
1018 // version.
1019 if (!GVEntry) {
1020 GVEntry = GV;
1021 continue;
1022 }
1023
1024 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +00001025 if (GVEntry->hasExternalLinkage() ||
1026 GVEntry->hasDLLImportLinkage() ||
1027 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001028 continue;
1029
1030 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +00001031 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +00001032 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +00001033 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +00001034 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001035 }
Chris Lattnerfe854032006-08-16 01:24:12 +00001036 }
1037
1038 std::vector<const GlobalValue*> NonCanonicalGlobals;
1039 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001040 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001041 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1042 I != E; ++I) {
1043 // In the multi-module case, see what this global maps to.
1044 if (!LinkedGlobalsMap.empty()) {
1045 if (const GlobalValue *GVEntry =
1046 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1047 // If something else is the canonical global, ignore this one.
1048 if (GVEntry != &*I) {
1049 NonCanonicalGlobals.push_back(I);
1050 continue;
1051 }
1052 }
1053 }
1054
Reid Spencer5cbf9852007-01-30 20:08:39 +00001055 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001056 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001057 } else {
1058 // External variable reference. Try to use the dynamic loader to
1059 // get a pointer to it.
1060 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001061 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001062 addGlobalMapping(I, SymAddr);
1063 else {
Chris Lattner75361b62010-04-07 22:58:41 +00001064 report_fatal_error("Could not resolve external global address: "
Torok Edwin31e24662009-07-07 17:32:34 +00001065 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001066 }
1067 }
1068 }
1069
1070 // If there are multiple modules, map the non-canonical globals to their
1071 // canonical location.
1072 if (!NonCanonicalGlobals.empty()) {
1073 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1074 const GlobalValue *GV = NonCanonicalGlobals[i];
1075 const GlobalValue *CGV =
1076 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1077 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1078 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001079 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001080 }
1081 }
1082
Reid Spencera54b7cb2007-01-12 07:05:14 +00001083 // Now that all of the globals are set up in memory, loop through them all
1084 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001085 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1086 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001087 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001088 if (!LinkedGlobalsMap.empty()) {
1089 if (const GlobalValue *GVEntry =
1090 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1091 if (GVEntry != &*I) // Not the canonical variable.
1092 continue;
1093 }
1094 EmitGlobalVariable(I);
1095 }
1096 }
1097 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001098}
1099
1100// EmitGlobalVariable - This method emits the specified global variable to the
1101// address specified in GlobalAddresses, or allocates new memory if it's not
1102// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001103void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001104 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001105
Chris Lattner24b0a182003-12-20 02:45:37 +00001106 if (GA == 0) {
1107 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001108 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001109 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001110 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001111
1112 // Don't initialize if it's thread local, let the client do it.
1113 if (!GV->isThreadLocal())
1114 InitializeMemory(GV->getInitializer(), GA);
1115
1116 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001117 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001118 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001119 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001120}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001121
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001122ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1123 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001124}
1125
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001126sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1127 ExecutionEngineState *EES) {
1128 return &EES->EE.lock;
1129}
1130void ExecutionEngineState::AddressMapConfig::onDelete(
1131 ExecutionEngineState *EES, const GlobalValue *Old) {
1132 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1133 EES->GlobalAddressReverseMap.erase(OldVal);
1134}
1135
1136void ExecutionEngineState::AddressMapConfig::onRAUW(
1137 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001138 assert(false && "The ExecutionEngine doesn't know how to handle a"
1139 " RAUW on a value it has a global mapping for.");
1140}