blob: b2e2a04084c4642f283990116d8557cdf23636e3 [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattneree937c82003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattner996fe012002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman260b0c82003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattner996fe012002-12-24 00:01:05 +000020#include "llvm/Module.h"
Chris Lattnerad481312003-09-05 20:08:15 +000021#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner390d78b2009-08-23 22:49:13 +000022#include "llvm/ADT/Statistic.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Torok Edwin6c2d2332009-07-07 17:32:34 +000024#include "llvm/Support/ErrorHandling.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +000026#include "llvm/Support/ValueHandle.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000027#include "llvm/Support/raw_ostream.h"
Reid Spencer70e37272004-11-29 14:11:29 +000028#include "llvm/System/DynamicLibrary.h"
Duncan Sandsfde55672007-12-12 23:03:45 +000029#include "llvm/System/Host.h"
Reid Spencer70e37272004-11-29 14:11:29 +000030#include "llvm/Target/TargetData.h"
Anton Korobeynikov579f0712008-02-20 11:08:44 +000031#include <cmath>
32#include <cstring>
Chris Lattner29681de2003-11-19 21:08:57 +000033using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000034
Chris Lattnerc346ecd2006-12-19 22:43:32 +000035STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
36STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000037
Jeffrey Yasskin31faeff2010-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 Yasskin091217b2010-01-27 20:34:15 +000048ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M,
Reid Klecknerfc8a2d52009-07-18 00:42:18 +000049 std::string *ErrorStr) = 0;
Nicolas Geoffray21ad4942008-02-13 18:39:37 +000050ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
51
Chris Lattner2d52c1b2006-03-22 06:07:50 +000052
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000053ExecutionEngine::ExecutionEngine(Module *M)
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +000054 : EEState(*this),
55 LazyFunctionCreator(0) {
Jeffrey Yasskin4567db42009-10-27 20:30:28 +000056 CompilingLazily = false;
Evan Chengcdc00602008-09-24 16:25:55 +000057 GVCompilationDisabled = false;
Evan Cheng84a90552008-06-17 16:49:02 +000058 SymbolSearchingDisabled = false;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000059 Modules.push_back(M);
60 assert(M && "Module is null?");
Misha Brukman260b0c82003-10-16 21:18:05 +000061}
62
Brian Gaeke92f8b302003-09-04 22:57:27 +000063ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000064 clearAllGlobalMappings();
Chris Lattner0621cae2006-08-16 01:24:12 +000065 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
66 delete Modules[i];
Brian Gaeke92f8b302003-09-04 22:57:27 +000067}
68
Nicolas Geoffray5457ce92008-10-25 15:41:43 +000069char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
70 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000071 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray5457ce92008-10-25 15:41:43 +000072 return new char[GVSize];
73}
74
Jeffrey Yasskin091217b2010-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 Patel324fe892007-10-15 19:56:32 +000078 E = Modules.end(); I != E; ++I) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000079 Module *Found = *I;
80 if (Found == M) {
Devang Patel324fe892007-10-15 19:56:32 +000081 Modules.erase(I);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000082 clearGlobalMappingsFromModule(M);
83 return true;
Devang Patel324fe892007-10-15 19:56:32 +000084 }
85 }
Jeffrey Yasskin091217b2010-01-27 20:34:15 +000086 return false;
Nate Begeman617001d2009-01-23 19:27:28 +000087}
88
Chris Lattner0621cae2006-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 Yasskin091217b2010-01-27 20:34:15 +000094 if (Function *F = Modules[i]->getFunction(FnName))
Chris Lattner0621cae2006-08-16 01:24:12 +000095 return F;
96 }
97 return 0;
98}
99
100
Jeffrey Yasskin307c0532009-10-09 22:10:27 +0000101void *ExecutionEngineState::RemoveMapping(
102 const MutexGuard &, const GlobalValue *ToUnmap) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000103 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap);
Jeffrey Yasskin307c0532009-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 Lattner6d8dd182006-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 Cheng5cc53c32008-09-18 07:54:21 +0000123
David Greene0967d2d2010-01-05 01:27:39 +0000124 DEBUG(dbgs() << "JIT: Map \'" << GV->getName()
Daniel Dunbar9813b0b2009-07-26 07:49:05 +0000125 << "\' to [" << Addr << "]\n";);
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000126 void *&CurVal = EEState.getGlobalAddressMap(locked)[GV];
Chris Lattner6d8dd182006-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 Yasskinf98e9812009-10-13 17:42:08 +0000131 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000132 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000133 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattner6d8dd182006-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 Yasskinf98e9812009-10-13 17:42:08 +0000144 EEState.getGlobalAddressMap(locked).clear();
145 EEState.getGlobalAddressReverseMap(locked).clear();
Chris Lattner6d8dd182006-05-08 22:00:52 +0000146}
147
Nate Begeman8f83fc42008-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 Yasskinf98e9812009-10-13 17:42:08 +0000154 EEState.RemoveMapping(locked, FI);
Nate Begeman8f83fc42008-05-21 16:34:48 +0000155 }
156 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
157 GI != GE; ++GI) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000158 EEState.RemoveMapping(locked, GI);
Nate Begeman8f83fc42008-05-21 16:34:48 +0000159 }
160}
161
Chris Lattner6d8dd182006-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 Lattneree181732008-04-04 04:47:41 +0000165void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattner6d8dd182006-05-08 22:00:52 +0000166 MutexGuard locked(lock);
Chris Lattneree181732008-04-04 04:47:41 +0000167
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000168 ExecutionEngineState::GlobalAddressMapTy &Map =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000169 EEState.getGlobalAddressMap(locked);
Chris Lattneree181732008-04-04 04:47:41 +0000170
Chris Lattner6d8dd182006-05-08 22:00:52 +0000171 // Deleting from the mapping?
172 if (Addr == 0) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000173 return EEState.RemoveMapping(locked, GV);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000174 }
175
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000176 void *&CurVal = Map[GV];
Chris Lattneree181732008-04-04 04:47:41 +0000177 void *OldVal = CurVal;
178
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000179 if (CurVal && !EEState.getGlobalAddressReverseMap(locked).empty())
180 EEState.getGlobalAddressReverseMap(locked).erase(CurVal);
Chris Lattner6d8dd182006-05-08 22:00:52 +0000181 CurVal = Addr;
182
183 // If we are using the reverse mapping, add it too
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000184 if (!EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000185 AssertingVH<const GlobalValue> &V =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000186 EEState.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattner6d8dd182006-05-08 22:00:52 +0000187 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
188 V = GV;
189 }
Chris Lattneree181732008-04-04 04:47:41 +0000190 return OldVal;
Chris Lattner6d8dd182006-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 Yasskind0fc8f82009-10-23 22:37:43 +0000199 ExecutionEngineState::GlobalAddressMapTy::iterator I =
200 EEState.getGlobalAddressMap(locked).find(GV);
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000201 return I != EEState.getGlobalAddressMap(locked).end() ? I->second : 0;
Chris Lattner6d8dd182006-05-08 22:00:52 +0000202}
203
Chris Lattner748e8572003-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 Spencer79876f52005-07-12 15:51:55 +0000208 MutexGuard locked(lock);
209
Chris Lattner748e8572003-12-31 20:21:04 +0000210 // If we haven't computed the reverse mapping yet, do so first.
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000211 if (EEState.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000212 for (ExecutionEngineState::GlobalAddressMapTy::iterator
Jeffrey Yasskinf98e9812009-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 Lattner6d8dd182006-05-08 22:00:52 +0000216 I->first));
Chris Lattner748e8572003-12-31 20:21:04 +0000217 }
218
Jeffrey Yasskin6bf87df2009-08-07 19:54:29 +0000219 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +0000220 EEState.getGlobalAddressReverseMap(locked).find(Addr);
221 return I != EEState.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner748e8572003-12-31 20:21:04 +0000222}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000223
224// CreateArgv - Turn a vector of strings into a nice argv style array of
225// pointers to null terminated strings.
226//
Owen Anderson55f1c092009-08-13 21:58:54 +0000227static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Chris Lattner5a0d4822003-12-26 06:50:30 +0000228 const std::vector<std::string> &InputArgv) {
Owen Anderson20a631f2006-05-03 01:29:57 +0000229 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000230 char *Result = new char[(InputArgv.size()+1)*PtrSize];
231
David Greene0967d2d2010-01-05 01:27:39 +0000232 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Result << "\n");
Duncan Sands9ed7b162009-10-06 15:40:36 +0000233 const Type *SBytePtr = Type::getInt8PtrTy(C);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000234
235 for (unsigned i = 0; i != InputArgv.size(); ++i) {
236 unsigned Size = InputArgv[i].size()+1;
237 char *Dest = new char[Size];
David Greene0967d2d2010-01-05 01:27:39 +0000238 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukman835702a2005-04-21 22:36:52 +0000239
Chris Lattner5a0d4822003-12-26 06:50:30 +0000240 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
241 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000242
Chris Lattner5a0d4822003-12-26 06:50:30 +0000243 // Endian safe: Result[i] = (PointerTy)Dest;
244 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
245 SBytePtr);
246 }
247
248 // Null terminate it
249 EE->StoreValueToMemory(PTOGV(0),
250 (GenericValue*)(Result+InputArgv.size()*PtrSize),
251 SBytePtr);
252 return Result;
253}
254
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000255
256/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000257/// the static constructors or destructors for a module, depending on the
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000258/// value of isDtors.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000259void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
260 bool isDtors) {
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000261 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000262
Chris Lattner0621cae2006-08-16 01:24:12 +0000263 // Execute global ctors/dtors for each module in the program.
Chris Lattner0621cae2006-08-16 01:24:12 +0000264
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000265 GlobalVariable *GV = module->getNamedGlobal(Name);
266
267 // If this global has internal linkage, or if it has a use, then it must be
268 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
269 // this is the case, don't execute any of the global ctors, __main will do
270 // it.
Rafael Espindola6de96a12009-01-15 20:18:42 +0000271 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng1a9a0b72008-09-30 15:51:21 +0000272
273 // Should be an array of '{ int, void ()* }' structs. The first value is
274 // the init priority, which we ignore.
275 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
276 if (!InitList) return;
277 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
278 if (ConstantStruct *CS =
279 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
280 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
281
282 Constant *FP = CS->getOperand(1);
283 if (FP->isNullValue())
284 break; // Found a null terminator, exit.
285
286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
287 if (CE->isCast())
288 FP = CE->getOperand(0);
289 if (Function *F = dyn_cast<Function>(FP)) {
290 // Execute the ctor/dtor function!
291 runFunction(F, std::vector<GenericValue>());
292 }
293 }
294}
295
296/// runStaticConstructorsDestructors - This method is used to execute all of
297/// the static constructors or destructors for a program, depending on the
298/// value of isDtors.
299void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
300 // Execute global ctors/dtors for each module in the program.
301 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000302 runStaticConstructorsDestructors(Modules[m], isDtors);
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000303}
304
Dan Gohmancf3e3012008-08-26 01:38:29 +0000305#ifndef NDEBUG
Duncan Sands1202d1b2007-12-14 19:38:31 +0000306/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
307static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
308 unsigned PtrSize = EE->getTargetData()->getPointerSize();
309 for (unsigned i = 0; i < PtrSize; ++i)
310 if (*(i + (uint8_t*)Loc))
311 return false;
312 return true;
313}
Dan Gohmancf3e3012008-08-26 01:38:29 +0000314#endif
Duncan Sands1202d1b2007-12-14 19:38:31 +0000315
Chris Lattner5a0d4822003-12-26 06:50:30 +0000316/// runFunctionAsMain - This is a helper function which wraps runFunction to
317/// handle the common task of starting up main with the specified argc, argv,
318/// and envp parameters.
319int ExecutionEngine::runFunctionAsMain(Function *Fn,
320 const std::vector<std::string> &argv,
321 const char * const * envp) {
322 std::vector<GenericValue> GVArgs;
323 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000324 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000325
326 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000327 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000328 const FunctionType *FTy = Fn->getFunctionType();
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000329 const Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo();
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000330 switch (NumArgs) {
331 case 3:
332 if (FTy->getParamType(2) != PPInt8Ty) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000333 llvm_report_error("Invalid type for third argument of main() supplied");
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000334 }
Anton Korobeynikovb7818862007-06-03 19:20:49 +0000335 // FALLS THROUGH
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000336 case 2:
337 if (FTy->getParamType(1) != PPInt8Ty) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000338 llvm_report_error("Invalid type for second argument of main() supplied");
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000339 }
Anton Korobeynikovb7818862007-06-03 19:20:49 +0000340 // FALLS THROUGH
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000341 case 1:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000342 if (!FTy->getParamType(0)->isIntegerTy(32)) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000343 llvm_report_error("Invalid type for first argument of main() supplied");
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000344 }
Anton Korobeynikovb7818862007-06-03 19:20:49 +0000345 // FALLS THROUGH
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000346 case 0:
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 if (!FTy->getReturnType()->isIntegerTy() &&
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000348 !FTy->getReturnType()->isVoidTy()) {
Torok Edwinccb29cd2009-07-11 13:10:19 +0000349 llvm_report_error("Invalid return type of main() supplied");
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000350 }
351 break;
352 default:
Torok Edwinccb29cd2009-07-11 13:10:19 +0000353 llvm_report_error("Invalid number of arguments of main() supplied");
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000354 }
355
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000356 if (NumArgs) {
357 GVArgs.push_back(GVArgc); // Arg #0 = argc.
358 if (NumArgs > 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000359 // Arg #1 = argv.
360 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sands1202d1b2007-12-14 19:38:31 +0000361 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000362 "argv[0] was null after CreateArgv");
363 if (NumArgs > 2) {
364 std::vector<std::string> EnvVars;
365 for (unsigned i = 0; envp[i]; ++i)
366 EnvVars.push_back(envp[i]);
Owen Anderson55f1c092009-08-13 21:58:54 +0000367 // Arg #2 = envp.
368 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000369 }
370 }
371 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000372 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000373}
374
Misha Brukman260b0c82003-10-16 21:18:05 +0000375/// If possible, create a JIT, unless the caller specifically requests an
376/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukman835702a2005-04-21 22:36:52 +0000377/// NULL is returned.
Misha Brukman857c21b2003-10-10 17:45:12 +0000378///
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000379ExecutionEngine *ExecutionEngine::create(Module *M,
Reid Spencer603682a2007-03-03 18:19:18 +0000380 bool ForceInterpreter,
Evan Cheng7ff05bf2008-08-08 08:11:34 +0000381 std::string *ErrorStr,
Jeffrey Yasskin70415d92009-07-08 21:59:57 +0000382 CodeGenOpt::Level OptLevel,
383 bool GVsWithCode) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000384 return EngineBuilder(M)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000385 .setEngineKind(ForceInterpreter
386 ? EngineKind::Interpreter
387 : EngineKind::JIT)
388 .setErrorStr(ErrorStr)
389 .setOptLevel(OptLevel)
390 .setAllocateGVsWithCode(GVsWithCode)
391 .create();
392}
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000393
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000394ExecutionEngine *EngineBuilder::create() {
Nick Lewyckya53414f2008-03-08 02:49:45 +0000395 // Make sure we can resolve symbols in the program as well. The zero arg
396 // to the function tells DynamicLibrary to load the program, not a library.
397 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
398 return 0;
399
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000400 // If the user specified a memory manager but didn't specify which engine to
401 // create, we assume they only want the JIT, and we fail if they only want
402 // the interpreter.
403 if (JMM) {
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000404 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000405 WhichEngine = EngineKind::JIT;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000406 else {
Chris Lattner8bcc6442009-09-23 02:03:49 +0000407 if (ErrorStr)
408 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000409 return 0;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000410 }
411 }
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000412
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000413 // Unless the interpreter was explicitly selected or the JIT is not linked,
414 // try making a JIT.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000415 if (WhichEngine & EngineKind::JIT) {
416 if (ExecutionEngine::JITCtor) {
417 ExecutionEngine *EE =
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000418 ExecutionEngine::JITCtor(M, ErrorStr, JMM, OptLevel,
Jeffrey Yasskin31faeff2010-02-05 16:19:36 +0000419 AllocateGVsWithCode, CMModel,
420 MArch, MCPU, MAttrs);
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000421 if (EE) return EE;
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000422 }
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000423 }
424
425 // If we can't make a JIT and we didn't request one specifically, try making
426 // an interpreter instead.
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000427 if (WhichEngine & EngineKind::Interpreter) {
428 if (ExecutionEngine::InterpCtor)
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000429 return ExecutionEngine::InterpCtor(M, ErrorStr);
Chris Lattner8bcc6442009-09-23 02:03:49 +0000430 if (ErrorStr)
431 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000432 return 0;
Reid Klecknerfc8a2d52009-07-18 00:42:18 +0000433 }
Chris Lattner8bcc6442009-09-23 02:03:49 +0000434
435 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
436 if (ErrorStr)
437 *ErrorStr = "JIT has not been linked in.";
438 }
Chris Lattner41fa2bd2009-09-23 01:46:04 +0000439 return 0;
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000440}
441
Misha Brukman857c21b2003-10-10 17:45:12 +0000442/// getPointerToGlobal - This returns the address of the specified global
443/// value. This may involve code generation if it's a function.
444///
Chris Lattner996fe012002-12-24 00:01:05 +0000445void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000446 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000447 return getPointerToFunction(F);
448
Reid Spencer79876f52005-07-12 15:51:55 +0000449 MutexGuard locked(lock);
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000450 void *p = EEState.getGlobalAddressMap(locked)[GV];
Jeff Cohen69e849012006-02-07 05:11:57 +0000451 if (p)
452 return p;
453
454 // Global variable might have been added since interpreter started.
455 if (GlobalVariable *GVar =
456 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
457 EmitGlobalVariable(GVar);
458 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000459 llvm_unreachable("Global hasn't had an address allocated yet!");
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +0000460 return EEState.getGlobalAddressMap(locked)[GV];
Chris Lattner996fe012002-12-24 00:01:05 +0000461}
462
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000463/// This function converts a Constant* into a GenericValue. The interesting
464/// part is if C is a ConstantExpr.
Reid Spencer2dc9f132007-08-11 15:57:56 +0000465/// @brief Get a GenericValue for a Constant*
Chris Lattner996fe012002-12-24 00:01:05 +0000466GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000467 // If its undefined, return the garbage.
Jay Foadbcbdbfb2010-01-15 08:32:58 +0000468 if (isa<UndefValue>(C)) {
469 GenericValue Result;
470 switch (C->getType()->getTypeID()) {
471 case Type::IntegerTyID:
472 case Type::X86_FP80TyID:
473 case Type::FP128TyID:
474 case Type::PPC_FP128TyID:
475 // Although the value is undefined, we still have to construct an APInt
476 // with the correct bit width.
477 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0);
478 break;
479 default:
480 break;
481 }
482 return Result;
483 }
Chris Lattner9de0d142003-04-23 19:01:49 +0000484
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000485 // If the value is a ConstantExpr
486 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000487 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000488 switch (CE->getOpcode()) {
489 case Instruction::GetElementPtr: {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000490 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000491 GenericValue Result = getConstantValue(Op0);
Chris Lattnerc44bd782007-02-10 20:35:22 +0000492 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattner9de0d142003-04-23 19:01:49 +0000493 uint64_t Offset =
Reid Spencer4fd528f2007-03-06 22:23:15 +0000494 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukman835702a2005-04-21 22:36:52 +0000495
Reid Spencer87aa65f2007-03-06 03:04:04 +0000496 char* tmp = (char*) Result.PointerVal;
497 Result = PTOGV(tmp + Offset);
Chris Lattner9de0d142003-04-23 19:01:49 +0000498 return Result;
499 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000500 case Instruction::Trunc: {
501 GenericValue GV = getConstantValue(Op0);
502 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
503 GV.IntVal = GV.IntVal.trunc(BitWidth);
504 return GV;
505 }
506 case Instruction::ZExt: {
507 GenericValue GV = getConstantValue(Op0);
508 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
509 GV.IntVal = GV.IntVal.zext(BitWidth);
510 return GV;
511 }
512 case Instruction::SExt: {
513 GenericValue GV = getConstantValue(Op0);
514 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
515 GV.IntVal = GV.IntVal.sext(BitWidth);
516 return GV;
517 }
518 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000519 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000520 GenericValue GV = getConstantValue(Op0);
521 GV.FloatVal = float(GV.DoubleVal);
522 return GV;
523 }
524 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000525 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000526 GenericValue GV = getConstantValue(Op0);
527 GV.DoubleVal = double(GV.FloatVal);
528 return GV;
529 }
530 case Instruction::UIToFP: {
531 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000532 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000533 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000534 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000535 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000536 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000537 const uint64_t zero[] = {0, 0};
538 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohmanca24fd92008-02-29 01:27:13 +0000539 (void)apf.convertFromAPInt(GV.IntVal,
540 false,
541 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000542 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000543 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000544 return GV;
545 }
546 case Instruction::SIToFP: {
547 GenericValue GV = getConstantValue(Op0);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000548 if (CE->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000549 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattnerfdd87902009-10-05 05:54:46 +0000550 else if (CE->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000551 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000552 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000553 const uint64_t zero[] = { 0, 0};
554 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohmanca24fd92008-02-29 01:27:13 +0000555 (void)apf.convertFromAPInt(GV.IntVal,
556 true,
557 APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000558 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000559 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000560 return GV;
561 }
562 case Instruction::FPToUI: // double->APInt conversion handles sign
563 case Instruction::FPToSI: {
564 GenericValue GV = getConstantValue(Op0);
565 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000566 if (Op0->getType()->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000567 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000568 else if (Op0->getType()->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000569 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattnerfdd87902009-10-05 05:54:46 +0000570 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000571 APFloat apf = APFloat(GV.IntVal);
572 uint64_t v;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000573 bool ignored;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000574 (void)apf.convertToInteger(&v, BitWidth,
575 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000576 APFloat::rmTowardZero, &ignored);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000577 GV.IntVal = v; // endian?
578 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000579 return GV;
580 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000581 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000582 GenericValue GV = getConstantValue(Op0);
583 uint32_t PtrWidth = TD->getPointerSizeInBits();
584 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
585 return GV;
586 }
587 case Instruction::IntToPtr: {
588 GenericValue GV = getConstantValue(Op0);
589 uint32_t PtrWidth = TD->getPointerSizeInBits();
590 if (PtrWidth != GV.IntVal.getBitWidth())
591 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
592 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
593 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000594 return GV;
595 }
596 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000597 GenericValue GV = getConstantValue(Op0);
598 const Type* DestTy = CE->getType();
599 switch (Op0->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000600 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000601 case Type::IntegerTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000602 assert(DestTy->isFloatingPointTy() && "invalid bitcast");
Chris Lattnerfdd87902009-10-05 05:54:46 +0000603 if (DestTy->isFloatTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000604 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattnerfdd87902009-10-05 05:54:46 +0000605 else if (DestTy->isDoubleTy())
Reid Spencer4fd528f2007-03-06 22:23:15 +0000606 GV.DoubleVal = GV.IntVal.bitsToDouble();
607 break;
608 case Type::FloatTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000609 assert(DestTy->isIntegerTy(32) && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000610 GV.IntVal.floatToBits(GV.FloatVal);
611 break;
612 case Type::DoubleTyID:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000613 assert(DestTy->isIntegerTy(64) && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000614 GV.IntVal.doubleToBits(GV.DoubleVal);
615 break;
616 case Type::PointerTyID:
Duncan Sands19d0b472010-02-16 11:11:14 +0000617 assert(DestTy->isPointerTy() && "Invalid bitcast");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000618 break; // getConstantValue(Op0) above already converted it
619 }
620 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000621 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000622 case Instruction::Add:
Dan Gohmana5b96452009-06-04 22:49:04 +0000623 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000624 case Instruction::Sub:
Dan Gohmana5b96452009-06-04 22:49:04 +0000625 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000626 case Instruction::Mul:
Dan Gohmana5b96452009-06-04 22:49:04 +0000627 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000628 case Instruction::UDiv:
629 case Instruction::SDiv:
630 case Instruction::URem:
631 case Instruction::SRem:
632 case Instruction::And:
633 case Instruction::Or:
634 case Instruction::Xor: {
635 GenericValue LHS = getConstantValue(Op0);
636 GenericValue RHS = getConstantValue(CE->getOperand(1));
637 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000638 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000639 default: llvm_unreachable("Bad add type!");
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000640 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000641 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000642 default: llvm_unreachable("Invalid integer opcode");
Reid Spencer4fd528f2007-03-06 22:23:15 +0000643 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
644 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
645 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
646 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
647 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
648 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
649 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
650 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
651 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
652 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
653 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000654 break;
655 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000656 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000657 default: llvm_unreachable("Invalid float opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000658 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000659 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000660 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000661 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000662 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000663 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
664 case Instruction::FDiv:
665 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
666 case Instruction::FRem:
667 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
668 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000669 break;
670 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000671 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000672 default: llvm_unreachable("Invalid double opcode");
Dan Gohmana5b96452009-06-04 22:49:04 +0000673 case Instruction::FAdd:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000674 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000675 case Instruction::FSub:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000676 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000677 case Instruction::FMul:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000678 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
679 case Instruction::FDiv:
680 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
681 case Instruction::FRem:
682 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
683 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000684 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000685 case Type::X86_FP80TyID:
686 case Type::PPC_FP128TyID:
687 case Type::FP128TyID: {
688 APFloat apfLHS = APFloat(LHS.IntVal);
689 switch (CE->getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000690 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmana5b96452009-06-04 22:49:04 +0000691 case Instruction::FAdd:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000692 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000693 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000694 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000695 case Instruction::FSub:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000696 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000697 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000698 break;
Dan Gohmana5b96452009-06-04 22:49:04 +0000699 case Instruction::FMul:
Dale Johannesena1336cf2007-09-17 18:44:13 +0000700 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000701 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000702 break;
703 case Instruction::FDiv:
704 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000705 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000706 break;
707 case Instruction::FRem:
708 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen54306fe2008-10-09 18:53:47 +0000709 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000710 break;
711 }
712 }
713 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000714 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000715 return GV;
716 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000717 default:
718 break;
719 }
Torok Edwinccb29cd2009-07-11 13:10:19 +0000720 std::string msg;
721 raw_string_ostream Msg(msg);
722 Msg << "ConstantExpr not handled: " << *CE;
723 llvm_report_error(Msg.str());
Chris Lattner68cbcc32003-05-14 17:51:49 +0000724 }
Misha Brukman835702a2005-04-21 22:36:52 +0000725
Reid Spencer4fd528f2007-03-06 22:23:15 +0000726 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000727 switch (C->getType()->getTypeID()) {
Reid Spencer87aa65f2007-03-06 03:04:04 +0000728 case Type::FloatTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000729 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000730 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000731 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000732 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000733 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000734 case Type::X86_FP80TyID:
735 case Type::FP128TyID:
736 case Type::PPC_FP128TyID:
Dale Johannesen54306fe2008-10-09 18:53:47 +0000737 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000738 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000739 case Type::IntegerTyID:
740 Result.IntVal = cast<ConstantInt>(C)->getValue();
741 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000742 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000743 if (isa<ConstantPointerNull>(C))
Chris Lattner996fe012002-12-24 00:01:05 +0000744 Result.PointerVal = 0;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000745 else if (const Function *F = dyn_cast<Function>(C))
746 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000747 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
Reid Spencer6a0fd732004-07-18 00:41:27 +0000748 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
Chris Lattner0c778f72009-10-29 05:26:09 +0000749 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
750 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>(
751 BA->getBasicBlock())));
Reid Spencer6a0fd732004-07-18 00:41:27 +0000752 else
Torok Edwinfbcc6632009-07-14 16:55:14 +0000753 llvm_unreachable("Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000754 break;
755 default:
Torok Edwinccb29cd2009-07-11 13:10:19 +0000756 std::string msg;
757 raw_string_ostream Msg(msg);
758 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
759 llvm_report_error(Msg.str());
Chris Lattner996fe012002-12-24 00:01:05 +0000760 }
761 return Result;
762}
763
Duncan Sands1202d1b2007-12-14 19:38:31 +0000764/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
765/// with the integer held in IntVal.
766static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
767 unsigned StoreBytes) {
768 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
769 uint8_t *Src = (uint8_t *)IntVal.getRawData();
770
Chris Lattneraa121222009-01-22 19:53:00 +0000771 if (sys::isLittleEndianHost())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000772 // Little-endian host - the source is ordered from LSB to MSB. Order the
773 // destination from LSB to MSB: Do a straight copy.
774 memcpy(Dst, Src, StoreBytes);
775 else {
776 // Big-endian host - the source is an array of 64 bit words ordered from
777 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
778 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
779 while (StoreBytes > sizeof(uint64_t)) {
780 StoreBytes -= sizeof(uint64_t);
781 // May not be aligned so use memcpy.
782 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
783 Src += sizeof(uint64_t);
784 }
785
786 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
787 }
788}
789
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000790/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
791/// is the address of the memory at which to store Val, cast to GenericValue *.
792/// It is not a pointer to a GenericValue containing the address at which to
793/// store Val.
Evan Cheng09053e62008-11-04 06:10:31 +0000794void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
795 GenericValue *Ptr, const Type *Ty) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000796 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
797
Reid Spencer87aa65f2007-03-06 03:04:04 +0000798 switch (Ty->getTypeID()) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000799 case Type::IntegerTyID:
800 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000801 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000802 case Type::FloatTyID:
803 *((float*)Ptr) = Val.FloatVal;
804 break;
805 case Type::DoubleTyID:
806 *((double*)Ptr) = Val.DoubleVal;
807 break;
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000808 case Type::X86_FP80TyID:
809 memcpy(Ptr, Val.IntVal.getRawData(), 10);
810 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000811 case Type::PointerTyID:
812 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
813 if (StoreBytes != sizeof(PointerTy))
814 memset(Ptr, 0, StoreBytes);
815
Reid Spencer87aa65f2007-03-06 03:04:04 +0000816 *((PointerTy*)Ptr) = Val.PointerVal;
817 break;
818 default:
David Greene0967d2d2010-01-05 01:27:39 +0000819 dbgs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattner996fe012002-12-24 00:01:05 +0000820 }
Duncan Sands1202d1b2007-12-14 19:38:31 +0000821
Chris Lattneraa121222009-01-22 19:53:00 +0000822 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000823 // Host and target are different endian - reverse the stored bytes.
824 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
825}
826
827/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
828/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
829static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
830 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
831 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
832
Chris Lattneraa121222009-01-22 19:53:00 +0000833 if (sys::isLittleEndianHost())
Duncan Sands1202d1b2007-12-14 19:38:31 +0000834 // Little-endian host - the destination must be ordered from LSB to MSB.
835 // The source is ordered from LSB to MSB: Do a straight copy.
836 memcpy(Dst, Src, LoadBytes);
837 else {
838 // Big-endian - the destination is an array of 64 bit words ordered from
839 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
840 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
841 // a word.
842 while (LoadBytes > sizeof(uint64_t)) {
843 LoadBytes -= sizeof(uint64_t);
844 // May not be aligned so use memcpy.
845 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
846 Dst += sizeof(uint64_t);
847 }
848
849 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
850 }
Chris Lattner996fe012002-12-24 00:01:05 +0000851}
852
Misha Brukman857c21b2003-10-10 17:45:12 +0000853/// FIXME: document
854///
Duncan Sands1202d1b2007-12-14 19:38:31 +0000855void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandscd4a6be2008-03-10 16:38:37 +0000856 GenericValue *Ptr,
857 const Type *Ty) {
Duncan Sands1202d1b2007-12-14 19:38:31 +0000858 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands5c65cb42007-12-10 17:43:13 +0000859
Duncan Sands1202d1b2007-12-14 19:38:31 +0000860 switch (Ty->getTypeID()) {
861 case Type::IntegerTyID:
862 // An APInt with all words initially zero.
863 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
864 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
865 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000866 case Type::FloatTyID:
867 Result.FloatVal = *((float*)Ptr);
868 break;
869 case Type::DoubleTyID:
Duncan Sands1202d1b2007-12-14 19:38:31 +0000870 Result.DoubleVal = *((double*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000871 break;
Duncan Sands1202d1b2007-12-14 19:38:31 +0000872 case Type::PointerTyID:
Reid Spencer87aa65f2007-03-06 03:04:04 +0000873 Result.PointerVal = *((PointerTy*)Ptr);
874 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000875 case Type::X86_FP80TyID: {
876 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands26d65392007-12-15 17:37:40 +0000877 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen4d7e4ee2009-03-24 18:16:17 +0000878 uint64_t y[2];
879 memcpy(y, Ptr, 10);
Duncan Sandsff306282007-11-28 10:36:19 +0000880 Result.IntVal = APInt(80, 2, y);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000881 break;
882 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000883 default:
Torok Edwinccb29cd2009-07-11 13:10:19 +0000884 std::string msg;
885 raw_string_ostream Msg(msg);
886 Msg << "Cannot load value of type " << *Ty << "!";
887 llvm_report_error(Msg.str());
Chris Lattner7f389e82003-05-08 16:52:16 +0000888 }
Chris Lattner7f389e82003-05-08 16:52:16 +0000889}
890
Chris Lattner996fe012002-12-24 00:01:05 +0000891// InitializeMemory - Recursive function to apply a Constant value into the
892// specified memory location...
893//
894void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
David Greene0967d2d2010-01-05 01:27:39 +0000895 DEBUG(dbgs() << "JIT: Initializing " << Addr << " ");
Dale Johannesenb086d382008-08-07 01:30:15 +0000896 DEBUG(Init->dump());
Chris Lattner61753bf2004-10-16 18:19:26 +0000897 if (isa<UndefValue>(Init)) {
898 return;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000899 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +0000900 unsigned ElementSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000901 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +0000902 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
903 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
904 return;
Chris Lattner1dd86b12008-02-15 00:57:28 +0000905 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000906 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattner1dd86b12008-02-15 00:57:28 +0000907 return;
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000908 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
909 unsigned ElementSize =
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000910 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman69ddfbf2008-05-20 03:20:09 +0000911 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
912 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
913 return;
914 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
915 const StructLayout *SL =
916 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
917 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
918 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
919 return;
Chris Lattner61753bf2004-10-16 18:19:26 +0000920 } else if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +0000921 GenericValue Val = getConstantValue(Init);
922 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
923 return;
924 }
925
David Greene0967d2d2010-01-05 01:27:39 +0000926 dbgs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinfbcc6632009-07-14 16:55:14 +0000927 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattner996fe012002-12-24 00:01:05 +0000928}
929
Chris Lattner996fe012002-12-24 00:01:05 +0000930/// EmitGlobals - Emit all of the global variables to memory, storing their
931/// addresses into GlobalAddress. This must make sure to copy the contents of
932/// their initializers into the memory.
933///
934void ExecutionEngine::emitGlobals() {
Misha Brukman835702a2005-04-21 22:36:52 +0000935
Chris Lattner996fe012002-12-24 00:01:05 +0000936 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +0000937 // to hold them. If there is more than one module, do a prepass over globals
938 // to figure out how the different modules should link together.
939 //
940 std::map<std::pair<std::string, const Type*>,
941 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +0000942
Chris Lattner0621cae2006-08-16 01:24:12 +0000943 if (Modules.size() != 1) {
944 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000945 Module &M = *Modules[m];
Chris Lattner0621cae2006-08-16 01:24:12 +0000946 for (Module::const_global_iterator I = M.global_begin(),
947 E = M.global_end(); I != E; ++I) {
948 const GlobalValue *GV = I;
Rafael Espindola6de96a12009-01-15 20:18:42 +0000949 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattner0621cae2006-08-16 01:24:12 +0000950 GV->hasAppendingLinkage() || !GV->hasName())
951 continue;// Ignore external globals and globals with internal linkage.
952
953 const GlobalValue *&GVEntry =
954 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
955
956 // If this is the first time we've seen this global, it is the canonical
957 // version.
958 if (!GVEntry) {
959 GVEntry = GV;
960 continue;
961 }
962
963 // If the existing global is strong, never replace it.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000964 if (GVEntry->hasExternalLinkage() ||
965 GVEntry->hasDLLImportLinkage() ||
966 GVEntry->hasDLLExportLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +0000967 continue;
968
969 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesence4396b2008-05-14 20:12:51 +0000970 // symbol. FIXME is this right for common?
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000971 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +0000972 GVEntry = GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000973 }
Chris Lattner996fe012002-12-24 00:01:05 +0000974 }
Chris Lattner0621cae2006-08-16 01:24:12 +0000975 }
976
977 std::vector<const GlobalValue*> NonCanonicalGlobals;
978 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +0000979 Module &M = *Modules[m];
Chris Lattner0621cae2006-08-16 01:24:12 +0000980 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
981 I != E; ++I) {
982 // In the multi-module case, see what this global maps to.
983 if (!LinkedGlobalsMap.empty()) {
984 if (const GlobalValue *GVEntry =
985 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
986 // If something else is the canonical global, ignore this one.
987 if (GVEntry != &*I) {
988 NonCanonicalGlobals.push_back(I);
989 continue;
990 }
991 }
992 }
993
Reid Spencer5301e7c2007-01-30 20:08:39 +0000994 if (!I->isDeclaration()) {
Nicolas Geoffray5457ce92008-10-25 15:41:43 +0000995 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattner0621cae2006-08-16 01:24:12 +0000996 } else {
997 // External variable reference. Try to use the dynamic loader to
998 // get a pointer to it.
999 if (void *SymAddr =
Daniel Dunbar5899e342009-07-21 08:54:24 +00001000 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattner0621cae2006-08-16 01:24:12 +00001001 addGlobalMapping(I, SymAddr);
1002 else {
Torok Edwin6c2d2332009-07-07 17:32:34 +00001003 llvm_report_error("Could not resolve external global address: "
1004 +I->getName());
Chris Lattner0621cae2006-08-16 01:24:12 +00001005 }
1006 }
1007 }
1008
1009 // If there are multiple modules, map the non-canonical globals to their
1010 // canonical location.
1011 if (!NonCanonicalGlobals.empty()) {
1012 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1013 const GlobalValue *GV = NonCanonicalGlobals[i];
1014 const GlobalValue *CGV =
1015 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1016 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1017 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesa67f06b2008-10-14 10:04:52 +00001018 addGlobalMapping(GV, Ptr);
Chris Lattner0621cae2006-08-16 01:24:12 +00001019 }
1020 }
1021
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001022 // Now that all of the globals are set up in memory, loop through them all
1023 // and initialize their contents.
Chris Lattner0621cae2006-08-16 01:24:12 +00001024 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1025 I != E; ++I) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001026 if (!I->isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +00001027 if (!LinkedGlobalsMap.empty()) {
1028 if (const GlobalValue *GVEntry =
1029 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1030 if (GVEntry != &*I) // Not the canonical variable.
1031 continue;
1032 }
1033 EmitGlobalVariable(I);
1034 }
1035 }
1036 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001037}
1038
1039// EmitGlobalVariable - This method emits the specified global variable to the
1040// address specified in GlobalAddresses, or allocates new memory if it's not
1041// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +00001042void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +00001043 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattnerdc631732004-02-08 19:33:23 +00001044
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001045 if (GA == 0) {
1046 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001047 GA = getMemoryForGV(GV);
Chris Lattner748e8572003-12-31 20:21:04 +00001048 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001049 }
Nicolas Geoffray5457ce92008-10-25 15:41:43 +00001050
1051 // Don't initialize if it's thread local, let the client do it.
1052 if (!GV->isThreadLocal())
1053 InitializeMemory(GV->getInitializer(), GA);
1054
1055 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001056 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattnerdf1f1522005-01-08 20:13:19 +00001057 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +00001058 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +00001059}
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001060
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001061ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE)
1062 : EE(EE), GlobalAddressMap(this) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001063}
1064
Jeffrey Yasskind0fc8f82009-10-23 22:37:43 +00001065sys::Mutex *ExecutionEngineState::AddressMapConfig::getMutex(
1066 ExecutionEngineState *EES) {
1067 return &EES->EE.lock;
1068}
1069void ExecutionEngineState::AddressMapConfig::onDelete(
1070 ExecutionEngineState *EES, const GlobalValue *Old) {
1071 void *OldVal = EES->GlobalAddressMap.lookup(Old);
1072 EES->GlobalAddressReverseMap.erase(OldVal);
1073}
1074
1075void ExecutionEngineState::AddressMapConfig::onRAUW(
1076 ExecutionEngineState *, const GlobalValue *, const GlobalValue *) {
Jeffrey Yasskinf98e9812009-10-13 17:42:08 +00001077 assert(false && "The ExecutionEngine doesn't know how to handle a"
1078 " RAUW on a value it has a global mapping for.");
1079}