blob: 512c4520e07ee61108f65ec8d66853197363dfbf [file] [log] [blame]
Misha Brukman857c21b2003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukman835702a2005-04-21 22:36:52 +00009//
Chris Lattner996fe012002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattneree937c82003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Chris Lattner996fe012002-12-24 00:01:05 +000016#include "llvm/Constants.h"
Misha Brukman260b0c82003-10-16 21:18:05 +000017#include "llvm/DerivedTypes.h"
Chris Lattner996fe012002-12-24 00:01:05 +000018#include "llvm/Module.h"
Misha Brukman260b0c82003-10-16 21:18:05 +000019#include "llvm/ModuleProvider.h"
Reid Spencer70e37272004-11-29 14:11:29 +000020#include "llvm/ADT/Statistic.h"
Misha Brukman260b0c82003-10-16 21:18:05 +000021#include "llvm/ExecutionEngine/ExecutionEngine.h"
Chris Lattnerad481312003-09-05 20:08:15 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Chris Lattner6d8dd182006-05-08 22:00:52 +000024#include "llvm/Support/MutexGuard.h"
Reid Spencer70e37272004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
26#include "llvm/Target/TargetData.h"
Jeff Cohen72ac14e2007-03-12 17:57:00 +000027#include <math.h>
Chris Lattner29681de2003-11-19 21:08:57 +000028using namespace llvm;
Chris Lattner996fe012002-12-24 00:01:05 +000029
Chris Lattnerc346ecd2006-12-19 22:43:32 +000030STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
31STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattner996fe012002-12-24 00:01:05 +000032
Chris Lattner2d52c1b2006-03-22 06:07:50 +000033ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
34ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
35
Chris Lattner0621cae2006-08-16 01:24:12 +000036ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
Chris Lattner87aee742006-11-09 19:31:15 +000037 LazyCompilationDisabled = false;
Chris Lattner0621cae2006-08-16 01:24:12 +000038 Modules.push_back(P);
Misha Brukman260b0c82003-10-16 21:18:05 +000039 assert(P && "ModuleProvider is null?");
40}
41
Chris Lattner0621cae2006-08-16 01:24:12 +000042ExecutionEngine::ExecutionEngine(Module *M) {
Chris Lattner87aee742006-11-09 19:31:15 +000043 LazyCompilationDisabled = false;
Misha Brukmane37fb9d2003-10-17 18:31:59 +000044 assert(M && "Module is null?");
Chris Lattner0621cae2006-08-16 01:24:12 +000045 Modules.push_back(new ExistingModuleProvider(M));
Misha Brukman260b0c82003-10-16 21:18:05 +000046}
47
Brian Gaeke92f8b302003-09-04 22:57:27 +000048ExecutionEngine::~ExecutionEngine() {
Reid Spencer603682a2007-03-03 18:19:18 +000049 clearAllGlobalMappings();
Chris Lattner0621cae2006-08-16 01:24:12 +000050 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
51 delete Modules[i];
Brian Gaeke92f8b302003-09-04 22:57:27 +000052}
53
Devang Patel324fe892007-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);
63 return MP->releaseModule(ErrInfo);
64 }
65 }
66 return NULL;
67}
68
Chris Lattner0621cae2006-08-16 01:24:12 +000069/// FindFunctionNamed - Search all of the active modules to find the one that
70/// defines FnName. This is very slow operation and shouldn't be used for
71/// general code.
72Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
73 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer1241d6d2007-02-05 21:19:13 +000074 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattner0621cae2006-08-16 01:24:12 +000075 return F;
76 }
77 return 0;
78}
79
80
Chris Lattner6d8dd182006-05-08 22:00:52 +000081/// addGlobalMapping - Tell the execution engine that the specified global is
82/// at the specified location. This is used internally as functions are JIT'd
83/// and as global variables are laid out in memory. It can and should also be
84/// used by clients of the EE that want to have an LLVM global overlay
85/// existing data in memory.
86void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
87 MutexGuard locked(lock);
88
89 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
90 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
91 CurVal = Addr;
92
93 // If we are using the reverse mapping, add it too
94 if (!state.getGlobalAddressReverseMap(locked).empty()) {
95 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
96 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
97 V = GV;
98 }
99}
100
101/// clearAllGlobalMappings - Clear all global mappings and start over again
102/// use in dynamic compilation scenarios when you want to move globals
103void ExecutionEngine::clearAllGlobalMappings() {
104 MutexGuard locked(lock);
105
106 state.getGlobalAddressMap(locked).clear();
107 state.getGlobalAddressReverseMap(locked).clear();
108}
109
110/// updateGlobalMapping - Replace an existing mapping for GV with a new
111/// address. This updates both maps as required. If "Addr" is null, the
112/// entry for the global is removed from the mappings.
113void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
114 MutexGuard locked(lock);
115
116 // Deleting from the mapping?
117 if (Addr == 0) {
118 state.getGlobalAddressMap(locked).erase(GV);
119 if (!state.getGlobalAddressReverseMap(locked).empty())
120 state.getGlobalAddressReverseMap(locked).erase(Addr);
121 return;
122 }
123
124 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
125 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
126 state.getGlobalAddressReverseMap(locked).erase(CurVal);
127 CurVal = Addr;
128
129 // If we are using the reverse mapping, add it too
130 if (!state.getGlobalAddressReverseMap(locked).empty()) {
131 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
132 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
133 V = GV;
134 }
135}
136
137/// getPointerToGlobalIfAvailable - This returns the address of the specified
138/// global value if it is has already been codegen'd, otherwise it returns null.
139///
140void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
141 MutexGuard locked(lock);
142
143 std::map<const GlobalValue*, void*>::iterator I =
144 state.getGlobalAddressMap(locked).find(GV);
145 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
146}
147
Chris Lattner748e8572003-12-31 20:21:04 +0000148/// getGlobalValueAtAddress - Return the LLVM global value object that starts
149/// at the specified address.
150///
151const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spencer79876f52005-07-12 15:51:55 +0000152 MutexGuard locked(lock);
153
Chris Lattner748e8572003-12-31 20:21:04 +0000154 // If we haven't computed the reverse mapping yet, do so first.
Reid Spencer79876f52005-07-12 15:51:55 +0000155 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattner6d8dd182006-05-08 22:00:52 +0000156 for (std::map<const GlobalValue*, void *>::iterator
157 I = state.getGlobalAddressMap(locked).begin(),
158 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
159 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
160 I->first));
Chris Lattner748e8572003-12-31 20:21:04 +0000161 }
162
163 std::map<void *, const GlobalValue*>::iterator I =
Reid Spencer79876f52005-07-12 15:51:55 +0000164 state.getGlobalAddressReverseMap(locked).find(Addr);
165 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner748e8572003-12-31 20:21:04 +0000166}
Chris Lattner5a0d4822003-12-26 06:50:30 +0000167
168// CreateArgv - Turn a vector of strings into a nice argv style array of
169// pointers to null terminated strings.
170//
171static void *CreateArgv(ExecutionEngine *EE,
172 const std::vector<std::string> &InputArgv) {
Owen Anderson20a631f2006-05-03 01:29:57 +0000173 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000174 char *Result = new char[(InputArgv.size()+1)*PtrSize];
175
Bill Wendling5834fdb2006-11-27 23:54:50 +0000176 DOUT << "ARGV = " << (void*)Result << "\n";
Reid Spencer0d54e782006-12-31 05:51:36 +0000177 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
Chris Lattner5a0d4822003-12-26 06:50:30 +0000178
179 for (unsigned i = 0; i != InputArgv.size(); ++i) {
180 unsigned Size = InputArgv[i].size()+1;
181 char *Dest = new char[Size];
Bill Wendling5834fdb2006-11-27 23:54:50 +0000182 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukman835702a2005-04-21 22:36:52 +0000183
Chris Lattner5a0d4822003-12-26 06:50:30 +0000184 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
185 Dest[Size-1] = 0;
Misha Brukman835702a2005-04-21 22:36:52 +0000186
Chris Lattner5a0d4822003-12-26 06:50:30 +0000187 // Endian safe: Result[i] = (PointerTy)Dest;
188 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
189 SBytePtr);
190 }
191
192 // Null terminate it
193 EE->StoreValueToMemory(PTOGV(0),
194 (GenericValue*)(Result+InputArgv.size()*PtrSize),
195 SBytePtr);
196 return Result;
197}
198
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000199
200/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattner0621cae2006-08-16 01:24:12 +0000201/// the static constructors or destructors for a program, depending on the
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000202/// value of isDtors.
203void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
204 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000205
Chris Lattner0621cae2006-08-16 01:24:12 +0000206 // Execute global ctors/dtors for each module in the program.
207 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
208 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
209
210 // If this global has internal linkage, or if it has a use, then it must be
211 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
212 // this is the case, don't execute any of the global ctors, __main will do
213 // it.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000214 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattner0621cae2006-08-16 01:24:12 +0000215
216 // Should be an array of '{ int, void ()* }' structs. The first value is
217 // the init priority, which we ignore.
218 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
219 if (!InitList) continue;
220 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
221 if (ConstantStruct *CS =
222 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
223 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000224
Chris Lattner0621cae2006-08-16 01:24:12 +0000225 Constant *FP = CS->getOperand(1);
226 if (FP->isNullValue())
227 break; // Found a null terminator, exit.
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000228
Chris Lattner0621cae2006-08-16 01:24:12 +0000229 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000230 if (CE->isCast())
Chris Lattner0621cae2006-08-16 01:24:12 +0000231 FP = CE->getOperand(0);
232 if (Function *F = dyn_cast<Function>(FP)) {
233 // Execute the ctor/dtor function!
234 runFunction(F, std::vector<GenericValue>());
235 }
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000236 }
Chris Lattner0621cae2006-08-16 01:24:12 +0000237 }
Chris Lattnerfaae50b2006-03-08 18:42:46 +0000238}
239
Chris Lattner5a0d4822003-12-26 06:50:30 +0000240/// runFunctionAsMain - This is a helper function which wraps runFunction to
241/// handle the common task of starting up main with the specified argc, argv,
242/// and envp parameters.
243int ExecutionEngine::runFunctionAsMain(Function *Fn,
244 const std::vector<std::string> &argv,
245 const char * const * envp) {
246 std::vector<GenericValue> GVArgs;
247 GenericValue GVArgc;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000248 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000249
250 // Check main() type
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000251 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000252 const FunctionType *FTy = Fn->getFunctionType();
253 const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty));
254 switch (NumArgs) {
255 case 3:
256 if (FTy->getParamType(2) != PPInt8Ty) {
257 cerr << "Invalid type for third argument of main() supplied\n";
258 abort();
259 }
Anton Korobeynikovb7818862007-06-03 19:20:49 +0000260 // FALLS THROUGH
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000261 case 2:
262 if (FTy->getParamType(1) != PPInt8Ty) {
263 cerr << "Invalid type for second argument of main() supplied\n";
264 abort();
265 }
Anton Korobeynikovb7818862007-06-03 19:20:49 +0000266 // FALLS THROUGH
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000267 case 1:
268 if (FTy->getParamType(0) != Type::Int32Ty) {
269 cerr << "Invalid type for first argument of main() supplied\n";
270 abort();
271 }
Anton Korobeynikovb7818862007-06-03 19:20:49 +0000272 // FALLS THROUGH
Anton Korobeynikov8c32c112007-06-03 19:17:35 +0000273 case 0:
274 if (FTy->getReturnType() != Type::Int32Ty &&
275 FTy->getReturnType() != Type::VoidTy) {
276 cerr << "Invalid return type of main() supplied\n";
277 abort();
278 }
279 break;
280 default:
281 cerr << "Invalid number of arguments of main() supplied\n";
282 abort();
283 }
284
Chris Lattnerb1cad0b2004-08-16 01:05:35 +0000285 if (NumArgs) {
286 GVArgs.push_back(GVArgc); // Arg #0 = argc.
287 if (NumArgs > 1) {
288 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
289 assert(((char **)GVTOP(GVArgs[1]))[0] &&
290 "argv[0] was null after CreateArgv");
291 if (NumArgs > 2) {
292 std::vector<std::string> EnvVars;
293 for (unsigned i = 0; envp[i]; ++i)
294 EnvVars.push_back(envp[i]);
295 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
296 }
297 }
298 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000299 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner5a0d4822003-12-26 06:50:30 +0000300}
301
Misha Brukman260b0c82003-10-16 21:18:05 +0000302/// If possible, create a JIT, unless the caller specifically requests an
303/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukman835702a2005-04-21 22:36:52 +0000304/// NULL is returned.
Misha Brukman857c21b2003-10-10 17:45:12 +0000305///
Misha Brukman835702a2005-04-21 22:36:52 +0000306ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencer603682a2007-03-03 18:19:18 +0000307 bool ForceInterpreter,
308 std::string *ErrorStr) {
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000309 ExecutionEngine *EE = 0;
310
Chris Lattnerc8c6c032003-12-28 09:44:37 +0000311 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2d52c1b2006-03-22 06:07:50 +0000312 if (!ForceInterpreter && JITCtor)
Reid Spencer603682a2007-03-03 18:19:18 +0000313 EE = JITCtor(MP, ErrorStr);
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000314
315 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2d52c1b2006-03-22 06:07:50 +0000316 if (EE == 0 && InterpCtor)
Reid Spencer603682a2007-03-03 18:19:18 +0000317 EE = InterpCtor(MP, ErrorStr);
Chris Lattnerc8c6c032003-12-28 09:44:37 +0000318
Chris Lattner0b2de9f2006-03-23 05:22:51 +0000319 if (EE) {
Misha Brukman835702a2005-04-21 22:36:52 +0000320 // Make sure we can resolve symbols in the program as well. The zero arg
Reid Spencer70e37272004-11-29 14:11:29 +0000321 // to the function tells DynamicLibrary to load the program, not a library.
Chris Lattner63539382006-05-14 19:01:55 +0000322 try {
323 sys::DynamicLibrary::LoadLibraryPermanently(0);
324 } catch (...) {
325 }
Chris Lattner0b2de9f2006-03-23 05:22:51 +0000326 }
Reid Spencer70e37272004-11-29 14:11:29 +0000327
Brian Gaeke4bd3bd52003-09-03 20:34:19 +0000328 return EE;
329}
330
Misha Brukman857c21b2003-10-10 17:45:12 +0000331/// getPointerToGlobal - This returns the address of the specified global
332/// value. This may involve code generation if it's a function.
333///
Chris Lattner996fe012002-12-24 00:01:05 +0000334void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke1678e852003-08-13 18:16:14 +0000335 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattner996fe012002-12-24 00:01:05 +0000336 return getPointerToFunction(F);
337
Reid Spencer79876f52005-07-12 15:51:55 +0000338 MutexGuard locked(lock);
Jeff Cohen69e849012006-02-07 05:11:57 +0000339 void *p = state.getGlobalAddressMap(locked)[GV];
340 if (p)
341 return p;
342
343 // Global variable might have been added since interpreter started.
344 if (GlobalVariable *GVar =
345 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
346 EmitGlobalVariable(GVar);
347 else
Chris Lattner4da5e172007-02-14 06:20:04 +0000348 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spencer79876f52005-07-12 15:51:55 +0000349 return state.getGlobalAddressMap(locked)[GV];
Chris Lattner996fe012002-12-24 00:01:05 +0000350}
351
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000352/// This function converts a Constant* into a GenericValue. The interesting
353/// part is if C is a ConstantExpr.
Reid Spencer2dc9f132007-08-11 15:57:56 +0000354/// @brief Get a GenericValue for a Constant*
Chris Lattner996fe012002-12-24 00:01:05 +0000355GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000356 // If its undefined, return the garbage.
Reid Spencer4fd528f2007-03-06 22:23:15 +0000357 if (isa<UndefValue>(C))
358 return GenericValue();
Chris Lattner9de0d142003-04-23 19:01:49 +0000359
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000360 // If the value is a ConstantExpr
361 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000362 Constant *Op0 = CE->getOperand(0);
Chris Lattner9de0d142003-04-23 19:01:49 +0000363 switch (CE->getOpcode()) {
364 case Instruction::GetElementPtr: {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000365 // Compute the index
Reid Spencer4fd528f2007-03-06 22:23:15 +0000366 GenericValue Result = getConstantValue(Op0);
Chris Lattnerc44bd782007-02-10 20:35:22 +0000367 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattner9de0d142003-04-23 19:01:49 +0000368 uint64_t Offset =
Reid Spencer4fd528f2007-03-06 22:23:15 +0000369 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukman835702a2005-04-21 22:36:52 +0000370
Reid Spencer87aa65f2007-03-06 03:04:04 +0000371 char* tmp = (char*) Result.PointerVal;
372 Result = PTOGV(tmp + Offset);
Chris Lattner9de0d142003-04-23 19:01:49 +0000373 return Result;
374 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000375 case Instruction::Trunc: {
376 GenericValue GV = getConstantValue(Op0);
377 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
378 GV.IntVal = GV.IntVal.trunc(BitWidth);
379 return GV;
380 }
381 case Instruction::ZExt: {
382 GenericValue GV = getConstantValue(Op0);
383 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
384 GV.IntVal = GV.IntVal.zext(BitWidth);
385 return GV;
386 }
387 case Instruction::SExt: {
388 GenericValue GV = getConstantValue(Op0);
389 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
390 GV.IntVal = GV.IntVal.sext(BitWidth);
391 return GV;
392 }
393 case Instruction::FPTrunc: {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000394 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000395 GenericValue GV = getConstantValue(Op0);
396 GV.FloatVal = float(GV.DoubleVal);
397 return GV;
398 }
399 case Instruction::FPExt:{
Dale Johannesena1336cf2007-09-17 18:44:13 +0000400 // FIXME long double
Reid Spencer4fd528f2007-03-06 22:23:15 +0000401 GenericValue GV = getConstantValue(Op0);
402 GV.DoubleVal = double(GV.FloatVal);
403 return GV;
404 }
405 case Instruction::UIToFP: {
406 GenericValue GV = getConstantValue(Op0);
407 if (CE->getType() == Type::FloatTy)
408 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesena1336cf2007-09-17 18:44:13 +0000409 else if (CE->getType() == Type::DoubleTy)
Reid Spencer4fd528f2007-03-06 22:23:15 +0000410 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen42305122007-09-21 22:09:37 +0000411 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesena1336cf2007-09-17 18:44:13 +0000412 const uint64_t zero[] = {0, 0};
413 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Booth5f009732007-10-07 11:45:55 +0000414 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen42305122007-09-21 22:09:37 +0000415 GV.IntVal.getBitWidth(), false,
Dale Johannesen91506522007-09-30 18:19:03 +0000416 APFloat::rmNearestTiesToEven);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000417 GV.IntVal = apf.convertToAPInt();
418 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000419 return GV;
420 }
421 case Instruction::SIToFP: {
422 GenericValue GV = getConstantValue(Op0);
423 if (CE->getType() == Type::FloatTy)
424 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesena1336cf2007-09-17 18:44:13 +0000425 else if (CE->getType() == Type::DoubleTy)
Reid Spencer4fd528f2007-03-06 22:23:15 +0000426 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesena1336cf2007-09-17 18:44:13 +0000427 else if (CE->getType() == Type::X86_FP80Ty) {
428 const uint64_t zero[] = { 0, 0};
429 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Booth5f009732007-10-07 11:45:55 +0000430 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen42305122007-09-21 22:09:37 +0000431 GV.IntVal.getBitWidth(), true,
Dale Johannesen91506522007-09-30 18:19:03 +0000432 APFloat::rmNearestTiesToEven);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000433 GV.IntVal = apf.convertToAPInt();
434 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000435 return GV;
436 }
437 case Instruction::FPToUI: // double->APInt conversion handles sign
438 case Instruction::FPToSI: {
439 GenericValue GV = getConstantValue(Op0);
440 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
441 if (Op0->getType() == Type::FloatTy)
442 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000443 else if (Op0->getType() == Type::DoubleTy)
Reid Spencer4fd528f2007-03-06 22:23:15 +0000444 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesena1336cf2007-09-17 18:44:13 +0000445 else if (Op0->getType() == Type::X86_FP80Ty) {
446 APFloat apf = APFloat(GV.IntVal);
447 uint64_t v;
448 (void)apf.convertToInteger(&v, BitWidth,
449 CE->getOpcode()==Instruction::FPToSI,
450 APFloat::rmTowardZero);
451 GV.IntVal = v; // endian?
452 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000453 return GV;
454 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000455 case Instruction::PtrToInt: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000456 GenericValue GV = getConstantValue(Op0);
457 uint32_t PtrWidth = TD->getPointerSizeInBits();
458 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
459 return GV;
460 }
461 case Instruction::IntToPtr: {
462 GenericValue GV = getConstantValue(Op0);
463 uint32_t PtrWidth = TD->getPointerSizeInBits();
464 if (PtrWidth != GV.IntVal.getBitWidth())
465 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
466 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
467 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000468 return GV;
469 }
470 case Instruction::BitCast: {
Reid Spencer4fd528f2007-03-06 22:23:15 +0000471 GenericValue GV = getConstantValue(Op0);
472 const Type* DestTy = CE->getType();
473 switch (Op0->getType()->getTypeID()) {
474 default: assert(0 && "Invalid bitcast operand");
475 case Type::IntegerTyID:
476 assert(DestTy->isFloatingPoint() && "invalid bitcast");
477 if (DestTy == Type::FloatTy)
478 GV.FloatVal = GV.IntVal.bitsToFloat();
479 else if (DestTy == Type::DoubleTy)
480 GV.DoubleVal = GV.IntVal.bitsToDouble();
481 break;
482 case Type::FloatTyID:
483 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
484 GV.IntVal.floatToBits(GV.FloatVal);
485 break;
486 case Type::DoubleTyID:
487 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
488 GV.IntVal.doubleToBits(GV.DoubleVal);
489 break;
490 case Type::PointerTyID:
491 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
492 break; // getConstantValue(Op0) above already converted it
493 }
494 return GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000495 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000496 case Instruction::Add:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000497 case Instruction::Sub:
498 case Instruction::Mul:
499 case Instruction::UDiv:
500 case Instruction::SDiv:
501 case Instruction::URem:
502 case Instruction::SRem:
503 case Instruction::And:
504 case Instruction::Or:
505 case Instruction::Xor: {
506 GenericValue LHS = getConstantValue(Op0);
507 GenericValue RHS = getConstantValue(CE->getOperand(1));
508 GenericValue GV;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000509 switch (CE->getOperand(0)->getType()->getTypeID()) {
510 default: assert(0 && "Bad add type!"); abort();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000511 case Type::IntegerTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000512 switch (CE->getOpcode()) {
513 default: assert(0 && "Invalid integer opcode");
514 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
515 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
516 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
517 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
518 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
519 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
520 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
521 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
522 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
523 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
524 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000525 break;
526 case Type::FloatTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000527 switch (CE->getOpcode()) {
528 default: assert(0 && "Invalid float opcode"); abort();
529 case Instruction::Add:
530 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
531 case Instruction::Sub:
532 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
533 case Instruction::Mul:
534 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
535 case Instruction::FDiv:
536 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
537 case Instruction::FRem:
538 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
539 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000540 break;
541 case Type::DoubleTyID:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000542 switch (CE->getOpcode()) {
543 default: assert(0 && "Invalid double opcode"); abort();
544 case Instruction::Add:
545 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
546 case Instruction::Sub:
547 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
548 case Instruction::Mul:
549 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
550 case Instruction::FDiv:
551 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
552 case Instruction::FRem:
553 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
554 }
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000555 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000556 case Type::X86_FP80TyID:
557 case Type::PPC_FP128TyID:
558 case Type::FP128TyID: {
559 APFloat apfLHS = APFloat(LHS.IntVal);
560 switch (CE->getOpcode()) {
561 default: assert(0 && "Invalid long double opcode"); abort();
562 case Instruction::Add:
563 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
564 GV.IntVal = apfLHS.convertToAPInt();
565 break;
566 case Instruction::Sub:
567 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
568 GV.IntVal = apfLHS.convertToAPInt();
569 break;
570 case Instruction::Mul:
571 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
572 GV.IntVal = apfLHS.convertToAPInt();
573 break;
574 case Instruction::FDiv:
575 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
576 GV.IntVal = apfLHS.convertToAPInt();
577 break;
578 case Instruction::FRem:
579 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
580 GV.IntVal = apfLHS.convertToAPInt();
581 break;
582 }
583 }
584 break;
Chris Lattnerc4e6bb52004-07-11 08:01:11 +0000585 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000586 return GV;
587 }
Chris Lattner68cbcc32003-05-14 17:51:49 +0000588 default:
589 break;
590 }
Reid Spencer4fd528f2007-03-06 22:23:15 +0000591 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner68cbcc32003-05-14 17:51:49 +0000592 abort();
593 }
Misha Brukman835702a2005-04-21 22:36:52 +0000594
Reid Spencer4fd528f2007-03-06 22:23:15 +0000595 GenericValue Result;
Chris Lattner6b727592004-06-17 18:19:28 +0000596 switch (C->getType()->getTypeID()) {
Reid Spencer87aa65f2007-03-06 03:04:04 +0000597 case Type::FloatTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000598 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000599 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000600 case Type::DoubleTyID:
Dale Johannesenbed9dc42007-09-06 18:13:44 +0000601 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer87aa65f2007-03-06 03:04:04 +0000602 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000603 case Type::X86_FP80TyID:
604 case Type::FP128TyID:
605 case Type::PPC_FP128TyID:
606 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
607 break;
Reid Spencer87aa65f2007-03-06 03:04:04 +0000608 case Type::IntegerTyID:
609 Result.IntVal = cast<ConstantInt>(C)->getValue();
610 break;
Chris Lattner996fe012002-12-24 00:01:05 +0000611 case Type::PointerTyID:
Reid Spencer6a0fd732004-07-18 00:41:27 +0000612 if (isa<ConstantPointerNull>(C))
Chris Lattner996fe012002-12-24 00:01:05 +0000613 Result.PointerVal = 0;
Reid Spencer6a0fd732004-07-18 00:41:27 +0000614 else if (const Function *F = dyn_cast<Function>(C))
615 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
616 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
617 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
618 else
Chris Lattner996fe012002-12-24 00:01:05 +0000619 assert(0 && "Unknown constant pointer type!");
Chris Lattner996fe012002-12-24 00:01:05 +0000620 break;
621 default:
Reid Spencer4fd528f2007-03-06 22:23:15 +0000622 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattner9de0d142003-04-23 19:01:49 +0000623 abort();
Chris Lattner996fe012002-12-24 00:01:05 +0000624 }
625 return Result;
626}
627
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000628/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
629/// is the address of the memory at which to store Val, cast to GenericValue *.
630/// It is not a pointer to a GenericValue containing the address at which to
631/// store Val.
Misha Brukman857c21b2003-10-10 17:45:12 +0000632///
Reid Spencer4e427902007-03-06 05:03:16 +0000633void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman857c21b2003-10-10 17:45:12 +0000634 const Type *Ty) {
Reid Spencer87aa65f2007-03-06 03:04:04 +0000635 switch (Ty->getTypeID()) {
636 case Type::IntegerTyID: {
637 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
638 GenericValue TmpVal = Val;
639 if (BitWidth <= 8)
640 *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
641 else if (BitWidth <= 16) {
642 *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
643 } else if (BitWidth <= 32) {
644 *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
645 } else if (BitWidth <= 64) {
Reid Spencer4e427902007-03-06 05:03:16 +0000646 *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
Reid Spencer87aa65f2007-03-06 03:04:04 +0000647 } else {
648 uint64_t *Dest = (uint64_t*)Ptr;
649 const uint64_t *Src = Val.IntVal.getRawData();
650 for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
651 Dest[i] = Src[i];
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000652 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000653 break;
654 }
655 case Type::FloatTyID:
656 *((float*)Ptr) = Val.FloatVal;
657 break;
658 case Type::DoubleTyID:
659 *((double*)Ptr) = Val.DoubleVal;
660 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000661 case Type::X86_FP80TyID: {
662 uint16_t *Dest = (uint16_t*)Ptr;
663 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
664 // This is endian dependent, but it will only work on x86 anyway.
665 Dest[0] = Src[4];
666 Dest[1] = Src[0];
667 Dest[2] = Src[1];
668 Dest[3] = Src[2];
669 Dest[4] = Src[3];
670 break;
671 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000672 case Type::PointerTyID:
673 *((PointerTy*)Ptr) = Val.PointerVal;
674 break;
675 default:
676 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattner996fe012002-12-24 00:01:05 +0000677 }
678}
679
Misha Brukman857c21b2003-10-10 17:45:12 +0000680/// FIXME: document
681///
Reid Spencer00919f52007-03-03 08:36:29 +0000682void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
683 GenericValue *Ptr,
Chris Lattner7f389e82003-05-08 16:52:16 +0000684 const Type *Ty) {
Reid Spencer87aa65f2007-03-06 03:04:04 +0000685 switch (Ty->getTypeID()) {
686 case Type::IntegerTyID: {
687 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
688 if (BitWidth <= 8)
689 Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
690 else if (BitWidth <= 16) {
691 Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
692 } else if (BitWidth <= 32) {
693 Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
694 } else if (BitWidth <= 64) {
695 Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
696 } else
Zhou Sheng8ff9ff72007-05-24 15:03:18 +0000697 Result.IntVal = APInt(BitWidth, (BitWidth+63)/64, (uint64_t*)Ptr);
Reid Spencer87aa65f2007-03-06 03:04:04 +0000698 break;
699 }
700 case Type::FloatTyID:
701 Result.FloatVal = *((float*)Ptr);
702 break;
703 case Type::DoubleTyID:
704 Result.DoubleVal = *((double*)Ptr);
705 break;
706 case Type::PointerTyID:
707 Result.PointerVal = *((PointerTy*)Ptr);
708 break;
Dale Johannesena1336cf2007-09-17 18:44:13 +0000709 case Type::X86_FP80TyID: {
710 // This is endian dependent, but it will only work on x86 anyway.
711 uint16_t x[8], *p = (uint16_t*)Ptr;
712 x[0] = p[1];
713 x[1] = p[2];
714 x[2] = p[3];
715 x[3] = p[4];
716 x[4] = p[0];
717 Result.IntVal = APInt(80, 2, x);
718 break;
719 }
Reid Spencer87aa65f2007-03-06 03:04:04 +0000720 default:
721 cerr << "Cannot load value of type " << *Ty << "!\n";
722 abort();
Chris Lattner7f389e82003-05-08 16:52:16 +0000723 }
Chris Lattner7f389e82003-05-08 16:52:16 +0000724}
725
Chris Lattner996fe012002-12-24 00:01:05 +0000726// InitializeMemory - Recursive function to apply a Constant value into the
727// specified memory location...
728//
729void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattner61753bf2004-10-16 18:19:26 +0000730 if (isa<UndefValue>(Init)) {
731 return;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000732 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino69d62132006-01-20 18:18:40 +0000733 unsigned ElementSize =
Owen Anderson20a631f2006-05-03 01:29:57 +0000734 getTargetData()->getTypeSize(CP->getType()->getElementType());
Robert Bocchino69d62132006-01-20 18:18:40 +0000735 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
736 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
737 return;
Chris Lattner61753bf2004-10-16 18:19:26 +0000738 } else if (Init->getType()->isFirstClassType()) {
Chris Lattner996fe012002-12-24 00:01:05 +0000739 GenericValue Val = getConstantValue(Init);
740 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
741 return;
Chris Lattner834b1272004-02-15 05:54:06 +0000742 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Anderson20a631f2006-05-03 01:29:57 +0000743 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
Chris Lattner834b1272004-02-15 05:54:06 +0000744 return;
Chris Lattner996fe012002-12-24 00:01:05 +0000745 }
746
Chris Lattner6b727592004-06-17 18:19:28 +0000747 switch (Init->getType()->getTypeID()) {
Chris Lattner996fe012002-12-24 00:01:05 +0000748 case Type::ArrayTyID: {
749 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukman835702a2005-04-21 22:36:52 +0000750 unsigned ElementSize =
Owen Anderson20a631f2006-05-03 01:29:57 +0000751 getTargetData()->getTypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000752 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
753 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattner996fe012002-12-24 00:01:05 +0000754 return;
755 }
756
757 case Type::StructTyID: {
758 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
759 const StructLayout *SL =
Owen Anderson20a631f2006-05-03 01:29:57 +0000760 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000761 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerc473d8e2007-02-10 19:55:17 +0000762 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattner996fe012002-12-24 00:01:05 +0000763 return;
764 }
765
766 default:
Bill Wendlingf3baad32006-12-07 01:30:32 +0000767 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattner996fe012002-12-24 00:01:05 +0000768 assert(0 && "Unknown constant type to initialize memory with!");
769 }
770}
771
Chris Lattner996fe012002-12-24 00:01:05 +0000772/// EmitGlobals - Emit all of the global variables to memory, storing their
773/// addresses into GlobalAddress. This must make sure to copy the contents of
774/// their initializers into the memory.
775///
776void ExecutionEngine::emitGlobals() {
Owen Anderson20a631f2006-05-03 01:29:57 +0000777 const TargetData *TD = getTargetData();
Misha Brukman835702a2005-04-21 22:36:52 +0000778
Chris Lattner996fe012002-12-24 00:01:05 +0000779 // Loop over all of the global variables in the program, allocating the memory
Chris Lattner0621cae2006-08-16 01:24:12 +0000780 // to hold them. If there is more than one module, do a prepass over globals
781 // to figure out how the different modules should link together.
782 //
783 std::map<std::pair<std::string, const Type*>,
784 const GlobalValue*> LinkedGlobalsMap;
Misha Brukman835702a2005-04-21 22:36:52 +0000785
Chris Lattner0621cae2006-08-16 01:24:12 +0000786 if (Modules.size() != 1) {
787 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
788 Module &M = *Modules[m]->getModule();
789 for (Module::const_global_iterator I = M.global_begin(),
790 E = M.global_end(); I != E; ++I) {
791 const GlobalValue *GV = I;
Reid Spencer5301e7c2007-01-30 20:08:39 +0000792 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattner0621cae2006-08-16 01:24:12 +0000793 GV->hasAppendingLinkage() || !GV->hasName())
794 continue;// Ignore external globals and globals with internal linkage.
795
796 const GlobalValue *&GVEntry =
797 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
798
799 // If this is the first time we've seen this global, it is the canonical
800 // version.
801 if (!GVEntry) {
802 GVEntry = GV;
803 continue;
804 }
805
806 // If the existing global is strong, never replace it.
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000807 if (GVEntry->hasExternalLinkage() ||
808 GVEntry->hasDLLImportLinkage() ||
809 GVEntry->hasDLLExportLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +0000810 continue;
811
812 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
813 // symbol.
Anton Korobeynikov12c94942006-12-01 00:25:12 +0000814 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattner0621cae2006-08-16 01:24:12 +0000815 GVEntry = GV;
Chris Lattner9de0d142003-04-23 19:01:49 +0000816 }
Chris Lattner996fe012002-12-24 00:01:05 +0000817 }
Chris Lattner0621cae2006-08-16 01:24:12 +0000818 }
819
820 std::vector<const GlobalValue*> NonCanonicalGlobals;
821 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
822 Module &M = *Modules[m]->getModule();
823 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
824 I != E; ++I) {
825 // In the multi-module case, see what this global maps to.
826 if (!LinkedGlobalsMap.empty()) {
827 if (const GlobalValue *GVEntry =
828 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
829 // If something else is the canonical global, ignore this one.
830 if (GVEntry != &*I) {
831 NonCanonicalGlobals.push_back(I);
832 continue;
833 }
834 }
835 }
836
Reid Spencer5301e7c2007-01-30 20:08:39 +0000837 if (!I->isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +0000838 // Get the type of the global.
839 const Type *Ty = I->getType()->getElementType();
Misha Brukman835702a2005-04-21 22:36:52 +0000840
Chris Lattner0621cae2006-08-16 01:24:12 +0000841 // Allocate some memory for it!
842 unsigned Size = TD->getTypeSize(Ty);
843 addGlobalMapping(I, new char[Size]);
844 } else {
845 // External variable reference. Try to use the dynamic loader to
846 // get a pointer to it.
847 if (void *SymAddr =
848 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
849 addGlobalMapping(I, SymAddr);
850 else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000851 cerr << "Could not resolve external global address: "
852 << I->getName() << "\n";
Chris Lattner0621cae2006-08-16 01:24:12 +0000853 abort();
854 }
855 }
856 }
857
858 // If there are multiple modules, map the non-canonical globals to their
859 // canonical location.
860 if (!NonCanonicalGlobals.empty()) {
861 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
862 const GlobalValue *GV = NonCanonicalGlobals[i];
863 const GlobalValue *CGV =
864 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
865 void *Ptr = getPointerToGlobalIfAvailable(CGV);
866 assert(Ptr && "Canonical global wasn't codegen'd!");
867 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
868 }
869 }
870
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000871 // Now that all of the globals are set up in memory, loop through them all
872 // and initialize their contents.
Chris Lattner0621cae2006-08-16 01:24:12 +0000873 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
874 I != E; ++I) {
Reid Spencer5301e7c2007-01-30 20:08:39 +0000875 if (!I->isDeclaration()) {
Chris Lattner0621cae2006-08-16 01:24:12 +0000876 if (!LinkedGlobalsMap.empty()) {
877 if (const GlobalValue *GVEntry =
878 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
879 if (GVEntry != &*I) // Not the canonical variable.
880 continue;
881 }
882 EmitGlobalVariable(I);
883 }
884 }
885 }
Chris Lattner6bbe3ec2003-12-20 02:45:37 +0000886}
887
888// EmitGlobalVariable - This method emits the specified global variable to the
889// address specified in GlobalAddresses, or allocates new memory if it's not
890// already in the map.
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +0000891void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner748e8572003-12-31 20:21:04 +0000892 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling5834fdb2006-11-27 23:54:50 +0000893 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattnerdc631732004-02-08 19:33:23 +0000894
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +0000895 const Type *ElTy = GV->getType()->getElementType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000896 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +0000897 if (GA == 0) {
898 // If it's not already specified, allocate memory for the global.
Chris Lattnerd2159922004-11-19 08:44:07 +0000899 GA = new char[GVSize];
Chris Lattner748e8572003-12-31 20:21:04 +0000900 addGlobalMapping(GV, GA);
Chris Lattner6bbe3ec2003-12-20 02:45:37 +0000901 }
Chris Lattnerfbcc0aa2003-12-20 03:36:47 +0000902
Chris Lattner6bbe3ec2003-12-20 02:45:37 +0000903 InitializeMemory(GV->getInitializer(), GA);
Chris Lattnerdf1f1522005-01-08 20:13:19 +0000904 NumInitBytes += (unsigned)GVSize;
Chris Lattner6bbe3ec2003-12-20 02:45:37 +0000905 ++NumGlobals;
Chris Lattner996fe012002-12-24 00:01:05 +0000906}