blob: 9799f5085696be79ec7776968a93e03d973a840c [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"
Jeff Cohen2b7d7b52007-03-12 17:57:00 +000029#include <math.h>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000030using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000031
Chris Lattner36343732006-12-19 22:43:32 +000032STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
33STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000034
Chris Lattner2fe4bb02006-03-22 06:07:50 +000035ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
36ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000037ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
38
Chris Lattner2fe4bb02006-03-22 06:07:50 +000039
Chris Lattnerd958a5a2007-10-22 02:50:12 +000040ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000041 LazyCompilationDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000042 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000043 assert(P && "ModuleProvider is null?");
44}
45
Brian Gaeke8e539482003-09-04 22:57:27 +000046ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000047 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000048 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
49 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000050}
51
Devang Patel73d0e212007-10-15 19:56:32 +000052/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
53/// Release module from ModuleProvider.
54Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
55 std::string *ErrInfo) {
56 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
57 E = Modules.end(); I != E; ++I) {
58 ModuleProvider *MP = *I;
59 if (MP == P) {
60 Modules.erase(I);
61 return MP->releaseModule(ErrInfo);
62 }
63 }
64 return NULL;
65}
66
Chris Lattnerfe854032006-08-16 01:24:12 +000067/// FindFunctionNamed - Search all of the active modules to find the one that
68/// defines FnName. This is very slow operation and shouldn't be used for
69/// general code.
70Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
71 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000072 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000073 return F;
74 }
75 return 0;
76}
77
78
Chris Lattnere7fd5532006-05-08 22:00:52 +000079/// addGlobalMapping - Tell the execution engine that the specified global is
80/// at the specified location. This is used internally as functions are JIT'd
81/// and as global variables are laid out in memory. It can and should also be
82/// used by clients of the EE that want to have an LLVM global overlay
83/// existing data in memory.
84void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
85 MutexGuard locked(lock);
86
87 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
88 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
89 CurVal = Addr;
90
91 // If we are using the reverse mapping, add it too
92 if (!state.getGlobalAddressReverseMap(locked).empty()) {
93 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
94 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
95 V = GV;
96 }
97}
98
99/// clearAllGlobalMappings - Clear all global mappings and start over again
100/// use in dynamic compilation scenarios when you want to move globals
101void ExecutionEngine::clearAllGlobalMappings() {
102 MutexGuard locked(lock);
103
104 state.getGlobalAddressMap(locked).clear();
105 state.getGlobalAddressReverseMap(locked).clear();
106}
107
108/// updateGlobalMapping - Replace an existing mapping for GV with a new
109/// address. This updates both maps as required. If "Addr" is null, the
110/// entry for the global is removed from the mappings.
111void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
112 MutexGuard locked(lock);
113
114 // Deleting from the mapping?
115 if (Addr == 0) {
116 state.getGlobalAddressMap(locked).erase(GV);
117 if (!state.getGlobalAddressReverseMap(locked).empty())
118 state.getGlobalAddressReverseMap(locked).erase(Addr);
119 return;
120 }
121
122 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
123 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
124 state.getGlobalAddressReverseMap(locked).erase(CurVal);
125 CurVal = Addr;
126
127 // If we are using the reverse mapping, add it too
128 if (!state.getGlobalAddressReverseMap(locked).empty()) {
129 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
130 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
131 V = GV;
132 }
133}
134
135/// getPointerToGlobalIfAvailable - This returns the address of the specified
136/// global value if it is has already been codegen'd, otherwise it returns null.
137///
138void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
139 MutexGuard locked(lock);
140
141 std::map<const GlobalValue*, void*>::iterator I =
142 state.getGlobalAddressMap(locked).find(GV);
143 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
144}
145
Chris Lattner55d86482003-12-31 20:21:04 +0000146/// getGlobalValueAtAddress - Return the LLVM global value object that starts
147/// at the specified address.
148///
149const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000150 MutexGuard locked(lock);
151
Chris Lattner55d86482003-12-31 20:21:04 +0000152 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000153 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000154 for (std::map<const GlobalValue*, void *>::iterator
155 I = state.getGlobalAddressMap(locked).begin(),
156 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
157 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
158 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000159 }
160
161 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000162 state.getGlobalAddressReverseMap(locked).find(Addr);
163 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000164}
Chris Lattner87f03102003-12-26 06:50:30 +0000165
166// CreateArgv - Turn a vector of strings into a nice argv style array of
167// pointers to null terminated strings.
168//
169static void *CreateArgv(ExecutionEngine *EE,
170 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000171 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000172 char *Result = new char[(InputArgv.size()+1)*PtrSize];
173
Bill Wendling480f0932006-11-27 23:54:50 +0000174 DOUT << "ARGV = " << (void*)Result << "\n";
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000175 const Type *SBytePtr = PointerType::getUnqual(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000176
177 for (unsigned i = 0; i != InputArgv.size(); ++i) {
178 unsigned Size = InputArgv[i].size()+1;
179 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000180 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000181
Chris Lattner87f03102003-12-26 06:50:30 +0000182 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
183 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000184
Chris Lattner87f03102003-12-26 06:50:30 +0000185 // Endian safe: Result[i] = (PointerTy)Dest;
186 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
187 SBytePtr);
188 }
189
190 // Null terminate it
191 EE->StoreValueToMemory(PTOGV(0),
192 (GenericValue*)(Result+InputArgv.size()*PtrSize),
193 SBytePtr);
194 return Result;
195}
196
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000197
198/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000199/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000200/// value of isDtors.
201void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
202 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000203
Chris Lattnerfe854032006-08-16 01:24:12 +0000204 // Execute global ctors/dtors for each module in the program.
205 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
206 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
207
208 // If this global has internal linkage, or if it has a use, then it must be
209 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
210 // this is the case, don't execute any of the global ctors, __main will do
211 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000212 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000213
214 // Should be an array of '{ int, void ()* }' structs. The first value is
215 // the init priority, which we ignore.
216 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
217 if (!InitList) continue;
218 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
219 if (ConstantStruct *CS =
220 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
221 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000222
Chris Lattnerfe854032006-08-16 01:24:12 +0000223 Constant *FP = CS->getOperand(1);
224 if (FP->isNullValue())
225 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000226
Chris Lattnerfe854032006-08-16 01:24:12 +0000227 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000228 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000229 FP = CE->getOperand(0);
230 if (Function *F = dyn_cast<Function>(FP)) {
231 // Execute the ctor/dtor function!
232 runFunction(F, std::vector<GenericValue>());
233 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000234 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000235 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000236}
237
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000238/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
239static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
240 unsigned PtrSize = EE->getTargetData()->getPointerSize();
241 for (unsigned i = 0; i < PtrSize; ++i)
242 if (*(i + (uint8_t*)Loc))
243 return false;
244 return true;
245}
246
Chris Lattner87f03102003-12-26 06:50:30 +0000247/// runFunctionAsMain - This is a helper function which wraps runFunction to
248/// handle the common task of starting up main with the specified argc, argv,
249/// and envp parameters.
250int ExecutionEngine::runFunctionAsMain(Function *Fn,
251 const std::vector<std::string> &argv,
252 const char * const * envp) {
253 std::vector<GenericValue> GVArgs;
254 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000255 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000256
257 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000258 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000259 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000260 const Type* PPInt8Ty =
261 PointerType::getUnqual(PointerType::getUnqual(Type::Int8Ty));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000262 switch (NumArgs) {
263 case 3:
264 if (FTy->getParamType(2) != PPInt8Ty) {
265 cerr << "Invalid type for third argument of main() supplied\n";
266 abort();
267 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000268 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000269 case 2:
270 if (FTy->getParamType(1) != PPInt8Ty) {
271 cerr << "Invalid type for second argument of main() supplied\n";
272 abort();
273 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000274 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000275 case 1:
276 if (FTy->getParamType(0) != Type::Int32Ty) {
277 cerr << "Invalid type for first argument of main() supplied\n";
278 abort();
279 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000280 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000281 case 0:
282 if (FTy->getReturnType() != Type::Int32Ty &&
283 FTy->getReturnType() != Type::VoidTy) {
284 cerr << "Invalid return type of main() supplied\n";
285 abort();
286 }
287 break;
288 default:
289 cerr << "Invalid number of arguments of main() supplied\n";
290 abort();
291 }
292
Chris Lattnerf24d0992004-08-16 01:05:35 +0000293 if (NumArgs) {
294 GVArgs.push_back(GVArgc); // Arg #0 = argc.
295 if (NumArgs > 1) {
296 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000297 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000298 "argv[0] was null after CreateArgv");
299 if (NumArgs > 2) {
300 std::vector<std::string> EnvVars;
301 for (unsigned i = 0; envp[i]; ++i)
302 EnvVars.push_back(envp[i]);
303 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
304 }
305 }
306 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000307 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000308}
309
Misha Brukman19684162003-10-16 21:18:05 +0000310/// If possible, create a JIT, unless the caller specifically requests an
311/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000313///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000314ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000315 bool ForceInterpreter,
316 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000317 ExecutionEngine *EE = 0;
318
Chris Lattner73011782003-12-28 09:44:37 +0000319 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000320 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000321 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000322
323 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000324 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000325 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000326
Chris Lattner726c1ef2006-03-23 05:22:51 +0000327 if (EE) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000328 // Make sure we can resolve symbols in the program as well. The zero arg
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000329 // to the function tells DynamicLibrary to load the program, not a library.
Chris Lattnerc6185032007-10-21 22:58:11 +0000330 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
331 delete EE;
332 return 0;
Chris Lattner6f3ada52006-05-14 19:01:55 +0000333 }
Chris Lattner726c1ef2006-03-23 05:22:51 +0000334 }
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000335
Brian Gaeke82d82772003-09-03 20:34:19 +0000336 return EE;
337}
338
Chris Lattner8b5295b2007-10-21 22:57:11 +0000339ExecutionEngine *ExecutionEngine::create(Module *M) {
340 return create(new ExistingModuleProvider(M));
341}
342
Misha Brukman4afac182003-10-10 17:45:12 +0000343/// getPointerToGlobal - This returns the address of the specified global
344/// value. This may involve code generation if it's a function.
345///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000346void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000347 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000348 return getPointerToFunction(F);
349
Reid Spenceree448632005-07-12 15:51:55 +0000350 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000351 void *p = state.getGlobalAddressMap(locked)[GV];
352 if (p)
353 return p;
354
355 // Global variable might have been added since interpreter started.
356 if (GlobalVariable *GVar =
357 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
358 EmitGlobalVariable(GVar);
359 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000360 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000361 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000362}
363
Reid Spencer3da59db2006-11-27 01:05:10 +0000364/// This function converts a Constant* into a GenericValue. The interesting
365/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000366/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000367GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000368 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000369 if (isa<UndefValue>(C))
370 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000371
Reid Spencer3da59db2006-11-27 01:05:10 +0000372 // If the value is a ConstantExpr
373 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000374 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000375 switch (CE->getOpcode()) {
376 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000377 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000378 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000379 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000380 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000381 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000382
Reid Spencer8fb0f192007-03-06 03:04:04 +0000383 char* tmp = (char*) Result.PointerVal;
384 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000385 return Result;
386 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000387 case Instruction::Trunc: {
388 GenericValue GV = getConstantValue(Op0);
389 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
390 GV.IntVal = GV.IntVal.trunc(BitWidth);
391 return GV;
392 }
393 case Instruction::ZExt: {
394 GenericValue GV = getConstantValue(Op0);
395 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
396 GV.IntVal = GV.IntVal.zext(BitWidth);
397 return GV;
398 }
399 case Instruction::SExt: {
400 GenericValue GV = getConstantValue(Op0);
401 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
402 GV.IntVal = GV.IntVal.sext(BitWidth);
403 return GV;
404 }
405 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000406 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000407 GenericValue GV = getConstantValue(Op0);
408 GV.FloatVal = float(GV.DoubleVal);
409 return GV;
410 }
411 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000412 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000413 GenericValue GV = getConstantValue(Op0);
414 GV.DoubleVal = double(GV.FloatVal);
415 return GV;
416 }
417 case Instruction::UIToFP: {
418 GenericValue GV = getConstantValue(Op0);
419 if (CE->getType() == Type::FloatTy)
420 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000421 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000422 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000423 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000424 const uint64_t zero[] = {0, 0};
425 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Boothccf596a2007-10-07 11:45:55 +0000426 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen910993e2007-09-21 22:09:37 +0000427 GV.IntVal.getBitWidth(), false,
Dale Johannesen88216af2007-09-30 18:19:03 +0000428 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000429 GV.IntVal = apf.convertToAPInt();
430 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000431 return GV;
432 }
433 case Instruction::SIToFP: {
434 GenericValue GV = getConstantValue(Op0);
435 if (CE->getType() == Type::FloatTy)
436 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000437 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000438 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000439 else if (CE->getType() == Type::X86_FP80Ty) {
440 const uint64_t zero[] = { 0, 0};
441 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Boothccf596a2007-10-07 11:45:55 +0000442 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen910993e2007-09-21 22:09:37 +0000443 GV.IntVal.getBitWidth(), true,
Dale Johannesen88216af2007-09-30 18:19:03 +0000444 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000445 GV.IntVal = apf.convertToAPInt();
446 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000447 return GV;
448 }
449 case Instruction::FPToUI: // double->APInt conversion handles sign
450 case Instruction::FPToSI: {
451 GenericValue GV = getConstantValue(Op0);
452 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
453 if (Op0->getType() == Type::FloatTy)
454 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000455 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000456 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000457 else if (Op0->getType() == Type::X86_FP80Ty) {
458 APFloat apf = APFloat(GV.IntVal);
459 uint64_t v;
460 (void)apf.convertToInteger(&v, BitWidth,
461 CE->getOpcode()==Instruction::FPToSI,
462 APFloat::rmTowardZero);
463 GV.IntVal = v; // endian?
464 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000465 return GV;
466 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000468 GenericValue GV = getConstantValue(Op0);
469 uint32_t PtrWidth = TD->getPointerSizeInBits();
470 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
471 return GV;
472 }
473 case Instruction::IntToPtr: {
474 GenericValue GV = getConstantValue(Op0);
475 uint32_t PtrWidth = TD->getPointerSizeInBits();
476 if (PtrWidth != GV.IntVal.getBitWidth())
477 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
478 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
479 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000480 return GV;
481 }
482 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000483 GenericValue GV = getConstantValue(Op0);
484 const Type* DestTy = CE->getType();
485 switch (Op0->getType()->getTypeID()) {
486 default: assert(0 && "Invalid bitcast operand");
487 case Type::IntegerTyID:
488 assert(DestTy->isFloatingPoint() && "invalid bitcast");
489 if (DestTy == Type::FloatTy)
490 GV.FloatVal = GV.IntVal.bitsToFloat();
491 else if (DestTy == Type::DoubleTy)
492 GV.DoubleVal = GV.IntVal.bitsToDouble();
493 break;
494 case Type::FloatTyID:
495 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
496 GV.IntVal.floatToBits(GV.FloatVal);
497 break;
498 case Type::DoubleTyID:
499 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
500 GV.IntVal.doubleToBits(GV.DoubleVal);
501 break;
502 case Type::PointerTyID:
503 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
504 break; // getConstantValue(Op0) above already converted it
505 }
506 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000507 }
Chris Lattner9a231222003-05-14 17:51:49 +0000508 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000509 case Instruction::Sub:
510 case Instruction::Mul:
511 case Instruction::UDiv:
512 case Instruction::SDiv:
513 case Instruction::URem:
514 case Instruction::SRem:
515 case Instruction::And:
516 case Instruction::Or:
517 case Instruction::Xor: {
518 GenericValue LHS = getConstantValue(Op0);
519 GenericValue RHS = getConstantValue(CE->getOperand(1));
520 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000521 switch (CE->getOperand(0)->getType()->getTypeID()) {
522 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000523 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000524 switch (CE->getOpcode()) {
525 default: assert(0 && "Invalid integer opcode");
526 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
527 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
528 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
529 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
530 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
531 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
532 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
533 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
534 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
535 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
536 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000537 break;
538 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000539 switch (CE->getOpcode()) {
540 default: assert(0 && "Invalid float opcode"); abort();
541 case Instruction::Add:
542 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
543 case Instruction::Sub:
544 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
545 case Instruction::Mul:
546 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
547 case Instruction::FDiv:
548 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
549 case Instruction::FRem:
550 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
551 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000552 break;
553 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000554 switch (CE->getOpcode()) {
555 default: assert(0 && "Invalid double opcode"); abort();
556 case Instruction::Add:
557 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
558 case Instruction::Sub:
559 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
560 case Instruction::Mul:
561 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
562 case Instruction::FDiv:
563 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
564 case Instruction::FRem:
565 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
566 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000567 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000568 case Type::X86_FP80TyID:
569 case Type::PPC_FP128TyID:
570 case Type::FP128TyID: {
571 APFloat apfLHS = APFloat(LHS.IntVal);
572 switch (CE->getOpcode()) {
573 default: assert(0 && "Invalid long double opcode"); abort();
574 case Instruction::Add:
575 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
576 GV.IntVal = apfLHS.convertToAPInt();
577 break;
578 case Instruction::Sub:
579 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
580 GV.IntVal = apfLHS.convertToAPInt();
581 break;
582 case Instruction::Mul:
583 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
584 GV.IntVal = apfLHS.convertToAPInt();
585 break;
586 case Instruction::FDiv:
587 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
588 GV.IntVal = apfLHS.convertToAPInt();
589 break;
590 case Instruction::FRem:
591 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
592 GV.IntVal = apfLHS.convertToAPInt();
593 break;
594 }
595 }
596 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000597 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000598 return GV;
599 }
Chris Lattner9a231222003-05-14 17:51:49 +0000600 default:
601 break;
602 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000603 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000604 abort();
605 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000606
Reid Spencerbce30f12007-03-06 22:23:15 +0000607 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000608 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000609 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000610 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000611 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000612 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000613 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000614 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000615 case Type::X86_FP80TyID:
616 case Type::FP128TyID:
617 case Type::PPC_FP128TyID:
618 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
619 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000620 case Type::IntegerTyID:
621 Result.IntVal = cast<ConstantInt>(C)->getValue();
622 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000623 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000624 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000625 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000626 else if (const Function *F = dyn_cast<Function>(C))
627 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
628 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
629 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
630 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000631 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000632 break;
633 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000634 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000635 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000636 }
637 return Result;
638}
639
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000640/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
641/// with the integer held in IntVal.
642static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
643 unsigned StoreBytes) {
644 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
645 uint8_t *Src = (uint8_t *)IntVal.getRawData();
646
647 if (sys::littleEndianHost())
648 // Little-endian host - the source is ordered from LSB to MSB. Order the
649 // destination from LSB to MSB: Do a straight copy.
650 memcpy(Dst, Src, StoreBytes);
651 else {
652 // Big-endian host - the source is an array of 64 bit words ordered from
653 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
654 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
655 while (StoreBytes > sizeof(uint64_t)) {
656 StoreBytes -= sizeof(uint64_t);
657 // May not be aligned so use memcpy.
658 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
659 Src += sizeof(uint64_t);
660 }
661
662 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
663 }
664}
665
Nate Begeman37efe672006-04-22 18:53:45 +0000666/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
667/// is the address of the memory at which to store Val, cast to GenericValue *.
668/// It is not a pointer to a GenericValue containing the address at which to
669/// store Val.
Reid Spencer415c1f72007-03-06 05:03:16 +0000670void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000671 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000672 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
673
Reid Spencer8fb0f192007-03-06 03:04:04 +0000674 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000675 case Type::IntegerTyID:
676 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000677 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000678 case Type::FloatTyID:
679 *((float*)Ptr) = Val.FloatVal;
680 break;
681 case Type::DoubleTyID:
682 *((double*)Ptr) = Val.DoubleVal;
683 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000684 case Type::X86_FP80TyID: {
685 uint16_t *Dest = (uint16_t*)Ptr;
686 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
687 // This is endian dependent, but it will only work on x86 anyway.
688 Dest[0] = Src[4];
689 Dest[1] = Src[0];
690 Dest[2] = Src[1];
691 Dest[3] = Src[2];
692 Dest[4] = Src[3];
693 break;
694 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000695 case Type::PointerTyID:
696 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
697 if (StoreBytes != sizeof(PointerTy))
698 memset(Ptr, 0, StoreBytes);
699
Reid Spencer8fb0f192007-03-06 03:04:04 +0000700 *((PointerTy*)Ptr) = Val.PointerVal;
701 break;
702 default:
703 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000704 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000705
706 if (sys::littleEndianHost() != getTargetData()->isLittleEndian())
707 // Host and target are different endian - reverse the stored bytes.
708 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
709}
710
711/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
712/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
713static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
714 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
715 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
716
717 if (sys::littleEndianHost())
718 // Little-endian host - the destination must be ordered from LSB to MSB.
719 // The source is ordered from LSB to MSB: Do a straight copy.
720 memcpy(Dst, Src, LoadBytes);
721 else {
722 // Big-endian - the destination is an array of 64 bit words ordered from
723 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
724 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
725 // a word.
726 while (LoadBytes > sizeof(uint64_t)) {
727 LoadBytes -= sizeof(uint64_t);
728 // May not be aligned so use memcpy.
729 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
730 Dst += sizeof(uint64_t);
731 }
732
733 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
734 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000735}
736
Misha Brukman4afac182003-10-10 17:45:12 +0000737/// FIXME: document
738///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000739void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Reid Spencerf0f09a92007-03-03 08:36:29 +0000740 GenericValue *Ptr,
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000741 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000742 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000743
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000744 if (sys::littleEndianHost() != getTargetData()->isLittleEndian()) {
745 // Host and target are different endian - reverse copy the stored
746 // bytes into a buffer, and load from that.
747 uint8_t *Src = (uint8_t*)Ptr;
748 uint8_t *Buf = (uint8_t*)alloca(LoadBytes);
749 std::reverse_copy(Src, Src + LoadBytes, Buf);
750 Ptr = (GenericValue*)Buf;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000751 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000752
753 switch (Ty->getTypeID()) {
754 case Type::IntegerTyID:
755 // An APInt with all words initially zero.
756 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
757 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
758 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000759 case Type::FloatTyID:
760 Result.FloatVal = *((float*)Ptr);
761 break;
762 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000763 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000764 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000765 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000766 Result.PointerVal = *((PointerTy*)Ptr);
767 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000768 case Type::X86_FP80TyID: {
769 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000770 // FIXME: Will not trap if loading a signaling NaN.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000771 uint16_t *p = (uint16_t*)Ptr;
772 union {
773 uint16_t x[8];
774 uint64_t y[2];
775 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000776 x[0] = p[1];
777 x[1] = p[2];
778 x[2] = p[3];
779 x[3] = p[4];
780 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000781 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000782 break;
783 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000784 default:
785 cerr << "Cannot load value of type " << *Ty << "!\n";
786 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000787 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000788}
789
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000790// InitializeMemory - Recursive function to apply a Constant value into the
791// specified memory location...
792//
793void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000794 if (isa<UndefValue>(Init)) {
795 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000796 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000797 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000798 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000799 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
800 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
801 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000802 } else if (isa<ConstantAggregateZero>(Init)) {
803 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
804 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000805 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000806 GenericValue Val = getConstantValue(Init);
807 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
808 return;
809 }
810
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000811 switch (Init->getType()->getTypeID()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000812 case Type::ArrayTyID: {
813 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000814 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000815 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000816 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
817 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000818 return;
819 }
820
821 case Type::StructTyID: {
822 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
823 const StructLayout *SL =
Owen Andersona69571c2006-05-03 01:29:57 +0000824 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000825 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000826 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000827 return;
828 }
829
830 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000831 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000832 assert(0 && "Unknown constant type to initialize memory with!");
833 }
834}
835
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000836/// EmitGlobals - Emit all of the global variables to memory, storing their
837/// addresses into GlobalAddress. This must make sure to copy the contents of
838/// their initializers into the memory.
839///
840void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000841 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000842
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000843 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000844 // to hold them. If there is more than one module, do a prepass over globals
845 // to figure out how the different modules should link together.
846 //
847 std::map<std::pair<std::string, const Type*>,
848 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000849
Chris Lattnerfe854032006-08-16 01:24:12 +0000850 if (Modules.size() != 1) {
851 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
852 Module &M = *Modules[m]->getModule();
853 for (Module::const_global_iterator I = M.global_begin(),
854 E = M.global_end(); I != E; ++I) {
855 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000856 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000857 GV->hasAppendingLinkage() || !GV->hasName())
858 continue;// Ignore external globals and globals with internal linkage.
859
860 const GlobalValue *&GVEntry =
861 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
862
863 // If this is the first time we've seen this global, it is the canonical
864 // version.
865 if (!GVEntry) {
866 GVEntry = GV;
867 continue;
868 }
869
870 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000871 if (GVEntry->hasExternalLinkage() ||
872 GVEntry->hasDLLImportLinkage() ||
873 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000874 continue;
875
876 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
877 // symbol.
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000878 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000879 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000880 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000881 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000882 }
883
884 std::vector<const GlobalValue*> NonCanonicalGlobals;
885 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
886 Module &M = *Modules[m]->getModule();
887 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
888 I != E; ++I) {
889 // In the multi-module case, see what this global maps to.
890 if (!LinkedGlobalsMap.empty()) {
891 if (const GlobalValue *GVEntry =
892 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
893 // If something else is the canonical global, ignore this one.
894 if (GVEntry != &*I) {
895 NonCanonicalGlobals.push_back(I);
896 continue;
897 }
898 }
899 }
900
Reid Spencer5cbf9852007-01-30 20:08:39 +0000901 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000902 // Get the type of the global.
903 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000904
Chris Lattnerfe854032006-08-16 01:24:12 +0000905 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000906 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000907 addGlobalMapping(I, new char[Size]);
908 } else {
909 // External variable reference. Try to use the dynamic loader to
910 // get a pointer to it.
911 if (void *SymAddr =
912 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
913 addGlobalMapping(I, SymAddr);
914 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000915 cerr << "Could not resolve external global address: "
916 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000917 abort();
918 }
919 }
920 }
921
922 // If there are multiple modules, map the non-canonical globals to their
923 // canonical location.
924 if (!NonCanonicalGlobals.empty()) {
925 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
926 const GlobalValue *GV = NonCanonicalGlobals[i];
927 const GlobalValue *CGV =
928 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
929 void *Ptr = getPointerToGlobalIfAvailable(CGV);
930 assert(Ptr && "Canonical global wasn't codegen'd!");
931 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
932 }
933 }
934
Reid Spencera54b7cb2007-01-12 07:05:14 +0000935 // Now that all of the globals are set up in memory, loop through them all
936 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000937 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
938 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000939 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000940 if (!LinkedGlobalsMap.empty()) {
941 if (const GlobalValue *GVEntry =
942 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
943 if (GVEntry != &*I) // Not the canonical variable.
944 continue;
945 }
946 EmitGlobalVariable(I);
947 }
948 }
949 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000950}
951
952// EmitGlobalVariable - This method emits the specified global variable to the
953// address specified in GlobalAddresses, or allocates new memory if it's not
954// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000955void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000956 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000957 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000958
Chris Lattnerc07ed132003-12-20 03:36:47 +0000959 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000960 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000961 if (GA == 0) {
962 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000963 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000964 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000965 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000966
Chris Lattner24b0a182003-12-20 02:45:37 +0000967 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000968 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000969 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000970}