blob: d3d19df286a329c9c144fd9089eba1c41f5543b0 [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;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000050ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
51
Chris Lattner2fe4bb02006-03-22 06:07:50 +000052
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000053ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +000054 : EEState(*this),
55 LazyFunctionCreator(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
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000069char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
70 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +000071 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000072 return new char[GVSize];
73}
74
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000075/// removeModule - Remove a Module from the list of modules.
76bool ExecutionEngine::removeModule(Module *M) {
77 for(SmallVector<Module *, 1>::iterator I = Modules.begin(),
Devang Patel73d0e212007-10-15 19:56:32 +000078 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000079 Module *Found = *I;
80 if (Found == M) {
Devang Patel73d0e212007-10-15 19:56:32 +000081 Modules.erase(I);
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000082 clearGlobalMappingsFromModule(M);
83 return true;
Devang Patel73d0e212007-10-15 19:56:32 +000084 }
85 }
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000086 return false;
Nate Begeman60789e42009-01-23 19:27:28 +000087}
88
Chris Lattnerfe854032006-08-16 01:24:12 +000089/// FindFunctionNamed - Search all of the active modules to find the one that
90/// defines FnName. This is very slow operation and shouldn't be used for
91/// general code.
92Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
93 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +000094 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000095 return F;
96 }
97 return 0;
98}
99
100
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000101void *ExecutionEngineState::RemoveMapping(
102 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000103 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskinc89d27a2009-10-09 22:10:27 +0000104 void *OldVal;
105 if (I == GlobalAddressMap.end())
106 OldVal = 0;
107 else {
108 OldVal = I->second;
109 GlobalAddressMap.erase(I);
110 }
111
112 GlobalAddressReverseMap.erase(OldVal);
113 return OldVal;
114}
115
Chris Lattnere7fd5532006-05-08 22:00:52 +0000116/// addGlobalMapping - Tell the execution engine that the specified global is
117/// at the specified location. This is used internally as functions are JIT'd
118/// and as global variables are laid out in memory. It can and should also be
119/// used by clients of the EE that want to have an LLVM global overlay
120/// existing data in memory.
121void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
122 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000123
David Greeneae7c59a2010-01-05 01:27:39 +0000124 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000125 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000126 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000127 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
128 CurVal = Addr;
129
130 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000131 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000132 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000133 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000134 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
135 V = GV;
136 }
137}
138
139/// clearAllGlobalMappings - Clear all global mappings and start over again
140/// use in dynamic compilation scenarios when you want to move globals
141void ExecutionEngine::clearAllGlobalMappings() {
142 MutexGuard locked(lock);
143
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000144 EEState.getGlobalAddressMap(locked).clear();
145 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattnere7fd5532006-05-08 22:00:52 +0000146}
147
Nate Begemanf049e072008-05-21 16:34:48 +0000148/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
149/// particular module, because it has been removed from the JIT.
150void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
151 MutexGuard locked(lock);
152
153 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000154 EEState.RemoveMapping(locked, FI);
Nate Begemanf049e072008-05-21 16:34:48 +0000155 }
156 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
157 GI != GE; ++GI) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000158 EEState.RemoveMapping(locked, GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000159 }
160}
161
Chris Lattnere7fd5532006-05-08 22:00:52 +0000162/// updateGlobalMapping - Replace an existing mapping for GV with a new
163/// address. This updates both maps as required. If "Addr" is null, the
164/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000165void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000166 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000167
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000168 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000169 EEState.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000170
Chris Lattnere7fd5532006-05-08 22:00:52 +0000171 // Deleting from the mapping?
172 if (Addr == 0) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000173 return EEState.RemoveMapping(locked, GV);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000174 }
175
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000176 void *&CurVal = Map[GV];
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000177 void *OldVal = CurVal;
178
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000179 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
180 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000181 CurVal = Addr;
182
183 // If we are using the reverse mapping, add it too
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000184 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000185 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000186 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
188 V = GV;
189 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000190 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000191}
192
193/// getPointerToGlobalIfAvailable - This returns the address of the specified
194/// global value if it is has already been codegen'd, otherwise it returns null.
195///
196void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
197 MutexGuard locked(lock);
198
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000199 ExecutionEngineState::GlobalAddressMapTy::iterator I =
200 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000201 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000202}
203
Chris Lattner55d86482003-12-31 20:21:04 +0000204/// getGlobalValueAtAddress - Return the LLVM global value object that starts
205/// at the specified address.
206///
207const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000208 MutexGuard locked(lock);
209
Chris Lattner55d86482003-12-31 20:21:04 +0000210 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000211 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000212 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000213 I = EEState.getGlobalAddressMap(locked).begin(),
214 E = EEState.getGlobalAddressMap(locked).end(); I != E; ++I)
215 EEState.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
Chris Lattnere7fd5532006-05-08 22:00:52 +0000216 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000217 }
218
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000219 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +0000220 EEState.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000222}
Chris Lattner87f03102003-12-26 06:50:30 +0000223
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000224namespace {
225class ArgvArray {
226 char *Array;
227 std::vector<char*> Values;
228public:
229 ArgvArray() : Array(NULL) {}
230 ~ArgvArray() { clear(); }
231 void clear() {
232 delete[] Array;
233 Array = NULL;
234 for (size_t I = 0, E = Values.size(); I != E; ++I) {
235 delete[] Values[I];
236 }
237 Values.clear();
238 }
239 /// Turn a vector of strings into a nice argv style array of pointers to null
240 /// terminated strings.
241 void *reset(LLVMContext &C, ExecutionEngine *EE,
242 const std::vector<std::string> &InputArgv);
243};
244} // anonymous namespace
245void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE,
246 const std::vector<std::string> &InputArgv) {
247 clear(); // Free the old contents.
Owen Andersona69571c2006-05-03 01:29:57 +0000248 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000249 Array = new char[(InputArgv.size()+1)*PtrSize];
Chris Lattner87f03102003-12-26 06:50:30 +0000250
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000251 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n");
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000252 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner87f03102003-12-26 06:50:30 +0000253
254 for (unsigned i = 0; i != InputArgv.size(); ++i) {
255 unsigned Size = InputArgv[i].size()+1;
256 char *Dest = new char[Size];
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000257 Values.push_back(Dest);
David Greeneae7c59a2010-01-05 01:27:39 +0000258 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000259
Chris Lattner87f03102003-12-26 06:50:30 +0000260 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
261 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000262
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000263 // Endian safe: Array[i] = (PointerTy)Dest;
264 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000265 SBytePtr);
266 }
267
268 // Null terminate it
269 EE->StoreValueToMemory(PTOGV(0),
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000270 (GenericValue*)(Array+InputArgv.size()*PtrSize),
Chris Lattner87f03102003-12-26 06:50:30 +0000271 SBytePtr);
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000272 return Array;
Chris Lattner87f03102003-12-26 06:50:30 +0000273}
274
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000275
276/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng18314dc2008-09-30 15:51:21 +0000277/// the static constructors or destructors for a module, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000278/// value of isDtors.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000279void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
280 bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000281 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000282
Chris Lattnerfe854032006-08-16 01:24:12 +0000283 // Execute global ctors/dtors for each module in the program.
Chris Lattnerfe854032006-08-16 01:24:12 +0000284
Evan Cheng18314dc2008-09-30 15:51:21 +0000285 GlobalVariable *GV = module->getNamedGlobal(Name);
286
287 // If this global has internal linkage, or if it has a use, then it must be
288 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
289 // this is the case, don't execute any of the global ctors, __main will do
290 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000291 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng18314dc2008-09-30 15:51:21 +0000292
293 // Should be an array of '{ int, void ()* }' structs. The first value is
294 // the init priority, which we ignore.
295 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
296 if (!InitList) return;
297 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
298 if (ConstantStruct *CS =
299 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
300 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
301
302 Constant *FP = CS->getOperand(1);
303 if (FP->isNullValue())
304 break; // Found a null terminator, exit.
305
306 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
307 if (CE->isCast())
308 FP = CE->getOperand(0);
309 if (Function *F = dyn_cast<Function>(FP)) {
310 // Execute the ctor/dtor function!
311 runFunction(F, std::vector<GenericValue>());
312 }
313 }
314}
315
316/// runStaticConstructorsDestructors - This method is used to execute all of
317/// the static constructors or destructors for a program, depending on the
318/// value of isDtors.
319void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
320 // Execute global ctors/dtors for each module in the program.
321 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000322 runStaticConstructorsDestructors(Modules[m], isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000323}
324
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000325#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000326/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
327static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
328 unsigned PtrSize = EE->getTargetData()->getPointerSize();
329 for (unsigned i = 0; i < PtrSize; ++i)
330 if (*(i + (uint8_t*)Loc))
331 return false;
332 return true;
333}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000334#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000335
Chris Lattner87f03102003-12-26 06:50:30 +0000336/// runFunctionAsMain - This is a helper function which wraps runFunction to
337/// handle the common task of starting up main with the specified argc, argv,
338/// and envp parameters.
339int ExecutionEngine::runFunctionAsMain(Function *Fn,
340 const std::vector<std::string> &argv,
341 const char * const * envp) {
342 std::vector<GenericValue> GVArgs;
343 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000344 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000345
346 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000347 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000348 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerf0127052010-01-05 13:12:22 +0000349 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000350 switch (NumArgs) {
351 case 3:
352 if (FTy->getParamType(2) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000353 llvm_report_error("Invalid type for third argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000354 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000355 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000356 case 2:
357 if (FTy->getParamType(1) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000358 llvm_report_error("Invalid type for second argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000359 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000360 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000361 case 1:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000362 if (!FTy->getParamType(0)->isIntegerTy(32)) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000363 llvm_report_error("Invalid type for first argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000364 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000365 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000366 case 0:
Duncan Sands1df98592010-02-16 11:11:14 +0000367 if (!FTy->getReturnType()->isIntegerTy() &&
Benjamin Kramerf0127052010-01-05 13:12:22 +0000368 !FTy->getReturnType()->isVoidTy()) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000369 llvm_report_error("Invalid return type of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000370 }
371 break;
372 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000373 llvm_report_error("Invalid number of arguments of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000374 }
375
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000376 ArgvArray CArgv;
377 ArgvArray CEnv;
Chris Lattnerf24d0992004-08-16 01:05:35 +0000378 if (NumArgs) {
379 GVArgs.push_back(GVArgc); // Arg #0 = argc.
380 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000381 // Arg #1 = argv.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000382 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000383 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000384 "argv[0] was null after CreateArgv");
385 if (NumArgs > 2) {
386 std::vector<std::string> EnvVars;
387 for (unsigned i = 0; envp[i]; ++i)
388 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000389 // Arg #2 = envp.
Jeffrey Yasskinb1938382010-03-26 00:59:12 +0000390 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000391 }
392 }
393 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000394 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000395}
396
Misha Brukman19684162003-10-16 21:18:05 +0000397/// If possible, create a JIT, unless the caller specifically requests an
398/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000399/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000400///
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000401ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000402 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000403 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000404 CodeGenOpt::Level OptLevel,
405 bool GVsWithCode) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000406 return EngineBuilder(M)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000407 .setEngineKind(ForceInterpreter
408 ? EngineKind::Interpreter
409 : EngineKind::JIT)
410 .setErrorStr(ErrorStr)
411 .setOptLevel(OptLevel)
412 .setAllocateGVsWithCode(GVsWithCode)
413 .create();
414}
Brian Gaeke82d82772003-09-03 20:34:19 +0000415
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000416ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000417 // Make sure we can resolve symbols in the program as well. The zero arg
418 // to the function tells DynamicLibrary to load the program, not a library.
419 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
420 return 0;
421
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000422 // If the user specified a memory manager but didn't specify which engine to
423 // create, we assume they only want the JIT, and we fail if they only want
424 // the interpreter.
425 if (JMM) {
Chris Lattnerfbd39762009-09-23 01:46:04 +0000426 if (WhichEngine & EngineKind::JIT)
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000427 WhichEngine = EngineKind::JIT;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000428 else {
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000429 if (ErrorStr)
430 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000431 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000432 }
433 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000434
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000435 // Unless the interpreter was explicitly selected or the JIT is not linked,
436 // try making a JIT.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000437 if (WhichEngine & EngineKind::JIT) {
438 if (ExecutionEngine::JITCtor) {
439 ExecutionEngine *EE =
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000440 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin46882612010-02-05 16:19:36 +0000441 AllocateGVsWithCode, CMModel,
442 MArch, MCPU, MAttrs);
Chris Lattnerfbd39762009-09-23 01:46:04 +0000443 if (EE) return EE;
Chris Lattnerfbd39762009-09-23 01:46:04 +0000444 }
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000445 }
446
447 // If we can't make a JIT and we didn't request one specifically, try making
448 // an interpreter instead.
Chris Lattnerfbd39762009-09-23 01:46:04 +0000449 if (WhichEngine & EngineKind::Interpreter) {
450 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000451 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000452 if (ErrorStr)
453 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnerfbd39762009-09-23 01:46:04 +0000454 return 0;
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000455 }
Chris Lattnerc72efbe2009-09-23 02:03:49 +0000456
457 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
458 if (ErrorStr)
459 *ErrorStr = "JIT has not been linked in.";
460 }
Chris Lattnerfbd39762009-09-23 01:46:04 +0000461 return 0;
Brian Gaeke82d82772003-09-03 20:34:19 +0000462}
463
Misha Brukman4afac182003-10-10 17:45:12 +0000464/// getPointerToGlobal - This returns the address of the specified global
465/// value. This may involve code generation if it's a function.
466///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000467void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000468 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000469 return getPointerToFunction(F);
470
Reid Spenceree448632005-07-12 15:51:55 +0000471 MutexGuard locked(lock);
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000472 void *p = EEState.getGlobalAddressMap(locked)[GV];
Jeff Cohen68835dd2006-02-07 05:11:57 +0000473 if (p)
474 return p;
475
476 // Global variable might have been added since interpreter started.
477 if (GlobalVariable *GVar =
478 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
479 EmitGlobalVariable(GVar);
480 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000481 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +0000482 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000483}
484
Reid Spencer3da59db2006-11-27 01:05:10 +0000485/// This function converts a Constant* into a GenericValue. The interesting
486/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000487/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000488GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000489 // If its undefined, return the garbage.
Jay Foad5b370122010-01-15 08:32:58 +0000490 if (isa<UndefValue>(C)) {
491 GenericValue Result;
492 switch (C->getType()->getTypeID()) {
493 case Type::IntegerTyID:
494 case Type::X86_FP80TyID:
495 case Type::FP128TyID:
496 case Type::PPC_FP128TyID:
497 // Although the value is undefined, we still have to construct an APInt
498 // with the correct bit width.
499 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
500 break;
501 default:
502 break;
503 }
504 return Result;
505 }
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000506
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 // If the value is a ConstantExpr
508 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000509 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000510 switch (CE->getOpcode()) {
511 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000512 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000513 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000514 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000515 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000516 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000517
Reid Spencer8fb0f192007-03-06 03:04:04 +0000518 char* tmp = (char*) Result.PointerVal;
519 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000520 return Result;
521 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000522 case Instruction::Trunc: {
523 GenericValue GV = getConstantValue(Op0);
524 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
525 GV.IntVal = GV.IntVal.trunc(BitWidth);
526 return GV;
527 }
528 case Instruction::ZExt: {
529 GenericValue GV = getConstantValue(Op0);
530 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
531 GV.IntVal = GV.IntVal.zext(BitWidth);
532 return GV;
533 }
534 case Instruction::SExt: {
535 GenericValue GV = getConstantValue(Op0);
536 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
537 GV.IntVal = GV.IntVal.sext(BitWidth);
538 return GV;
539 }
540 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000541 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000542 GenericValue GV = getConstantValue(Op0);
543 GV.FloatVal = float(GV.DoubleVal);
544 return GV;
545 }
546 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000547 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000548 GenericValue GV = getConstantValue(Op0);
549 GV.DoubleVal = double(GV.FloatVal);
550 return GV;
551 }
552 case Instruction::UIToFP: {
553 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000554 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000555 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000556 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000557 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000558 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000559 const uint64_t zero[] = {0, 0};
560 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000561 (void)apf.convertFromAPInt(GV.IntVal,
562 false,
563 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000564 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000565 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000566 return GV;
567 }
568 case Instruction::SIToFP: {
569 GenericValue GV = getConstantValue(Op0);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000570 if (CE->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000571 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000572 else if (CE->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000573 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000574 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000575 const uint64_t zero[] = { 0, 0};
576 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000577 (void)apf.convertFromAPInt(GV.IntVal,
578 true,
579 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000580 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000581 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000582 return GV;
583 }
584 case Instruction::FPToUI: // double->APInt conversion handles sign
585 case Instruction::FPToSI: {
586 GenericValue GV = getConstantValue(Op0);
587 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000588 if (Op0->getType()->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000589 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000590 else if (Op0->getType()->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000591 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000592 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000593 APFloat apf = APFloat(GV.IntVal);
594 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000595 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000596 (void)apf.convertToInteger(&v, BitWidth,
597 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000598 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000599 GV.IntVal = v; // endian?
600 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000601 return GV;
602 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000603 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000604 GenericValue GV = getConstantValue(Op0);
605 uint32_t PtrWidth = TD->getPointerSizeInBits();
606 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
607 return GV;
608 }
609 case Instruction::IntToPtr: {
610 GenericValue GV = getConstantValue(Op0);
611 uint32_t PtrWidth = TD->getPointerSizeInBits();
612 if (PtrWidth != GV.IntVal.getBitWidth())
613 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
614 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
615 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000616 return GV;
617 }
618 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000619 GenericValue GV = getConstantValue(Op0);
620 const Type* DestTy = CE->getType();
621 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000622 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000623 case Type::IntegerTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000624 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000625 if (DestTy->isFloatTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000626 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000627 else if (DestTy->isDoubleTy())
Reid Spencerbce30f12007-03-06 22:23:15 +0000628 GV.DoubleVal = GV.IntVal.bitsToDouble();
629 break;
630 case Type::FloatTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000631 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000632 GV.IntVal.floatToBits(GV.FloatVal);
633 break;
634 case Type::DoubleTyID:
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000635 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000636 GV.IntVal.doubleToBits(GV.DoubleVal);
637 break;
638 case Type::PointerTyID:
Duncan Sands1df98592010-02-16 11:11:14 +0000639 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000640 break; // getConstantValue(Op0) above already converted it
641 }
642 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000643 }
Chris Lattner9a231222003-05-14 17:51:49 +0000644 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000645 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000646 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000647 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000648 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000649 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000650 case Instruction::UDiv:
651 case Instruction::SDiv:
652 case Instruction::URem:
653 case Instruction::SRem:
654 case Instruction::And:
655 case Instruction::Or:
656 case Instruction::Xor: {
657 GenericValue LHS = getConstantValue(Op0);
658 GenericValue RHS = getConstantValue(CE->getOperand(1));
659 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000660 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000661 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000662 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000664 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000665 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
666 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
667 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
668 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
669 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
670 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
671 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
672 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
673 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
674 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
675 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000676 break;
677 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000678 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000679 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000680 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000681 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000682 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000683 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000684 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000685 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
686 case Instruction::FDiv:
687 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
688 case Instruction::FRem:
689 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
690 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000691 break;
692 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000693 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000694 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000695 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000696 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000697 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000698 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000699 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000700 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
701 case Instruction::FDiv:
702 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
703 case Instruction::FRem:
704 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
705 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000706 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000707 case Type::X86_FP80TyID:
708 case Type::PPC_FP128TyID:
709 case Type::FP128TyID: {
710 APFloat apfLHS = APFloat(LHS.IntVal);
711 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000712 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000713 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000714 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000715 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000716 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000717 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000718 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000719 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000720 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000721 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000722 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000723 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000724 break;
725 case Instruction::FDiv:
726 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000727 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000728 break;
729 case Instruction::FRem:
730 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000731 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000732 break;
733 }
734 }
735 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000736 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000737 return GV;
738 }
Chris Lattner9a231222003-05-14 17:51:49 +0000739 default:
740 break;
741 }
Torok Edwin7d696d82009-07-11 13:10:19 +0000742 std::string msg;
743 raw_string_ostream Msg(msg);
744 Msg << "ConstantExpr not handled: " << *CE;
745 llvm_report_error(Msg.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000746 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000747
Reid Spencerbce30f12007-03-06 22:23:15 +0000748 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000749 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000750 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000751 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000752 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000753 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000754 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000755 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000756 case Type::X86_FP80TyID:
757 case Type::FP128TyID:
758 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000759 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000760 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000761 case Type::IntegerTyID:
762 Result.IntVal = cast<ConstantInt>(C)->getValue();
763 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000764 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000765 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000766 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000767 else if (const Function *F = dyn_cast<Function>(C))
768 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000769 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer40cf2f92004-07-18 00:41:27 +0000770 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattnerf32a6a32009-10-29 05:26:09 +0000771 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
772 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
773 BA->getBasicBlock())));
Reid Spencer40cf2f92004-07-18 00:41:27 +0000774 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000775 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000776 break;
777 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000778 std::string msg;
779 raw_string_ostream Msg(msg);
780 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
781 llvm_report_error(Msg.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000782 }
783 return Result;
784}
785
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000786/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
787/// with the integer held in IntVal.
788static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
789 unsigned StoreBytes) {
790 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
791 uint8_t *Src = (uint8_t *)IntVal.getRawData();
792
Chris Lattnerb67c9582009-01-22 19:53:00 +0000793 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000794 // Little-endian host - the source is ordered from LSB to MSB. Order the
795 // destination from LSB to MSB: Do a straight copy.
796 memcpy(Dst, Src, StoreBytes);
797 else {
798 // Big-endian host - the source is an array of 64 bit words ordered from
799 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
800 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
801 while (StoreBytes > sizeof(uint64_t)) {
802 StoreBytes -= sizeof(uint64_t);
803 // May not be aligned so use memcpy.
804 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
805 Src += sizeof(uint64_t);
806 }
807
808 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
809 }
810}
811
Nate Begeman37efe672006-04-22 18:53:45 +0000812/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
813/// is the address of the memory at which to store Val, cast to GenericValue *.
814/// It is not a pointer to a GenericValue containing the address at which to
815/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000816void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
817 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000818 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
819
Reid Spencer8fb0f192007-03-06 03:04:04 +0000820 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000821 case Type::IntegerTyID:
822 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000823 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000824 case Type::FloatTyID:
825 *((float*)Ptr) = Val.FloatVal;
826 break;
827 case Type::DoubleTyID:
828 *((double*)Ptr) = Val.DoubleVal;
829 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000830 case Type::X86_FP80TyID:
831 memcpy(Ptr, Val.IntVal.getRawData(), 10);
832 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000833 case Type::PointerTyID:
834 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
835 if (StoreBytes != sizeof(PointerTy))
836 memset(Ptr, 0, StoreBytes);
837
Reid Spencer8fb0f192007-03-06 03:04:04 +0000838 *((PointerTy*)Ptr) = Val.PointerVal;
839 break;
840 default:
David Greeneae7c59a2010-01-05 01:27:39 +0000841 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000842 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000843
Chris Lattnerb67c9582009-01-22 19:53:00 +0000844 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000845 // Host and target are different endian - reverse the stored bytes.
846 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
847}
848
849/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
850/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
851static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
852 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
853 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
854
Chris Lattnerb67c9582009-01-22 19:53:00 +0000855 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000856 // Little-endian host - the destination must be ordered from LSB to MSB.
857 // The source is ordered from LSB to MSB: Do a straight copy.
858 memcpy(Dst, Src, LoadBytes);
859 else {
860 // Big-endian - the destination is an array of 64 bit words ordered from
861 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
862 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
863 // a word.
864 while (LoadBytes > sizeof(uint64_t)) {
865 LoadBytes -= sizeof(uint64_t);
866 // May not be aligned so use memcpy.
867 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
868 Dst += sizeof(uint64_t);
869 }
870
871 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
872 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000873}
874
Misha Brukman4afac182003-10-10 17:45:12 +0000875/// FIXME: document
876///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000877void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000878 GenericValue *Ptr,
879 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000880 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000881
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000882 switch (Ty->getTypeID()) {
883 case Type::IntegerTyID:
884 // An APInt with all words initially zero.
885 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
886 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
887 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000888 case Type::FloatTyID:
889 Result.FloatVal = *((float*)Ptr);
890 break;
891 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000892 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000893 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000894 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000895 Result.PointerVal = *((PointerTy*)Ptr);
896 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000897 case Type::X86_FP80TyID: {
898 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000899 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000900 uint64_t y[2];
901 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000902 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000903 break;
904 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000905 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000906 std::string msg;
907 raw_string_ostream Msg(msg);
908 Msg << "Cannot load value of type " << *Ty << "!";
909 llvm_report_error(Msg.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000910 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000911}
912
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000913// InitializeMemory - Recursive function to apply a Constant value into the
914// specified memory location...
915//
916void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greeneae7c59a2010-01-05 01:27:39 +0000917 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000918 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000919 if (isa<UndefValue>(Init)) {
920 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000921 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000922 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000923 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000924 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
925 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
926 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000927 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000928 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000929 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000930 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
931 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000932 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000933 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
934 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
935 return;
936 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
937 const StructLayout *SL =
938 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
939 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
940 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
941 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000942 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000943 GenericValue Val = getConstantValue(Init);
944 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
945 return;
946 }
947
David Greeneae7c59a2010-01-05 01:27:39 +0000948 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000949 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000950}
951
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000952/// EmitGlobals - Emit all of the global variables to memory, storing their
953/// addresses into GlobalAddress. This must make sure to copy the contents of
954/// their initializers into the memory.
955///
956void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000957
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.
961 //
962 std::map<std::pair<std::string, const Type*>,
963 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000964
Chris Lattnerfe854032006-08-16 01:24:12 +0000965 if (Modules.size() != 1) {
966 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +0000967 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +0000968 for (Module::const_global_iterator I = M.global_begin(),
969 E = M.global_end(); I != E; ++I) {
970 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000971 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000972 GV->hasAppendingLinkage() || !GV->hasName())
973 continue;// Ignore external globals and globals with internal linkage.
974
975 const GlobalValue *&GVEntry =
976 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
977
978 // If this is the first time we've seen this global, it is the canonical
979 // version.
980 if (!GVEntry) {
981 GVEntry = GV;
982 continue;
983 }
984
985 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000986 if (GVEntry->hasExternalLinkage() ||
987 GVEntry->hasDLLImportLinkage() ||
988 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000989 continue;
990
991 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000992 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000993 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000994 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000995 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000996 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000997 }
998
999 std::vector<const GlobalValue*> NonCanonicalGlobals;
1000 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskinf0356fe2010-01-27 20:34:15 +00001001 Module &M = *Modules[m];
Chris Lattnerfe854032006-08-16 01:24:12 +00001002 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1003 I != E; ++I) {
1004 // In the multi-module case, see what this global maps to.
1005 if (!LinkedGlobalsMap.empty()) {
1006 if (const GlobalValue *GVEntry =
1007 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
1008 // If something else is the canonical global, ignore this one.
1009 if (GVEntry != &*I) {
1010 NonCanonicalGlobals.push_back(I);
1011 continue;
1012 }
1013 }
1014 }
1015
Reid Spencer5cbf9852007-01-30 20:08:39 +00001016 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001017 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +00001018 } else {
1019 // External variable reference. Try to use the dynamic loader to
1020 // get a pointer to it.
1021 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +00001022 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +00001023 addGlobalMapping(I, SymAddr);
1024 else {
Torok Edwin31e24662009-07-07 17:32:34 +00001025 llvm_report_error("Could not resolve external global address: "
1026 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001027 }
1028 }
1029 }
1030
1031 // If there are multiple modules, map the non-canonical globals to their
1032 // canonical location.
1033 if (!NonCanonicalGlobals.empty()) {
1034 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1035 const GlobalValue *GV = NonCanonicalGlobals[i];
1036 const GlobalValue *CGV =
1037 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1038 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1039 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001040 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001041 }
1042 }
1043
Reid Spencera54b7cb2007-01-12 07:05:14 +00001044 // Now that all of the globals are set up in memory, loop through them all
1045 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001046 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1047 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001048 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001049 if (!LinkedGlobalsMap.empty()) {
1050 if (const GlobalValue *GVEntry =
1051 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1052 if (GVEntry != &*I) // Not the canonical variable.
1053 continue;
1054 }
1055 EmitGlobalVariable(I);
1056 }
1057 }
1058 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001059}
1060
1061// EmitGlobalVariable - This method emits the specified global variable to the
1062// address specified in GlobalAddresses, or allocates new memory if it's not
1063// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001064void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001065 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001066
Chris Lattner24b0a182003-12-20 02:45:37 +00001067 if (GA == 0) {
1068 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001069 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001070 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001071 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001072
1073 // Don't initialize if it's thread local, let the client do it.
1074 if (!GV->isThreadLocal())
1075 InitializeMemory(GV->getInitializer(), GA);
1076
1077 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001078 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001079 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001080 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001081}
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001082
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001083ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1084 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001085}
1086
Jeffrey Yasskin23e5fcf2009-10-23 22:37:43 +00001087sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1088 ExecutionEngineState *EES) {
1089 return &EES->EE.lock;
1090}
1091void ExecutionEngineState::AddressMapConfig::onDelete(
1092 ExecutionEngineState *EES, const GlobalValue *Old) {
1093 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1094 EES->GlobalAddressReverseMap.erase(OldVal);
1095}
1096
1097void ExecutionEngineState::AddressMapConfig::onRAUW(
1098 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
Jeffrey Yasskin4c5b23b2009-10-13 17:42:08 +00001099 assert(false && "The ExecutionEngine doesn't know how to handle a"
1100 " RAUW on a value it has a global mapping for.");
1101}