blob: 94136d54af0c5e150f3d518f4f85104026e5d3ba [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;
Evan Cheng1b088f32008-06-17 16:49:02 +000043 SymbolSearchingDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000044 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000045 assert(P && "ModuleProvider is null?");
46}
47
Brian Gaeke8e539482003-09-04 22:57:27 +000048ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000049 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000050 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
51 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000052}
53
Devang Patel73d0e212007-10-15 19:56:32 +000054/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
55/// Release module from ModuleProvider.
56Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
57 std::string *ErrInfo) {
58 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
59 E = Modules.end(); I != E; ++I) {
60 ModuleProvider *MP = *I;
61 if (MP == P) {
62 Modules.erase(I);
Nate Begemanf049e072008-05-21 16:34:48 +000063 clearGlobalMappingsFromModule(MP->getModule());
Devang Patel73d0e212007-10-15 19:56:32 +000064 return MP->releaseModule(ErrInfo);
65 }
66 }
67 return NULL;
68}
69
Chris Lattnerfe854032006-08-16 01:24:12 +000070/// FindFunctionNamed - Search all of the active modules to find the one that
71/// defines FnName. This is very slow operation and shouldn't be used for
72/// general code.
73Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
74 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000075 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000076 return F;
77 }
78 return 0;
79}
80
81
Chris Lattnere7fd5532006-05-08 22:00:52 +000082/// addGlobalMapping - Tell the execution engine that the specified global is
83/// at the specified location. This is used internally as functions are JIT'd
84/// and as global variables are laid out in memory. It can and should also be
85/// used by clients of the EE that want to have an LLVM global overlay
86/// existing data in memory.
87void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
88 MutexGuard locked(lock);
89
90 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
91 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
92 CurVal = Addr;
93
94 // If we are using the reverse mapping, add it too
95 if (!state.getGlobalAddressReverseMap(locked).empty()) {
96 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
97 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
98 V = GV;
99 }
100}
101
102/// clearAllGlobalMappings - Clear all global mappings and start over again
103/// use in dynamic compilation scenarios when you want to move globals
104void ExecutionEngine::clearAllGlobalMappings() {
105 MutexGuard locked(lock);
106
107 state.getGlobalAddressMap(locked).clear();
108 state.getGlobalAddressReverseMap(locked).clear();
109}
110
Nate Begemanf049e072008-05-21 16:34:48 +0000111/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
112/// particular module, because it has been removed from the JIT.
113void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
114 MutexGuard locked(lock);
115
116 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
117 state.getGlobalAddressMap(locked).erase(FI);
118 state.getGlobalAddressReverseMap(locked).erase(FI);
119 }
120 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
121 GI != GE; ++GI) {
122 state.getGlobalAddressMap(locked).erase(GI);
123 state.getGlobalAddressReverseMap(locked).erase(GI);
124 }
125}
126
Chris Lattnere7fd5532006-05-08 22:00:52 +0000127/// updateGlobalMapping - Replace an existing mapping for GV with a new
128/// address. This updates both maps as required. If "Addr" is null, the
129/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000130void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000131 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000132
133 std::map<const GlobalValue*, void *> &Map = state.getGlobalAddressMap(locked);
134
Chris Lattnere7fd5532006-05-08 22:00:52 +0000135 // Deleting from the mapping?
136 if (Addr == 0) {
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000137 std::map<const GlobalValue*, void *>::iterator I = Map.find(GV);
138 void *OldVal;
139 if (I == Map.end())
140 OldVal = 0;
141 else {
142 OldVal = I->second;
143 Map.erase(I);
144 }
145
Chris Lattnere7fd5532006-05-08 22:00:52 +0000146 if (!state.getGlobalAddressReverseMap(locked).empty())
147 state.getGlobalAddressReverseMap(locked).erase(Addr);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000148 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000149 }
150
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000151 void *&CurVal = Map[GV];
152 void *OldVal = CurVal;
153
Chris Lattnere7fd5532006-05-08 22:00:52 +0000154 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
155 state.getGlobalAddressReverseMap(locked).erase(CurVal);
156 CurVal = Addr;
157
158 // If we are using the reverse mapping, add it too
159 if (!state.getGlobalAddressReverseMap(locked).empty()) {
160 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
161 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
162 V = GV;
163 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000164 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000165}
166
167/// getPointerToGlobalIfAvailable - This returns the address of the specified
168/// global value if it is has already been codegen'd, otherwise it returns null.
169///
170void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
171 MutexGuard locked(lock);
172
173 std::map<const GlobalValue*, void*>::iterator I =
174 state.getGlobalAddressMap(locked).find(GV);
175 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
176}
177
Chris Lattner55d86482003-12-31 20:21:04 +0000178/// getGlobalValueAtAddress - Return the LLVM global value object that starts
179/// at the specified address.
180///
181const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000182 MutexGuard locked(lock);
183
Chris Lattner55d86482003-12-31 20:21:04 +0000184 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000185 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000186 for (std::map<const GlobalValue*, void *>::iterator
187 I = state.getGlobalAddressMap(locked).begin(),
188 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
189 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
190 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000191 }
192
193 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000194 state.getGlobalAddressReverseMap(locked).find(Addr);
195 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000196}
Chris Lattner87f03102003-12-26 06:50:30 +0000197
198// CreateArgv - Turn a vector of strings into a nice argv style array of
199// pointers to null terminated strings.
200//
201static void *CreateArgv(ExecutionEngine *EE,
202 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000203 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000204 char *Result = new char[(InputArgv.size()+1)*PtrSize];
205
Bill Wendling480f0932006-11-27 23:54:50 +0000206 DOUT << "ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000207 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000208
209 for (unsigned i = 0; i != InputArgv.size(); ++i) {
210 unsigned Size = InputArgv[i].size()+1;
211 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000212 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000213
Chris Lattner87f03102003-12-26 06:50:30 +0000214 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
215 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000216
Chris Lattner87f03102003-12-26 06:50:30 +0000217 // Endian safe: Result[i] = (PointerTy)Dest;
218 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
219 SBytePtr);
220 }
221
222 // Null terminate it
223 EE->StoreValueToMemory(PTOGV(0),
224 (GenericValue*)(Result+InputArgv.size()*PtrSize),
225 SBytePtr);
226 return Result;
227}
228
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000229
230/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000231/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000232/// value of isDtors.
233void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
234 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000235
Chris Lattnerfe854032006-08-16 01:24:12 +0000236 // Execute global ctors/dtors for each module in the program.
237 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
238 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
239
240 // If this global has internal linkage, or if it has a use, then it must be
241 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
242 // this is the case, don't execute any of the global ctors, __main will do
243 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000244 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000245
246 // Should be an array of '{ int, void ()* }' structs. The first value is
247 // the init priority, which we ignore.
248 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
249 if (!InitList) continue;
250 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
251 if (ConstantStruct *CS =
252 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
253 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000254
Chris Lattnerfe854032006-08-16 01:24:12 +0000255 Constant *FP = CS->getOperand(1);
256 if (FP->isNullValue())
257 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000258
Chris Lattnerfe854032006-08-16 01:24:12 +0000259 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000260 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000261 FP = CE->getOperand(0);
262 if (Function *F = dyn_cast<Function>(FP)) {
263 // Execute the ctor/dtor function!
264 runFunction(F, std::vector<GenericValue>());
265 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000266 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000267 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000268}
269
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000270/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
271static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
272 unsigned PtrSize = EE->getTargetData()->getPointerSize();
273 for (unsigned i = 0; i < PtrSize; ++i)
274 if (*(i + (uint8_t*)Loc))
275 return false;
276 return true;
277}
278
Chris Lattner87f03102003-12-26 06:50:30 +0000279/// runFunctionAsMain - This is a helper function which wraps runFunction to
280/// handle the common task of starting up main with the specified argc, argv,
281/// and envp parameters.
282int ExecutionEngine::runFunctionAsMain(Function *Fn,
283 const std::vector<std::string> &argv,
284 const char * const * envp) {
285 std::vector<GenericValue> GVArgs;
286 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000287 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000288
289 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000290 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000291 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000292 const Type* PPInt8Ty =
293 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000294 switch (NumArgs) {
295 case 3:
296 if (FTy->getParamType(2) != PPInt8Ty) {
297 cerr << "Invalid type for third argument of main() supplied\n";
298 abort();
299 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000300 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000301 case 2:
302 if (FTy->getParamType(1) != PPInt8Ty) {
303 cerr << "Invalid type for second argument of main() supplied\n";
304 abort();
305 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000306 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000307 case 1:
308 if (FTy->getParamType(0) != Type::Int32Ty) {
309 cerr << "Invalid type for first argument of main() supplied\n";
310 abort();
311 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000312 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000313 case 0:
314 if (FTy->getReturnType() != Type::Int32Ty &&
315 FTy->getReturnType() != Type::VoidTy) {
316 cerr << "Invalid return type of main() supplied\n";
317 abort();
318 }
319 break;
320 default:
321 cerr << "Invalid number of arguments of main() supplied\n";
322 abort();
323 }
324
Chris Lattnerf24d0992004-08-16 01:05:35 +0000325 if (NumArgs) {
326 GVArgs.push_back(GVArgc); // Arg #0 = argc.
327 if (NumArgs > 1) {
328 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000329 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000330 "argv[0] was null after CreateArgv");
331 if (NumArgs > 2) {
332 std::vector<std::string> EnvVars;
333 for (unsigned i = 0; envp[i]; ++i)
334 EnvVars.push_back(envp[i]);
335 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
336 }
337 }
338 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000339 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000340}
341
Misha Brukman19684162003-10-16 21:18:05 +0000342/// If possible, create a JIT, unless the caller specifically requests an
343/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000344/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000345///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000346ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000347 bool ForceInterpreter,
348 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000349 ExecutionEngine *EE = 0;
350
Nick Lewycky6456d862008-03-08 02:49:45 +0000351 // Make sure we can resolve symbols in the program as well. The zero arg
352 // to the function tells DynamicLibrary to load the program, not a library.
353 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
354 return 0;
355
Chris Lattner73011782003-12-28 09:44:37 +0000356 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000357 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000358 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000359
360 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000361 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000362 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000363
Brian Gaeke82d82772003-09-03 20:34:19 +0000364 return EE;
365}
366
Chris Lattner8b5295b2007-10-21 22:57:11 +0000367ExecutionEngine *ExecutionEngine::create(Module *M) {
368 return create(new ExistingModuleProvider(M));
369}
370
Misha Brukman4afac182003-10-10 17:45:12 +0000371/// getPointerToGlobal - This returns the address of the specified global
372/// value. This may involve code generation if it's a function.
373///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000374void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000375 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000376 return getPointerToFunction(F);
377
Reid Spenceree448632005-07-12 15:51:55 +0000378 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000379 void *p = state.getGlobalAddressMap(locked)[GV];
380 if (p)
381 return p;
382
383 // Global variable might have been added since interpreter started.
384 if (GlobalVariable *GVar =
385 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
386 EmitGlobalVariable(GVar);
387 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000388 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000389 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000390}
391
Reid Spencer3da59db2006-11-27 01:05:10 +0000392/// This function converts a Constant* into a GenericValue. The interesting
393/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000394/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000395GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000396 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000397 if (isa<UndefValue>(C))
398 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000399
Reid Spencer3da59db2006-11-27 01:05:10 +0000400 // If the value is a ConstantExpr
401 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000402 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000403 switch (CE->getOpcode()) {
404 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000405 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000406 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000407 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000408 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000409 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000410
Reid Spencer8fb0f192007-03-06 03:04:04 +0000411 char* tmp = (char*) Result.PointerVal;
412 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000413 return Result;
414 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000415 case Instruction::Trunc: {
416 GenericValue GV = getConstantValue(Op0);
417 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
418 GV.IntVal = GV.IntVal.trunc(BitWidth);
419 return GV;
420 }
421 case Instruction::ZExt: {
422 GenericValue GV = getConstantValue(Op0);
423 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
424 GV.IntVal = GV.IntVal.zext(BitWidth);
425 return GV;
426 }
427 case Instruction::SExt: {
428 GenericValue GV = getConstantValue(Op0);
429 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
430 GV.IntVal = GV.IntVal.sext(BitWidth);
431 return GV;
432 }
433 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000434 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000435 GenericValue GV = getConstantValue(Op0);
436 GV.FloatVal = float(GV.DoubleVal);
437 return GV;
438 }
439 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000440 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000441 GenericValue GV = getConstantValue(Op0);
442 GV.DoubleVal = double(GV.FloatVal);
443 return GV;
444 }
445 case Instruction::UIToFP: {
446 GenericValue GV = getConstantValue(Op0);
447 if (CE->getType() == Type::FloatTy)
448 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000449 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000450 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000451 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000452 const uint64_t zero[] = {0, 0};
453 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000454 (void)apf.convertFromAPInt(GV.IntVal,
455 false,
456 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000457 GV.IntVal = apf.convertToAPInt();
458 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000459 return GV;
460 }
461 case Instruction::SIToFP: {
462 GenericValue GV = getConstantValue(Op0);
463 if (CE->getType() == Type::FloatTy)
464 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000465 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000466 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000467 else if (CE->getType() == Type::X86_FP80Ty) {
468 const uint64_t zero[] = { 0, 0};
469 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000470 (void)apf.convertFromAPInt(GV.IntVal,
471 true,
472 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000473 GV.IntVal = apf.convertToAPInt();
474 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000475 return GV;
476 }
477 case Instruction::FPToUI: // double->APInt conversion handles sign
478 case Instruction::FPToSI: {
479 GenericValue GV = getConstantValue(Op0);
480 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
481 if (Op0->getType() == Type::FloatTy)
482 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000483 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000484 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000485 else if (Op0->getType() == Type::X86_FP80Ty) {
486 APFloat apf = APFloat(GV.IntVal);
487 uint64_t v;
488 (void)apf.convertToInteger(&v, BitWidth,
489 CE->getOpcode()==Instruction::FPToSI,
490 APFloat::rmTowardZero);
491 GV.IntVal = v; // endian?
492 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000493 return GV;
494 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000495 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000496 GenericValue GV = getConstantValue(Op0);
497 uint32_t PtrWidth = TD->getPointerSizeInBits();
498 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
499 return GV;
500 }
501 case Instruction::IntToPtr: {
502 GenericValue GV = getConstantValue(Op0);
503 uint32_t PtrWidth = TD->getPointerSizeInBits();
504 if (PtrWidth != GV.IntVal.getBitWidth())
505 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
506 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
507 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000508 return GV;
509 }
510 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000511 GenericValue GV = getConstantValue(Op0);
512 const Type* DestTy = CE->getType();
513 switch (Op0->getType()->getTypeID()) {
514 default: assert(0 && "Invalid bitcast operand");
515 case Type::IntegerTyID:
516 assert(DestTy->isFloatingPoint() && "invalid bitcast");
517 if (DestTy == Type::FloatTy)
518 GV.FloatVal = GV.IntVal.bitsToFloat();
519 else if (DestTy == Type::DoubleTy)
520 GV.DoubleVal = GV.IntVal.bitsToDouble();
521 break;
522 case Type::FloatTyID:
523 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
524 GV.IntVal.floatToBits(GV.FloatVal);
525 break;
526 case Type::DoubleTyID:
527 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
528 GV.IntVal.doubleToBits(GV.DoubleVal);
529 break;
530 case Type::PointerTyID:
531 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
532 break; // getConstantValue(Op0) above already converted it
533 }
534 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000535 }
Chris Lattner9a231222003-05-14 17:51:49 +0000536 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000537 case Instruction::Sub:
538 case Instruction::Mul:
539 case Instruction::UDiv:
540 case Instruction::SDiv:
541 case Instruction::URem:
542 case Instruction::SRem:
543 case Instruction::And:
544 case Instruction::Or:
545 case Instruction::Xor: {
546 GenericValue LHS = getConstantValue(Op0);
547 GenericValue RHS = getConstantValue(CE->getOperand(1));
548 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000549 switch (CE->getOperand(0)->getType()->getTypeID()) {
550 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000551 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000552 switch (CE->getOpcode()) {
553 default: assert(0 && "Invalid integer opcode");
554 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
555 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
556 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
557 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
558 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
559 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
560 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
561 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
562 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
563 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
564 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000565 break;
566 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000567 switch (CE->getOpcode()) {
568 default: assert(0 && "Invalid float opcode"); abort();
569 case Instruction::Add:
570 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
571 case Instruction::Sub:
572 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
573 case Instruction::Mul:
574 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
575 case Instruction::FDiv:
576 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
577 case Instruction::FRem:
578 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
579 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000580 break;
581 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000582 switch (CE->getOpcode()) {
583 default: assert(0 && "Invalid double opcode"); abort();
584 case Instruction::Add:
585 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
586 case Instruction::Sub:
587 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
588 case Instruction::Mul:
589 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
590 case Instruction::FDiv:
591 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
592 case Instruction::FRem:
593 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
594 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000595 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000596 case Type::X86_FP80TyID:
597 case Type::PPC_FP128TyID:
598 case Type::FP128TyID: {
599 APFloat apfLHS = APFloat(LHS.IntVal);
600 switch (CE->getOpcode()) {
601 default: assert(0 && "Invalid long double opcode"); abort();
602 case Instruction::Add:
603 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
604 GV.IntVal = apfLHS.convertToAPInt();
605 break;
606 case Instruction::Sub:
607 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
608 GV.IntVal = apfLHS.convertToAPInt();
609 break;
610 case Instruction::Mul:
611 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
612 GV.IntVal = apfLHS.convertToAPInt();
613 break;
614 case Instruction::FDiv:
615 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
616 GV.IntVal = apfLHS.convertToAPInt();
617 break;
618 case Instruction::FRem:
619 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
620 GV.IntVal = apfLHS.convertToAPInt();
621 break;
622 }
623 }
624 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000625 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000626 return GV;
627 }
Chris Lattner9a231222003-05-14 17:51:49 +0000628 default:
629 break;
630 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000631 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000632 abort();
633 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000634
Reid Spencerbce30f12007-03-06 22:23:15 +0000635 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000636 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000637 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000638 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000639 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000640 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000641 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000642 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000643 case Type::X86_FP80TyID:
644 case Type::FP128TyID:
645 case Type::PPC_FP128TyID:
646 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
647 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000648 case Type::IntegerTyID:
649 Result.IntVal = cast<ConstantInt>(C)->getValue();
650 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000651 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000652 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000653 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000654 else if (const Function *F = dyn_cast<Function>(C))
655 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
656 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
657 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
658 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000659 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000660 break;
661 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000662 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000663 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000664 }
665 return Result;
666}
667
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000668/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
669/// with the integer held in IntVal.
670static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
671 unsigned StoreBytes) {
672 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
673 uint8_t *Src = (uint8_t *)IntVal.getRawData();
674
675 if (sys::littleEndianHost())
676 // Little-endian host - the source is ordered from LSB to MSB. Order the
677 // destination from LSB to MSB: Do a straight copy.
678 memcpy(Dst, Src, StoreBytes);
679 else {
680 // Big-endian host - the source is an array of 64 bit words ordered from
681 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
682 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
683 while (StoreBytes > sizeof(uint64_t)) {
684 StoreBytes -= sizeof(uint64_t);
685 // May not be aligned so use memcpy.
686 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
687 Src += sizeof(uint64_t);
688 }
689
690 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
691 }
692}
693
Nate Begeman37efe672006-04-22 18:53:45 +0000694/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
695/// is the address of the memory at which to store Val, cast to GenericValue *.
696/// It is not a pointer to a GenericValue containing the address at which to
697/// store Val.
Reid Spencer415c1f72007-03-06 05:03:16 +0000698void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000699 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000700 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
701
Reid Spencer8fb0f192007-03-06 03:04:04 +0000702 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000703 case Type::IntegerTyID:
704 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000705 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000706 case Type::FloatTyID:
707 *((float*)Ptr) = Val.FloatVal;
708 break;
709 case Type::DoubleTyID:
710 *((double*)Ptr) = Val.DoubleVal;
711 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000712 case Type::X86_FP80TyID: {
713 uint16_t *Dest = (uint16_t*)Ptr;
714 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
715 // This is endian dependent, but it will only work on x86 anyway.
716 Dest[0] = Src[4];
717 Dest[1] = Src[0];
718 Dest[2] = Src[1];
719 Dest[3] = Src[2];
720 Dest[4] = Src[3];
721 break;
722 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000723 case Type::PointerTyID:
724 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
725 if (StoreBytes != sizeof(PointerTy))
726 memset(Ptr, 0, StoreBytes);
727
Reid Spencer8fb0f192007-03-06 03:04:04 +0000728 *((PointerTy*)Ptr) = Val.PointerVal;
729 break;
730 default:
731 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000732 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000733
734 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
735 // Host and target are different endian - reverse the stored bytes.
736 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
737}
738
739/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
740/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
741static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
742 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
743 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
744
745 if (sys::littleEndianHost())
746 // Little-endian host - the destination must be ordered from LSB to MSB.
747 // The source is ordered from LSB to MSB: Do a straight copy.
748 memcpy(Dst, Src, LoadBytes);
749 else {
750 // Big-endian - the destination is an array of 64 bit words ordered from
751 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
752 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
753 // a word.
754 while (LoadBytes > sizeof(uint64_t)) {
755 LoadBytes -= sizeof(uint64_t);
756 // May not be aligned so use memcpy.
757 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
758 Dst += sizeof(uint64_t);
759 }
760
761 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
762 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000763}
764
Misha Brukman4afac182003-10-10 17:45:12 +0000765/// FIXME: document
766///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000767void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000768 GenericValue *Ptr,
769 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000770 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000771
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000772 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
773 // Host and target are different endian - reverse copy the stored
774 // bytes into a buffer, and load from that.
775 uint8_t *Src = (uint8_t*)Ptr;
776 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
777 std::reverse_copy(Src, Src + LoadBytes, Buf);
778 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000779 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000780
781 switch (Ty->getTypeID()) {
782 case Type::IntegerTyID:
783 // An APInt with all words initially zero.
784 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
785 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
786 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000787 case Type::FloatTyID:
788 Result.FloatVal = *((float*)Ptr);
789 break;
790 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000791 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000792 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000793 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000794 Result.PointerVal = *((PointerTy*)Ptr);
795 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000796 case Type::X86_FP80TyID: {
797 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000798 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000799 uint16_t *p = (uint16_t*)Ptr;
800 union {
801 uint16_t x[8];
802 uint64_t y[2];
803 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000804 x[0] = p[1];
805 x[1] = p[2];
806 x[2] = p[3];
807 x[3] = p[4];
808 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000809 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000810 break;
811 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000812 default:
813 cerr << "Cannot load value of type " << *Ty << "!\n";
814 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000815 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000816}
817
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000818// InitializeMemory - Recursive function to apply a Constant value into the
819// specified memory location...
820//
821void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000822 if (isa<UndefValue>(Init)) {
823 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000824 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000825 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000826 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000827 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
828 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
829 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000830 } else if (isa<ConstantAggregateZero>(Init)) {
831 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
832 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000833 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
834 unsigned ElementSize =
835 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
836 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
837 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
838 return;
839 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
840 const StructLayout *SL =
841 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
842 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
843 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
844 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000845 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000846 GenericValue Val = getConstantValue(Init);
847 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
848 return;
849 }
850
Dan Gohman638e3782008-05-20 03:20:09 +0000851 cerr << "Bad Type: " << *Init->getType() << "\n";
852 assert(0 && "Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000853}
854
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000855/// EmitGlobals - Emit all of the global variables to memory, storing their
856/// addresses into GlobalAddress. This must make sure to copy the contents of
857/// their initializers into the memory.
858///
859void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000860 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000861
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000862 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000863 // to hold them. If there is more than one module, do a prepass over globals
864 // to figure out how the different modules should link together.
865 //
866 std::map<std::pair<std::string, const Type*>,
867 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000868
Chris Lattnerfe854032006-08-16 01:24:12 +0000869 if (Modules.size() != 1) {
870 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
871 Module &M = *Modules[m]->getModule();
872 for (Module::const_global_iterator I = M.global_begin(),
873 E = M.global_end(); I != E; ++I) {
874 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000875 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000876 GV->hasAppendingLinkage() || !GV->hasName())
877 continue;// Ignore external globals and globals with internal linkage.
878
879 const GlobalValue *&GVEntry =
880 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
881
882 // If this is the first time we've seen this global, it is the canonical
883 // version.
884 if (!GVEntry) {
885 GVEntry = GV;
886 continue;
887 }
888
889 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000890 if (GVEntry->hasExternalLinkage() ||
891 GVEntry->hasDLLImportLinkage() ||
892 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000893 continue;
894
895 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000896 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000897 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000898 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000899 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000900 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000901 }
902
903 std::vector<const GlobalValue*> NonCanonicalGlobals;
904 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
905 Module &M = *Modules[m]->getModule();
906 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
907 I != E; ++I) {
908 // In the multi-module case, see what this global maps to.
909 if (!LinkedGlobalsMap.empty()) {
910 if (const GlobalValue *GVEntry =
911 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
912 // If something else is the canonical global, ignore this one.
913 if (GVEntry != &*I) {
914 NonCanonicalGlobals.push_back(I);
915 continue;
916 }
917 }
918 }
919
Reid Spencer5cbf9852007-01-30 20:08:39 +0000920 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000921 // Get the type of the global.
922 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000923
Chris Lattnerfe854032006-08-16 01:24:12 +0000924 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000925 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000926 addGlobalMapping(I, new char[Size]);
927 } else {
928 // External variable reference. Try to use the dynamic loader to
929 // get a pointer to it.
930 if (void *SymAddr =
931 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
932 addGlobalMapping(I, SymAddr);
933 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000934 cerr << "Could not resolve external global address: "
935 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000936 abort();
937 }
938 }
939 }
940
941 // If there are multiple modules, map the non-canonical globals to their
942 // canonical location.
943 if (!NonCanonicalGlobals.empty()) {
944 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
945 const GlobalValue *GV = NonCanonicalGlobals[i];
946 const GlobalValue *CGV =
947 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
948 void *Ptr = getPointerToGlobalIfAvailable(CGV);
949 assert(Ptr && "Canonical global wasn't codegen'd!");
950 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
951 }
952 }
953
Reid Spencera54b7cb2007-01-12 07:05:14 +0000954 // Now that all of the globals are set up in memory, loop through them all
955 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000956 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
957 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000958 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000959 if (!LinkedGlobalsMap.empty()) {
960 if (const GlobalValue *GVEntry =
961 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
962 if (GVEntry != &*I) // Not the canonical variable.
963 continue;
964 }
965 EmitGlobalVariable(I);
966 }
967 }
968 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000969}
970
971// EmitGlobalVariable - This method emits the specified global variable to the
972// address specified in GlobalAddresses, or allocates new memory if it's not
973// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000974void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000975 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000976 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000977
Chris Lattnerc07ed132003-12-20 03:36:47 +0000978 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000979 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000980 if (GA == 0) {
981 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000982 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000983 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000984 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000985
Chris Lattner24b0a182003-12-20 02:45:37 +0000986 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000987 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000988 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000989}