blob: 8b94ad02840dc8e6fbe386c22601ab7e685f01c2 [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"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000016#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Module.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/ModuleProvider.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000020#include "llvm/ADT/Statistic.h"
Duncan Sands8a43e9e2007-12-14 19:38:31 +000021#include "llvm/Config/alloca.h"
Misha Brukman19684162003-10-16 21:18:05 +000022#include "llvm/ExecutionEngine/ExecutionEngine.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000023#include "llvm/ExecutionEngine/GenericValue.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000025#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000026#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000027#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000028#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000029#include <cmath>
30#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000031using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000032
Chris Lattner36343732006-12-19 22:43:32 +000033STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
34STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner2fe4bb02006-03-22 06:07:50 +000036ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
37ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000038ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
39
Chris Lattner2fe4bb02006-03-22 06:07:50 +000040
Chris Lattnerd958a5a2007-10-22 02:50:12 +000041ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000042 LazyCompilationDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000043 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000044 assert(P && "ModuleProvider is null?");
45}
46
Brian Gaeke8e539482003-09-04 22:57:27 +000047ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000048 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000049 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
50 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000051}
52
Devang Patel73d0e212007-10-15 19:56:32 +000053/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
54/// Release module from ModuleProvider.
55Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
56 std::string *ErrInfo) {
57 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
58 E = Modules.end(); I != E; ++I) {
59 ModuleProvider *MP = *I;
60 if (MP == P) {
61 Modules.erase(I);
Nate Begemanf049e072008-05-21 16:34:48 +000062 clearGlobalMappingsFromModule(MP->getModule());
Devang Patel73d0e212007-10-15 19:56:32 +000063 return MP->releaseModule(ErrInfo);
64 }
65 }
66 return NULL;
67}
68
Chris Lattnerfe854032006-08-16 01:24:12 +000069/// FindFunctionNamed - Search all of the active modules to find the one that
70/// defines FnName. This is very slow operation and shouldn't be used for
71/// general code.
72Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
73 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000074 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000075 return F;
76 }
77 return 0;
78}
79
80
Chris Lattnere7fd5532006-05-08 22:00:52 +000081/// addGlobalMapping - Tell the execution engine that the specified global is
82/// at the specified location. This is used internally as functions are JIT'd
83/// and as global variables are laid out in memory. It can and should also be
84/// used by clients of the EE that want to have an LLVM global overlay
85/// existing data in memory.
86void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
87 MutexGuard locked(lock);
88
89 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
90 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
91 CurVal = Addr;
92
93 // If we are using the reverse mapping, add it too
94 if (!state.getGlobalAddressReverseMap(locked).empty()) {
95 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
96 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
97 V = GV;
98 }
99}
100
101/// clearAllGlobalMappings - Clear all global mappings and start over again
102/// use in dynamic compilation scenarios when you want to move globals
103void ExecutionEngine::clearAllGlobalMappings() {
104 MutexGuard locked(lock);
105
106 state.getGlobalAddressMap(locked).clear();
107 state.getGlobalAddressReverseMap(locked).clear();
108}
109
Nate Begemanf049e072008-05-21 16:34:48 +0000110/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
111/// particular module, because it has been removed from the JIT.
112void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
113 MutexGuard locked(lock);
114
115 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
116 state.getGlobalAddressMap(locked).erase(FI);
117 state.getGlobalAddressReverseMap(locked).erase(FI);
118 }
119 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
120 GI != GE; ++GI) {
121 state.getGlobalAddressMap(locked).erase(GI);
122 state.getGlobalAddressReverseMap(locked).erase(GI);
123 }
124}
125
Chris Lattnere7fd5532006-05-08 22:00:52 +0000126/// updateGlobalMapping - Replace an existing mapping for GV with a new
127/// address. This updates both maps as required. If "Addr" is null, the
128/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000129void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000130 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000131
132 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
133
Chris Lattnere7fd5532006-05-08 22:00:52 +0000134 // Deleting from the mapping?
135 if (Addr == 0) {
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000136 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
137 void *OldVal;
138 if (I == Map.end())
139 OldVal = 0;
140 else {
141 OldVal = I->second;
142 Map.erase(I);
143 }
144
Chris Lattnere7fd5532006-05-08 22:00:52 +0000145 if (!state.getGlobalAddressReverseMap(locked).empty())
146 state.getGlobalAddressReverseMap(locked).erase(Addr);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000147 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000148 }
149
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000150 void *&CurVal = Map[GV];
151 void *OldVal = CurVal;
152
Chris Lattnere7fd5532006-05-08 22:00:52 +0000153 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
154 state.getGlobalAddressReverseMap(locked).erase(CurVal);
155 CurVal = Addr;
156
157 // If we are using the reverse mapping, add it too
158 if (!state.getGlobalAddressReverseMap(locked).empty()) {
159 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
160 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
161 V = GV;
162 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000163 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000164}
165
166/// getPointerToGlobalIfAvailable - This returns the address of the specified
167/// global value if it is has already been codegen'd, otherwise it returns null.
168///
169void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
170 MutexGuard locked(lock);
171
172 std::map<const GlobalValue*, void*>::iterator I =
173 state.getGlobalAddressMap(locked).find(GV);
174 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
175}
176
Chris Lattner55d86482003-12-31 20:21:04 +0000177/// getGlobalValueAtAddress - Return the LLVM global value object that starts
178/// at the specified address.
179///
180const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000181 MutexGuard locked(lock);
182
Chris Lattner55d86482003-12-31 20:21:04 +0000183 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000184 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000185 for (std::map<const GlobalValue*, void *>::iterator
186 I = state.getGlobalAddressMap(locked).begin(),
187 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
188 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
189 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000190 }
191
192 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000193 state.getGlobalAddressReverseMap(locked).find(Addr);
194 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000195}
Chris Lattner87f03102003-12-26 06:50:30 +0000196
197// CreateArgv - Turn a vector of strings into a nice argv style array of
198// pointers to null terminated strings.
199//
200static void *CreateArgv(ExecutionEngine *EE,
201 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000202 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000203 char *Result = new char[(InputArgv.size()+1)*PtrSize];
204
Bill Wendling480f0932006-11-27 23:54:50 +0000205 DOUT << "ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000206 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000207
208 for (unsigned i = 0; i != InputArgv.size(); ++i) {
209 unsigned Size = InputArgv[i].size()+1;
210 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000211 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000212
Chris Lattner87f03102003-12-26 06:50:30 +0000213 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
214 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000215
Chris Lattner87f03102003-12-26 06:50:30 +0000216 // Endian safe: Result[i] = (PointerTy)Dest;
217 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
218 SBytePtr);
219 }
220
221 // Null terminate it
222 EE->StoreValueToMemory(PTOGV(0),
223 (GenericValue*)(Result+InputArgv.size()*PtrSize),
224 SBytePtr);
225 return Result;
226}
227
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000228
229/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000230/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000231/// value of isDtors.
232void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
233 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000234
Chris Lattnerfe854032006-08-16 01:24:12 +0000235 // Execute global ctors/dtors for each module in the program.
236 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
237 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
238
239 // If this global has internal linkage, or if it has a use, then it must be
240 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
241 // this is the case, don't execute any of the global ctors, __main will do
242 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000243 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000244
245 // Should be an array of '{ int, void ()* }' structs. The first value is
246 // the init priority, which we ignore.
247 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
248 if (!InitList) continue;
249 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
250 if (ConstantStruct *CS =
251 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
252 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000253
Chris Lattnerfe854032006-08-16 01:24:12 +0000254 Constant *FP = CS->getOperand(1);
255 if (FP->isNullValue())
256 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000257
Chris Lattnerfe854032006-08-16 01:24:12 +0000258 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000259 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000260 FP = CE->getOperand(0);
261 if (Function *F = dyn_cast<Function>(FP)) {
262 // Execute the ctor/dtor function!
263 runFunction(F, std::vector<GenericValue>());
264 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000265 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000266 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000267}
268
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000269/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
270static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
271 unsigned PtrSize = EE->getTargetData()->getPointerSize();
272 for (unsigned i = 0; i < PtrSize; ++i)
273 if (*(i + (uint8_t*)Loc))
274 return false;
275 return true;
276}
277
Chris Lattner87f03102003-12-26 06:50:30 +0000278/// runFunctionAsMain - This is a helper function which wraps runFunction to
279/// handle the common task of starting up main with the specified argc, argv,
280/// and envp parameters.
281int ExecutionEngine::runFunctionAsMain(Function *Fn,
282 const std::vector<std::string> &argv,
283 const char * const * envp) {
284 std::vector<GenericValue> GVArgs;
285 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000286 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000287
288 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000289 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000290 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000291 const Type* PPInt8Ty =
292 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000293 switch (NumArgs) {
294 case 3:
295 if (FTy->getParamType(2) != PPInt8Ty) {
296 cerr << "Invalid type for third argument of main() supplied\n";
297 abort();
298 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000299 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000300 case 2:
301 if (FTy->getParamType(1) != PPInt8Ty) {
302 cerr << "Invalid type for second argument of main() supplied\n";
303 abort();
304 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000305 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000306 case 1:
307 if (FTy->getParamType(0) != Type::Int32Ty) {
308 cerr << "Invalid type for first argument of main() supplied\n";
309 abort();
310 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000311 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000312 case 0:
313 if (FTy->getReturnType() != Type::Int32Ty &&
314 FTy->getReturnType() != Type::VoidTy) {
315 cerr << "Invalid return type of main() supplied\n";
316 abort();
317 }
318 break;
319 default:
320 cerr << "Invalid number of arguments of main() supplied\n";
321 abort();
322 }
323
Chris Lattnerf24d0992004-08-16 01:05:35 +0000324 if (NumArgs) {
325 GVArgs.push_back(GVArgc); // Arg #0 = argc.
326 if (NumArgs > 1) {
327 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000328 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000329 "argv[0] was null after CreateArgv");
330 if (NumArgs > 2) {
331 std::vector<std::string> EnvVars;
332 for (unsigned i = 0; envp[i]; ++i)
333 EnvVars.push_back(envp[i]);
334 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
335 }
336 }
337 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000338 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000339}
340
Misha Brukman19684162003-10-16 21:18:05 +0000341/// If possible, create a JIT, unless the caller specifically requests an
342/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000343/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000344///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000345ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000346 bool ForceInterpreter,
347 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000348 ExecutionEngine *EE = 0;
349
Nick Lewycky6456d862008-03-08 02:49:45 +0000350 // Make sure we can resolve symbols in the program as well. The zero arg
351 // to the function tells DynamicLibrary to load the program, not a library.
352 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
353 return 0;
354
Chris Lattner73011782003-12-28 09:44:37 +0000355 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000356 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000357 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000358
359 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000360 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000361 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000362
Brian Gaeke82d82772003-09-03 20:34:19 +0000363 return EE;
364}
365
Chris Lattner8b5295b2007-10-21 22:57:11 +0000366ExecutionEngine *ExecutionEngine::create(Module *M) {
367 return create(new ExistingModuleProvider(M));
368}
369
Misha Brukman4afac182003-10-10 17:45:12 +0000370/// getPointerToGlobal - This returns the address of the specified global
371/// value. This may involve code generation if it's a function.
372///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000373void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000374 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000375 return getPointerToFunction(F);
376
Reid Spenceree448632005-07-12 15:51:55 +0000377 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000378 void *p = state.getGlobalAddressMap(locked)[GV];
379 if (p)
380 return p;
381
382 // Global variable might have been added since interpreter started.
383 if (GlobalVariable *GVar =
384 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
385 EmitGlobalVariable(GVar);
386 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000387 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000388 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000389}
390
Reid Spencer3da59db2006-11-27 01:05:10 +0000391/// This function converts a Constant* into a GenericValue. The interesting
392/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000393/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000394GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000395 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000396 if (isa<UndefValue>(C))
397 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000398
Reid Spencer3da59db2006-11-27 01:05:10 +0000399 // If the value is a ConstantExpr
400 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000401 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000402 switch (CE->getOpcode()) {
403 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000404 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000405 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000406 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000407 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000408 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000409
Reid Spencer8fb0f192007-03-06 03:04:04 +0000410 char* tmp = (char*) Result.PointerVal;
411 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000412 return Result;
413 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000414 case Instruction::Trunc: {
415 GenericValue GV = getConstantValue(Op0);
416 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
417 GV.IntVal = GV.IntVal.trunc(BitWidth);
418 return GV;
419 }
420 case Instruction::ZExt: {
421 GenericValue GV = getConstantValue(Op0);
422 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
423 GV.IntVal = GV.IntVal.zext(BitWidth);
424 return GV;
425 }
426 case Instruction::SExt: {
427 GenericValue GV = getConstantValue(Op0);
428 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
429 GV.IntVal = GV.IntVal.sext(BitWidth);
430 return GV;
431 }
432 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000433 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000434 GenericValue GV = getConstantValue(Op0);
435 GV.FloatVal = float(GV.DoubleVal);
436 return GV;
437 }
438 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000439 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000440 GenericValue GV = getConstantValue(Op0);
441 GV.DoubleVal = double(GV.FloatVal);
442 return GV;
443 }
444 case Instruction::UIToFP: {
445 GenericValue GV = getConstantValue(Op0);
446 if (CE->getType() == Type::FloatTy)
447 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000448 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000449 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000450 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000451 const uint64_t zero[] = {0, 0};
452 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000453 (void)apf.convertFromAPInt(GV.IntVal,
454 false,
455 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000456 GV.IntVal = apf.convertToAPInt();
457 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000458 return GV;
459 }
460 case Instruction::SIToFP: {
461 GenericValue GV = getConstantValue(Op0);
462 if (CE->getType() == Type::FloatTy)
463 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000464 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000465 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000466 else if (CE->getType() == Type::X86_FP80Ty) {
467 const uint64_t zero[] = { 0, 0};
468 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000469 (void)apf.convertFromAPInt(GV.IntVal,
470 true,
471 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000472 GV.IntVal = apf.convertToAPInt();
473 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000474 return GV;
475 }
476 case Instruction::FPToUI: // double->APInt conversion handles sign
477 case Instruction::FPToSI: {
478 GenericValue GV = getConstantValue(Op0);
479 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
480 if (Op0->getType() == Type::FloatTy)
481 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000482 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000483 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000484 else if (Op0->getType() == Type::X86_FP80Ty) {
485 APFloat apf = APFloat(GV.IntVal);
486 uint64_t v;
487 (void)apf.convertToInteger(&v, BitWidth,
488 CE->getOpcode()==Instruction::FPToSI,
489 APFloat::rmTowardZero);
490 GV.IntVal = v; // endian?
491 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000492 return GV;
493 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000494 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000495 GenericValue GV = getConstantValue(Op0);
496 uint32_t PtrWidth = TD->getPointerSizeInBits();
497 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
498 return GV;
499 }
500 case Instruction::IntToPtr: {
501 GenericValue GV = getConstantValue(Op0);
502 uint32_t PtrWidth = TD->getPointerSizeInBits();
503 if (PtrWidth != GV.IntVal.getBitWidth())
504 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
505 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
506 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 return GV;
508 }
509 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000510 GenericValue GV = getConstantValue(Op0);
511 const Type* DestTy = CE->getType();
512 switch (Op0->getType()->getTypeID()) {
513 default: assert(0 && "Invalid bitcast operand");
514 case Type::IntegerTyID:
515 assert(DestTy->isFloatingPoint() && "invalid bitcast");
516 if (DestTy == Type::FloatTy)
517 GV.FloatVal = GV.IntVal.bitsToFloat();
518 else if (DestTy == Type::DoubleTy)
519 GV.DoubleVal = GV.IntVal.bitsToDouble();
520 break;
521 case Type::FloatTyID:
522 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
523 GV.IntVal.floatToBits(GV.FloatVal);
524 break;
525 case Type::DoubleTyID:
526 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
527 GV.IntVal.doubleToBits(GV.DoubleVal);
528 break;
529 case Type::PointerTyID:
530 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
531 break; // getConstantValue(Op0) above already converted it
532 }
533 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000534 }
Chris Lattner9a231222003-05-14 17:51:49 +0000535 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000536 case Instruction::Sub:
537 case Instruction::Mul:
538 case Instruction::UDiv:
539 case Instruction::SDiv:
540 case Instruction::URem:
541 case Instruction::SRem:
542 case Instruction::And:
543 case Instruction::Or:
544 case Instruction::Xor: {
545 GenericValue LHS = getConstantValue(Op0);
546 GenericValue RHS = getConstantValue(CE->getOperand(1));
547 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000548 switch (CE->getOperand(0)->getType()->getTypeID()) {
549 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000550 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000551 switch (CE->getOpcode()) {
552 default: assert(0 && "Invalid integer opcode");
553 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
554 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
555 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
556 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
557 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
558 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
559 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
560 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
561 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
562 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
563 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000564 break;
565 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000566 switch (CE->getOpcode()) {
567 default: assert(0 && "Invalid float opcode"); abort();
568 case Instruction::Add:
569 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
570 case Instruction::Sub:
571 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
572 case Instruction::Mul:
573 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
574 case Instruction::FDiv:
575 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
576 case Instruction::FRem:
577 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
578 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000579 break;
580 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000581 switch (CE->getOpcode()) {
582 default: assert(0 && "Invalid double opcode"); abort();
583 case Instruction::Add:
584 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
585 case Instruction::Sub:
586 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
587 case Instruction::Mul:
588 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
589 case Instruction::FDiv:
590 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
591 case Instruction::FRem:
592 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
593 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000594 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000595 case Type::X86_FP80TyID:
596 case Type::PPC_FP128TyID:
597 case Type::FP128TyID: {
598 APFloat apfLHS = APFloat(LHS.IntVal);
599 switch (CE->getOpcode()) {
600 default: assert(0 && "Invalid long double opcode"); abort();
601 case Instruction::Add:
602 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
603 GV.IntVal = apfLHS.convertToAPInt();
604 break;
605 case Instruction::Sub:
606 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
607 GV.IntVal = apfLHS.convertToAPInt();
608 break;
609 case Instruction::Mul:
610 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
611 GV.IntVal = apfLHS.convertToAPInt();
612 break;
613 case Instruction::FDiv:
614 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
615 GV.IntVal = apfLHS.convertToAPInt();
616 break;
617 case Instruction::FRem:
618 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
619 GV.IntVal = apfLHS.convertToAPInt();
620 break;
621 }
622 }
623 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000624 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000625 return GV;
626 }
Chris Lattner9a231222003-05-14 17:51:49 +0000627 default:
628 break;
629 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000630 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000631 abort();
632 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000633
Reid Spencerbce30f12007-03-06 22:23:15 +0000634 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000635 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000636 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000637 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000638 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000639 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000640 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000641 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000642 case Type::X86_FP80TyID:
643 case Type::FP128TyID:
644 case Type::PPC_FP128TyID:
645 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
646 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000647 case Type::IntegerTyID:
648 Result.IntVal = cast<ConstantInt>(C)->getValue();
649 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000650 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000651 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000652 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000653 else if (const Function *F = dyn_cast<Function>(C))
654 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
655 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
656 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
657 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000658 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000659 break;
660 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000661 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000662 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000663 }
664 return Result;
665}
666
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000667/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
668/// with the integer held in IntVal.
669static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
670 unsigned StoreBytes) {
671 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
672 uint8_t *Src = (uint8_t *)IntVal.getRawData();
673
674 if (sys::littleEndianHost())
675 // Little-endian host - the source is ordered from LSB to MSB. Order the
676 // destination from LSB to MSB: Do a straight copy.
677 memcpy(Dst, Src, StoreBytes);
678 else {
679 // Big-endian host - the source is an array of 64 bit words ordered from
680 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
681 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
682 while (StoreBytes > sizeof(uint64_t)) {
683 StoreBytes -= sizeof(uint64_t);
684 // May not be aligned so use memcpy.
685 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
686 Src += sizeof(uint64_t);
687 }
688
689 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
690 }
691}
692
Nate Begeman37efe672006-04-22 18:53:45 +0000693/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
694/// is the address of the memory at which to store Val, cast to GenericValue *.
695/// It is not a pointer to a GenericValue containing the address at which to
696/// store Val.
Reid Spencer415c1f72007-03-06 05:03:16 +0000697void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000698 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000699 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
700
Reid Spencer8fb0f192007-03-06 03:04:04 +0000701 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000702 case Type::IntegerTyID:
703 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000704 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000705 case Type::FloatTyID:
706 *((float*)Ptr) = Val.FloatVal;
707 break;
708 case Type::DoubleTyID:
709 *((double*)Ptr) = Val.DoubleVal;
710 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000711 case Type::X86_FP80TyID: {
712 uint16_t *Dest = (uint16_t*)Ptr;
713 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
714 // This is endian dependent, but it will only work on x86 anyway.
715 Dest[0] = Src[4];
716 Dest[1] = Src[0];
717 Dest[2] = Src[1];
718 Dest[3] = Src[2];
719 Dest[4] = Src[3];
720 break;
721 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000722 case Type::PointerTyID:
723 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
724 if (StoreBytes != sizeof(PointerTy))
725 memset(Ptr, 0, StoreBytes);
726
Reid Spencer8fb0f192007-03-06 03:04:04 +0000727 *((PointerTy*)Ptr) = Val.PointerVal;
728 break;
729 default:
730 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000731 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000732
733 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
734 // Host and target are different endian - reverse the stored bytes.
735 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
736}
737
738/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
739/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
740static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
741 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
742 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
743
744 if (sys::littleEndianHost())
745 // Little-endian host - the destination must be ordered from LSB to MSB.
746 // The source is ordered from LSB to MSB: Do a straight copy.
747 memcpy(Dst, Src, LoadBytes);
748 else {
749 // Big-endian - the destination is an array of 64 bit words ordered from
750 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
751 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
752 // a word.
753 while (LoadBytes > sizeof(uint64_t)) {
754 LoadBytes -= sizeof(uint64_t);
755 // May not be aligned so use memcpy.
756 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
757 Dst += sizeof(uint64_t);
758 }
759
760 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
761 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000762}
763
Misha Brukman4afac182003-10-10 17:45:12 +0000764/// FIXME: document
765///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000766void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000767 GenericValue *Ptr,
768 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000769 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000770
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000771 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
772 // Host and target are different endian - reverse copy the stored
773 // bytes into a buffer, and load from that.
774 uint8_t *Src = (uint8_t*)Ptr;
775 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
776 std::reverse_copy(Src, Src + LoadBytes, Buf);
777 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000778 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000779
780 switch (Ty->getTypeID()) {
781 case Type::IntegerTyID:
782 // An APInt with all words initially zero.
783 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
784 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
785 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000786 case Type::FloatTyID:
787 Result.FloatVal = *((float*)Ptr);
788 break;
789 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000790 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000791 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000792 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000793 Result.PointerVal = *((PointerTy*)Ptr);
794 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000795 case Type::X86_FP80TyID: {
796 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000797 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000798 uint16_t *p = (uint16_t*)Ptr;
799 union {
800 uint16_t x[8];
801 uint64_t y[2];
802 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000803 x[0] = p[1];
804 x[1] = p[2];
805 x[2] = p[3];
806 x[3] = p[4];
807 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000808 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000809 break;
810 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000811 default:
812 cerr << "Cannot load value of type " << *Ty << "!\n";
813 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000814 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000815}
816
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000817// InitializeMemory - Recursive function to apply a Constant value into the
818// specified memory location...
819//
820void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000821 if (isa<UndefValue>(Init)) {
822 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000823 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000824 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000825 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000826 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
827 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
828 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000829 } else if (isa<ConstantAggregateZero>(Init)) {
830 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
831 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000832 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
833 unsigned ElementSize =
834 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
835 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
836 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
837 return;
838 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
839 const StructLayout *SL =
840 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
841 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
842 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
843 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000844 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000845 GenericValue Val = getConstantValue(Init);
846 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
847 return;
848 }
849
Dan Gohman638e3782008-05-20 03:20:09 +0000850 cerr << "Bad Type: " << *Init->getType() << "\n";
851 assert(0 && "Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000852}
853
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000854/// EmitGlobals - Emit all of the global variables to memory, storing their
855/// addresses into GlobalAddress. This must make sure to copy the contents of
856/// their initializers into the memory.
857///
858void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000859 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000860
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000861 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000862 // to hold them. If there is more than one module, do a prepass over globals
863 // to figure out how the different modules should link together.
864 //
865 std::map<std::pair<std::string, const Type*>,
866 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000867
Chris Lattnerfe854032006-08-16 01:24:12 +0000868 if (Modules.size() != 1) {
869 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
870 Module &M = *Modules[m]->getModule();
871 for (Module::const_global_iterator I = M.global_begin(),
872 E = M.global_end(); I != E; ++I) {
873 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000874 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000875 GV->hasAppendingLinkage() || !GV->hasName())
876 continue;// Ignore external globals and globals with internal linkage.
877
878 const GlobalValue *&GVEntry =
879 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
880
881 // If this is the first time we've seen this global, it is the canonical
882 // version.
883 if (!GVEntry) {
884 GVEntry = GV;
885 continue;
886 }
887
888 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000889 if (GVEntry->hasExternalLinkage() ||
890 GVEntry->hasDLLImportLinkage() ||
891 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000892 continue;
893
894 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000895 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000896 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000897 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000898 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000899 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000900 }
901
902 std::vector<const GlobalValue*> NonCanonicalGlobals;
903 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
904 Module &M = *Modules[m]->getModule();
905 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
906 I != E; ++I) {
907 // In the multi-module case, see what this global maps to.
908 if (!LinkedGlobalsMap.empty()) {
909 if (const GlobalValue *GVEntry =
910 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
911 // If something else is the canonical global, ignore this one.
912 if (GVEntry != &*I) {
913 NonCanonicalGlobals.push_back(I);
914 continue;
915 }
916 }
917 }
918
Reid Spencer5cbf9852007-01-30 20:08:39 +0000919 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000920 // Get the type of the global.
921 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000922
Chris Lattnerfe854032006-08-16 01:24:12 +0000923 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000924 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000925 addGlobalMapping(I, new char[Size]);
926 } else {
927 // External variable reference. Try to use the dynamic loader to
928 // get a pointer to it.
929 if (void *SymAddr =
930 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
931 addGlobalMapping(I, SymAddr);
932 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000933 cerr << "Could not resolve external global address: "
934 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000935 abort();
936 }
937 }
938 }
939
940 // If there are multiple modules, map the non-canonical globals to their
941 // canonical location.
942 if (!NonCanonicalGlobals.empty()) {
943 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
944 const GlobalValue *GV = NonCanonicalGlobals[i];
945 const GlobalValue *CGV =
946 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
947 void *Ptr = getPointerToGlobalIfAvailable(CGV);
948 assert(Ptr && "Canonical global wasn't codegen'd!");
949 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
950 }
951 }
952
Reid Spencera54b7cb2007-01-12 07:05:14 +0000953 // Now that all of the globals are set up in memory, loop through them all
954 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000955 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
956 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000957 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000958 if (!LinkedGlobalsMap.empty()) {
959 if (const GlobalValue *GVEntry =
960 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
961 if (GVEntry != &*I) // Not the canonical variable.
962 continue;
963 }
964 EmitGlobalVariable(I);
965 }
966 }
967 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000968}
969
970// EmitGlobalVariable - This method emits the specified global variable to the
971// address specified in GlobalAddresses, or allocates new memory if it's not
972// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000973void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000974 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000975 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000976
Chris Lattnerc07ed132003-12-20 03:36:47 +0000977 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000978 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000979 if (GA == 0) {
980 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000981 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000982 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000983 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000984
Chris Lattner24b0a182003-12-20 02:45:37 +0000985 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000986 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000987 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000988}