blob: 521e42336575868f29030f2e7f749bd43aa039ea [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//
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 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"
Misha Brukman19684162003-10-16 21:18:05 +000021#include "llvm/ExecutionEngine/ExecutionEngine.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000024#include "llvm/Support/MutexGuard.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000025#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000026#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000027#include "llvm/Target/TargetData.h"
Jeff Cohen2b7d7b52007-03-12 17:57:00 +000028#include <math.h>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000029using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000030
Chris Lattner36343732006-12-19 22:43:32 +000031STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
32STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000033
Chris Lattner2fe4bb02006-03-22 06:07:50 +000034ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
35ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
36
Chris Lattnerd958a5a2007-10-22 02:50:12 +000037ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000038 LazyCompilationDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000039 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000040 assert(P && "ModuleProvider is null?");
41}
42
Brian Gaeke8e539482003-09-04 22:57:27 +000043ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000044 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000045 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
46 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000047}
48
Devang Patel73d0e212007-10-15 19:56:32 +000049/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
50/// Release module from ModuleProvider.
51Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
52 std::string *ErrInfo) {
53 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
54 E = Modules.end(); I != E; ++I) {
55 ModuleProvider *MP = *I;
56 if (MP == P) {
57 Modules.erase(I);
58 return MP->releaseModule(ErrInfo);
59 }
60 }
61 return NULL;
62}
63
Chris Lattnerfe854032006-08-16 01:24:12 +000064/// FindFunctionNamed - Search all of the active modules to find the one that
65/// defines FnName. This is very slow operation and shouldn't be used for
66/// general code.
67Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
68 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000069 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000070 return F;
71 }
72 return 0;
73}
74
75
Chris Lattnere7fd5532006-05-08 22:00:52 +000076/// addGlobalMapping - Tell the execution engine that the specified global is
77/// at the specified location. This is used internally as functions are JIT'd
78/// and as global variables are laid out in memory. It can and should also be
79/// used by clients of the EE that want to have an LLVM global overlay
80/// existing data in memory.
81void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
82 MutexGuard locked(lock);
83
84 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
85 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
86 CurVal = Addr;
87
88 // If we are using the reverse mapping, add it too
89 if (!state.getGlobalAddressReverseMap(locked).empty()) {
90 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
91 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
92 V = GV;
93 }
94}
95
96/// clearAllGlobalMappings - Clear all global mappings and start over again
97/// use in dynamic compilation scenarios when you want to move globals
98void ExecutionEngine::clearAllGlobalMappings() {
99 MutexGuard locked(lock);
100
101 state.getGlobalAddressMap(locked).clear();
102 state.getGlobalAddressReverseMap(locked).clear();
103}
104
105/// updateGlobalMapping - Replace an existing mapping for GV with a new
106/// address. This updates both maps as required. If "Addr" is null, the
107/// entry for the global is removed from the mappings.
108void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
109 MutexGuard locked(lock);
110
111 // Deleting from the mapping?
112 if (Addr == 0) {
113 state.getGlobalAddressMap(locked).erase(GV);
114 if (!state.getGlobalAddressReverseMap(locked).empty())
115 state.getGlobalAddressReverseMap(locked).erase(Addr);
116 return;
117 }
118
119 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
120 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
121 state.getGlobalAddressReverseMap(locked).erase(CurVal);
122 CurVal = Addr;
123
124 // If we are using the reverse mapping, add it too
125 if (!state.getGlobalAddressReverseMap(locked).empty()) {
126 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
127 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
128 V = GV;
129 }
130}
131
132/// getPointerToGlobalIfAvailable - This returns the address of the specified
133/// global value if it is has already been codegen'd, otherwise it returns null.
134///
135void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
136 MutexGuard locked(lock);
137
138 std::map<const GlobalValue*, void*>::iterator I =
139 state.getGlobalAddressMap(locked).find(GV);
140 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
141}
142
Chris Lattner55d86482003-12-31 20:21:04 +0000143/// getGlobalValueAtAddress - Return the LLVM global value object that starts
144/// at the specified address.
145///
146const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000147 MutexGuard locked(lock);
148
Chris Lattner55d86482003-12-31 20:21:04 +0000149 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000150 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000151 for (std::map<const GlobalValue*, void *>::iterator
152 I = state.getGlobalAddressMap(locked).begin(),
153 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
154 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
155 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000156 }
157
158 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000159 state.getGlobalAddressReverseMap(locked).find(Addr);
160 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000161}
Chris Lattner87f03102003-12-26 06:50:30 +0000162
163// CreateArgv - Turn a vector of strings into a nice argv style array of
164// pointers to null terminated strings.
165//
166static void *CreateArgv(ExecutionEngine *EE,
167 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000168 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000169 char *Result = new char[(InputArgv.size()+1)*PtrSize];
170
Bill Wendling480f0932006-11-27 23:54:50 +0000171 DOUT << "ARGV = " << (void*)Result << "\n";
Reid Spencere49661b2006-12-31 05:51:36 +0000172 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000173
174 for (unsigned i = 0; i != InputArgv.size(); ++i) {
175 unsigned Size = InputArgv[i].size()+1;
176 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000177 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000178
Chris Lattner87f03102003-12-26 06:50:30 +0000179 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
180 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000181
Chris Lattner87f03102003-12-26 06:50:30 +0000182 // Endian safe: Result[i] = (PointerTy)Dest;
183 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
184 SBytePtr);
185 }
186
187 // Null terminate it
188 EE->StoreValueToMemory(PTOGV(0),
189 (GenericValue*)(Result+InputArgv.size()*PtrSize),
190 SBytePtr);
191 return Result;
192}
193
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000194
195/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000196/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000197/// value of isDtors.
198void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
199 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000200
Chris Lattnerfe854032006-08-16 01:24:12 +0000201 // Execute global ctors/dtors for each module in the program.
202 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
203 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
204
205 // If this global has internal linkage, or if it has a use, then it must be
206 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
207 // this is the case, don't execute any of the global ctors, __main will do
208 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000209 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000210
211 // Should be an array of '{ int, void ()* }' structs. The first value is
212 // the init priority, which we ignore.
213 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
214 if (!InitList) continue;
215 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
216 if (ConstantStruct *CS =
217 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
218 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000219
Chris Lattnerfe854032006-08-16 01:24:12 +0000220 Constant *FP = CS->getOperand(1);
221 if (FP->isNullValue())
222 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000223
Chris Lattnerfe854032006-08-16 01:24:12 +0000224 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000225 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000226 FP = CE->getOperand(0);
227 if (Function *F = dyn_cast<Function>(FP)) {
228 // Execute the ctor/dtor function!
229 runFunction(F, std::vector<GenericValue>());
230 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000231 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000232 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000233}
234
Chris Lattner87f03102003-12-26 06:50:30 +0000235/// runFunctionAsMain - This is a helper function which wraps runFunction to
236/// handle the common task of starting up main with the specified argc, argv,
237/// and envp parameters.
238int ExecutionEngine::runFunctionAsMain(Function *Fn,
239 const std::vector<std::string> &argv,
240 const char * const * envp) {
241 std::vector<GenericValue> GVArgs;
242 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000243 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000244
245 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000246 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000247 const FunctionType *FTy = Fn->getFunctionType();
248 const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty));
249 switch (NumArgs) {
250 case 3:
251 if (FTy->getParamType(2) != PPInt8Ty) {
252 cerr << "Invalid type for third argument of main() supplied\n";
253 abort();
254 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000255 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000256 case 2:
257 if (FTy->getParamType(1) != PPInt8Ty) {
258 cerr << "Invalid type for second argument of main() supplied\n";
259 abort();
260 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000261 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000262 case 1:
263 if (FTy->getParamType(0) != Type::Int32Ty) {
264 cerr << "Invalid type for first argument of main() supplied\n";
265 abort();
266 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000267 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000268 case 0:
269 if (FTy->getReturnType() != Type::Int32Ty &&
270 FTy->getReturnType() != Type::VoidTy) {
271 cerr << "Invalid return type of main() supplied\n";
272 abort();
273 }
274 break;
275 default:
276 cerr << "Invalid number of arguments of main() supplied\n";
277 abort();
278 }
279
Chris Lattnerf24d0992004-08-16 01:05:35 +0000280 if (NumArgs) {
281 GVArgs.push_back(GVArgc); // Arg #0 = argc.
282 if (NumArgs > 1) {
283 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
284 assert(((char **)GVTOP(GVArgs[1]))[0] &&
285 "argv[0] was null after CreateArgv");
286 if (NumArgs > 2) {
287 std::vector<std::string> EnvVars;
288 for (unsigned i = 0; envp[i]; ++i)
289 EnvVars.push_back(envp[i]);
290 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
291 }
292 }
293 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000294 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000295}
296
Misha Brukman19684162003-10-16 21:18:05 +0000297/// If possible, create a JIT, unless the caller specifically requests an
298/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000299/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000300///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000301ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000302 bool ForceInterpreter,
303 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000304 ExecutionEngine *EE = 0;
305
Chris Lattner73011782003-12-28 09:44:37 +0000306 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000307 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000308 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000309
310 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000311 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000312 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000313
Chris Lattner726c1ef2006-03-23 05:22:51 +0000314 if (EE) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000315 // Make sure we can resolve symbols in the program as well. The zero arg
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000316 // to the function tells DynamicLibrary to load the program, not a library.
Chris Lattnerc6185032007-10-21 22:58:11 +0000317 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr)) {
318 delete EE;
319 return 0;
Chris Lattner6f3ada52006-05-14 19:01:55 +0000320 }
Chris Lattner726c1ef2006-03-23 05:22:51 +0000321 }
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000322
Brian Gaeke82d82772003-09-03 20:34:19 +0000323 return EE;
324}
325
Chris Lattner8b5295b2007-10-21 22:57:11 +0000326ExecutionEngine *ExecutionEngine::create(Module *M) {
327 return create(new ExistingModuleProvider(M));
328}
329
Misha Brukman4afac182003-10-10 17:45:12 +0000330/// getPointerToGlobal - This returns the address of the specified global
331/// value. This may involve code generation if it's a function.
332///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000333void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000334 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000335 return getPointerToFunction(F);
336
Reid Spenceree448632005-07-12 15:51:55 +0000337 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000338 void *p = state.getGlobalAddressMap(locked)[GV];
339 if (p)
340 return p;
341
342 // Global variable might have been added since interpreter started.
343 if (GlobalVariable *GVar =
344 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
345 EmitGlobalVariable(GVar);
346 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000347 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000348 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000349}
350
Reid Spencer3da59db2006-11-27 01:05:10 +0000351/// This function converts a Constant* into a GenericValue. The interesting
352/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000353/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000354GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000355 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000356 if (isa<UndefValue>(C))
357 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000358
Reid Spencer3da59db2006-11-27 01:05:10 +0000359 // If the value is a ConstantExpr
360 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000361 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000362 switch (CE->getOpcode()) {
363 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000364 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000365 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000366 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000367 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000368 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000369
Reid Spencer8fb0f192007-03-06 03:04:04 +0000370 char* tmp = (char*) Result.PointerVal;
371 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000372 return Result;
373 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000374 case Instruction::Trunc: {
375 GenericValue GV = getConstantValue(Op0);
376 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
377 GV.IntVal = GV.IntVal.trunc(BitWidth);
378 return GV;
379 }
380 case Instruction::ZExt: {
381 GenericValue GV = getConstantValue(Op0);
382 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
383 GV.IntVal = GV.IntVal.zext(BitWidth);
384 return GV;
385 }
386 case Instruction::SExt: {
387 GenericValue GV = getConstantValue(Op0);
388 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
389 GV.IntVal = GV.IntVal.sext(BitWidth);
390 return GV;
391 }
392 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000393 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000394 GenericValue GV = getConstantValue(Op0);
395 GV.FloatVal = float(GV.DoubleVal);
396 return GV;
397 }
398 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000399 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000400 GenericValue GV = getConstantValue(Op0);
401 GV.DoubleVal = double(GV.FloatVal);
402 return GV;
403 }
404 case Instruction::UIToFP: {
405 GenericValue GV = getConstantValue(Op0);
406 if (CE->getType() == Type::FloatTy)
407 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000408 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000409 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen910993e2007-09-21 22:09:37 +0000410 else if (CE->getType() == Type::X86_FP80Ty) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000411 const uint64_t zero[] = {0, 0};
412 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Boothccf596a2007-10-07 11:45:55 +0000413 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen910993e2007-09-21 22:09:37 +0000414 GV.IntVal.getBitWidth(), false,
Dale Johannesen88216af2007-09-30 18:19:03 +0000415 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000416 GV.IntVal = apf.convertToAPInt();
417 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000418 return GV;
419 }
420 case Instruction::SIToFP: {
421 GenericValue GV = getConstantValue(Op0);
422 if (CE->getType() == Type::FloatTy)
423 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000424 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000425 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000426 else if (CE->getType() == Type::X86_FP80Ty) {
427 const uint64_t zero[] = { 0, 0};
428 APFloat apf = APFloat(APInt(80, 2, zero));
Neil Boothccf596a2007-10-07 11:45:55 +0000429 (void)apf.convertFromZeroExtendedInteger(GV.IntVal.getRawData(),
Dale Johannesen910993e2007-09-21 22:09:37 +0000430 GV.IntVal.getBitWidth(), true,
Dale Johannesen88216af2007-09-30 18:19:03 +0000431 APFloat::rmNearestTiesToEven);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000432 GV.IntVal = apf.convertToAPInt();
433 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000434 return GV;
435 }
436 case Instruction::FPToUI: // double->APInt conversion handles sign
437 case Instruction::FPToSI: {
438 GenericValue GV = getConstantValue(Op0);
439 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
440 if (Op0->getType() == Type::FloatTy)
441 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000442 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000443 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000444 else if (Op0->getType() == Type::X86_FP80Ty) {
445 APFloat apf = APFloat(GV.IntVal);
446 uint64_t v;
447 (void)apf.convertToInteger(&v, BitWidth,
448 CE->getOpcode()==Instruction::FPToSI,
449 APFloat::rmTowardZero);
450 GV.IntVal = v; // endian?
451 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000452 return GV;
453 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000454 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000455 GenericValue GV = getConstantValue(Op0);
456 uint32_t PtrWidth = TD->getPointerSizeInBits();
457 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
458 return GV;
459 }
460 case Instruction::IntToPtr: {
461 GenericValue GV = getConstantValue(Op0);
462 uint32_t PtrWidth = TD->getPointerSizeInBits();
463 if (PtrWidth != GV.IntVal.getBitWidth())
464 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
465 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
466 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 return GV;
468 }
469 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000470 GenericValue GV = getConstantValue(Op0);
471 const Type* DestTy = CE->getType();
472 switch (Op0->getType()->getTypeID()) {
473 default: assert(0 && "Invalid bitcast operand");
474 case Type::IntegerTyID:
475 assert(DestTy->isFloatingPoint() && "invalid bitcast");
476 if (DestTy == Type::FloatTy)
477 GV.FloatVal = GV.IntVal.bitsToFloat();
478 else if (DestTy == Type::DoubleTy)
479 GV.DoubleVal = GV.IntVal.bitsToDouble();
480 break;
481 case Type::FloatTyID:
482 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
483 GV.IntVal.floatToBits(GV.FloatVal);
484 break;
485 case Type::DoubleTyID:
486 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
487 GV.IntVal.doubleToBits(GV.DoubleVal);
488 break;
489 case Type::PointerTyID:
490 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
491 break; // getConstantValue(Op0) above already converted it
492 }
493 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000494 }
Chris Lattner9a231222003-05-14 17:51:49 +0000495 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000496 case Instruction::Sub:
497 case Instruction::Mul:
498 case Instruction::UDiv:
499 case Instruction::SDiv:
500 case Instruction::URem:
501 case Instruction::SRem:
502 case Instruction::And:
503 case Instruction::Or:
504 case Instruction::Xor: {
505 GenericValue LHS = getConstantValue(Op0);
506 GenericValue RHS = getConstantValue(CE->getOperand(1));
507 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000508 switch (CE->getOperand(0)->getType()->getTypeID()) {
509 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000510 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000511 switch (CE->getOpcode()) {
512 default: assert(0 && "Invalid integer opcode");
513 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
514 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
515 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
516 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
517 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
518 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
519 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
520 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
521 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
522 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
523 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000524 break;
525 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000526 switch (CE->getOpcode()) {
527 default: assert(0 && "Invalid float opcode"); abort();
528 case Instruction::Add:
529 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
530 case Instruction::Sub:
531 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
532 case Instruction::Mul:
533 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
534 case Instruction::FDiv:
535 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
536 case Instruction::FRem:
537 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
538 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000539 break;
540 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000541 switch (CE->getOpcode()) {
542 default: assert(0 && "Invalid double opcode"); abort();
543 case Instruction::Add:
544 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
545 case Instruction::Sub:
546 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
547 case Instruction::Mul:
548 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
549 case Instruction::FDiv:
550 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
551 case Instruction::FRem:
552 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
553 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000554 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000555 case Type::X86_FP80TyID:
556 case Type::PPC_FP128TyID:
557 case Type::FP128TyID: {
558 APFloat apfLHS = APFloat(LHS.IntVal);
559 switch (CE->getOpcode()) {
560 default: assert(0 && "Invalid long double opcode"); abort();
561 case Instruction::Add:
562 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
563 GV.IntVal = apfLHS.convertToAPInt();
564 break;
565 case Instruction::Sub:
566 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
567 GV.IntVal = apfLHS.convertToAPInt();
568 break;
569 case Instruction::Mul:
570 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
571 GV.IntVal = apfLHS.convertToAPInt();
572 break;
573 case Instruction::FDiv:
574 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
575 GV.IntVal = apfLHS.convertToAPInt();
576 break;
577 case Instruction::FRem:
578 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
579 GV.IntVal = apfLHS.convertToAPInt();
580 break;
581 }
582 }
583 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000584 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000585 return GV;
586 }
Chris Lattner9a231222003-05-14 17:51:49 +0000587 default:
588 break;
589 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000590 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000591 abort();
592 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000593
Reid Spencerbce30f12007-03-06 22:23:15 +0000594 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000595 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000596 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000597 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000598 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000599 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000600 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000601 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000602 case Type::X86_FP80TyID:
603 case Type::FP128TyID:
604 case Type::PPC_FP128TyID:
605 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
606 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000607 case Type::IntegerTyID:
608 Result.IntVal = cast<ConstantInt>(C)->getValue();
609 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000610 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000611 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000612 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000613 else if (const Function *F = dyn_cast<Function>(C))
614 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
615 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
616 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
617 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000618 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000619 break;
620 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000621 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000622 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000623 }
624 return Result;
625}
626
Nate Begeman37efe672006-04-22 18:53:45 +0000627/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
628/// is the address of the memory at which to store Val, cast to GenericValue *.
629/// It is not a pointer to a GenericValue containing the address at which to
630/// store Val.
Misha Brukman4afac182003-10-10 17:45:12 +0000631///
Reid Spencer415c1f72007-03-06 05:03:16 +0000632void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000633 const Type *Ty) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000634 switch (Ty->getTypeID()) {
635 case Type::IntegerTyID: {
636 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
Duncan Sands1eff7042007-12-10 17:43:13 +0000637 unsigned StoreBytes = (BitWidth + 7)/8;
638 uint8_t *Src = (uint8_t *)Val.IntVal.getRawData();
639 uint8_t *Dst = (uint8_t *)Ptr;
640
Duncan Sands67f1c492007-12-12 23:03:45 +0000641 if (sys::littleEndianHost())
Duncan Sands1eff7042007-12-10 17:43:13 +0000642 // Little-endian host - the source is ordered from LSB to MSB.
643 // Order the destination from LSB to MSB: Do a straight copy.
644 memcpy(Dst, Src, StoreBytes);
645 else {
646 // Big-endian host - the source is an array of 64 bit words ordered from
647 // LSW to MSW. Each word is ordered from MSB to LSB.
648 // Order the destination from MSB to LSB: Reverse the word order, but not
649 // the bytes in a word.
650 while (StoreBytes > sizeof(uint64_t)) {
651 StoreBytes -= sizeof(uint64_t);
652 // May not be aligned so use memcpy.
653 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
654 Src += sizeof(uint64_t);
655 }
656
657 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
Reid Spencera54b7cb2007-01-12 07:05:14 +0000658 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000659 break;
660 }
661 case Type::FloatTyID:
662 *((float*)Ptr) = Val.FloatVal;
663 break;
664 case Type::DoubleTyID:
665 *((double*)Ptr) = Val.DoubleVal;
666 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000667 case Type::X86_FP80TyID: {
668 uint16_t *Dest = (uint16_t*)Ptr;
669 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
670 // This is endian dependent, but it will only work on x86 anyway.
671 Dest[0] = Src[4];
672 Dest[1] = Src[0];
673 Dest[2] = Src[1];
674 Dest[3] = Src[2];
675 Dest[4] = Src[3];
676 break;
677 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000678 case Type::PointerTyID:
679 *((PointerTy*)Ptr) = Val.PointerVal;
680 break;
681 default:
682 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000683 }
684}
685
Misha Brukman4afac182003-10-10 17:45:12 +0000686/// FIXME: document
687///
Reid Spencerf0f09a92007-03-03 08:36:29 +0000688void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
689 GenericValue *Ptr,
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000690 const Type *Ty) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000691 switch (Ty->getTypeID()) {
692 case Type::IntegerTyID: {
693 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
Duncan Sands1eff7042007-12-10 17:43:13 +0000694 unsigned LoadBytes = (BitWidth + 7)/8;
695
696 // An APInt with all words initially zero.
697 Result.IntVal = APInt(BitWidth, 0);
698
699 uint8_t *Src = (uint8_t *)Ptr;
700 uint8_t *Dst = (uint8_t *)Result.IntVal.getRawData();
701
Duncan Sands67f1c492007-12-12 23:03:45 +0000702 if (sys::littleEndianHost())
Duncan Sands1eff7042007-12-10 17:43:13 +0000703 // Little-endian host - the destination must be ordered from LSB to MSB.
704 // The source is ordered from LSB to MSB: Do a straight copy.
705 memcpy(Dst, Src, LoadBytes);
706 else {
707 // Big-endian - the destination is an array of 64 bit words ordered from
708 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
709 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
710 // a word.
711 while (LoadBytes > sizeof(uint64_t)) {
712 LoadBytes -= sizeof(uint64_t);
713 // May not be aligned so use memcpy.
714 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
715 Dst += sizeof(uint64_t);
716 }
717
718 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
719 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000720 break;
721 }
722 case Type::FloatTyID:
723 Result.FloatVal = *((float*)Ptr);
724 break;
725 case Type::DoubleTyID:
726 Result.DoubleVal = *((double*)Ptr);
727 break;
728 case Type::PointerTyID:
729 Result.PointerVal = *((PointerTy*)Ptr);
730 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000731 case Type::X86_FP80TyID: {
732 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sandsdd65a732007-11-28 10:36:19 +0000733 uint16_t *p = (uint16_t*)Ptr;
734 union {
735 uint16_t x[8];
736 uint64_t y[2];
737 };
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000738 x[0] = p[1];
739 x[1] = p[2];
740 x[2] = p[3];
741 x[3] = p[4];
742 x[4] = p[0];
Duncan Sandsdd65a732007-11-28 10:36:19 +0000743 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000744 break;
745 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000746 default:
747 cerr << "Cannot load value of type " << *Ty << "!\n";
748 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000749 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000750}
751
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000752// InitializeMemory - Recursive function to apply a Constant value into the
753// specified memory location...
754//
755void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000756 if (isa<UndefValue>(Init)) {
757 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000758 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000759 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000760 getTargetData()->getABITypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000761 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
762 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
763 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000764 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000765 GenericValue Val = getConstantValue(Init);
766 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
767 return;
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000768 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands514ab342007-11-01 20:53:16 +0000769 memset(Addr, 0, (size_t)getTargetData()->getABITypeSize(Init->getType()));
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000770 return;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000771 }
772
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000773 switch (Init->getType()->getTypeID()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000774 case Type::ArrayTyID: {
775 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000776 unsigned ElementSize =
Duncan Sands514ab342007-11-01 20:53:16 +0000777 getTargetData()->getABITypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000778 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
779 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000780 return;
781 }
782
783 case Type::StructTyID: {
784 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
785 const StructLayout *SL =
Owen Andersona69571c2006-05-03 01:29:57 +0000786 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000787 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000788 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000789 return;
790 }
791
792 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000793 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000794 assert(0 && "Unknown constant type to initialize memory with!");
795 }
796}
797
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000798/// EmitGlobals - Emit all of the global variables to memory, storing their
799/// addresses into GlobalAddress. This must make sure to copy the contents of
800/// their initializers into the memory.
801///
802void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000803 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000804
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000805 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000806 // to hold them. If there is more than one module, do a prepass over globals
807 // to figure out how the different modules should link together.
808 //
809 std::map<std::pair<std::string, const Type*>,
810 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000811
Chris Lattnerfe854032006-08-16 01:24:12 +0000812 if (Modules.size() != 1) {
813 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
814 Module &M = *Modules[m]->getModule();
815 for (Module::const_global_iterator I = M.global_begin(),
816 E = M.global_end(); I != E; ++I) {
817 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000818 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000819 GV->hasAppendingLinkage() || !GV->hasName())
820 continue;// Ignore external globals and globals with internal linkage.
821
822 const GlobalValue *&GVEntry =
823 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
824
825 // If this is the first time we've seen this global, it is the canonical
826 // version.
827 if (!GVEntry) {
828 GVEntry = GV;
829 continue;
830 }
831
832 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000833 if (GVEntry->hasExternalLinkage() ||
834 GVEntry->hasDLLImportLinkage() ||
835 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000836 continue;
837
838 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
839 // symbol.
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000840 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000841 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000842 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000843 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000844 }
845
846 std::vector<const GlobalValue*> NonCanonicalGlobals;
847 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
848 Module &M = *Modules[m]->getModule();
849 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
850 I != E; ++I) {
851 // In the multi-module case, see what this global maps to.
852 if (!LinkedGlobalsMap.empty()) {
853 if (const GlobalValue *GVEntry =
854 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
855 // If something else is the canonical global, ignore this one.
856 if (GVEntry != &*I) {
857 NonCanonicalGlobals.push_back(I);
858 continue;
859 }
860 }
861 }
862
Reid Spencer5cbf9852007-01-30 20:08:39 +0000863 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000864 // Get the type of the global.
865 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000866
Chris Lattnerfe854032006-08-16 01:24:12 +0000867 // Allocate some memory for it!
Duncan Sands514ab342007-11-01 20:53:16 +0000868 unsigned Size = TD->getABITypeSize(Ty);
Chris Lattnerfe854032006-08-16 01:24:12 +0000869 addGlobalMapping(I, new char[Size]);
870 } else {
871 // External variable reference. Try to use the dynamic loader to
872 // get a pointer to it.
873 if (void *SymAddr =
874 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
875 addGlobalMapping(I, SymAddr);
876 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000877 cerr << "Could not resolve external global address: "
878 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000879 abort();
880 }
881 }
882 }
883
884 // If there are multiple modules, map the non-canonical globals to their
885 // canonical location.
886 if (!NonCanonicalGlobals.empty()) {
887 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
888 const GlobalValue *GV = NonCanonicalGlobals[i];
889 const GlobalValue *CGV =
890 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
891 void *Ptr = getPointerToGlobalIfAvailable(CGV);
892 assert(Ptr && "Canonical global wasn't codegen'd!");
893 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
894 }
895 }
896
Reid Spencera54b7cb2007-01-12 07:05:14 +0000897 // Now that all of the globals are set up in memory, loop through them all
898 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000899 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
900 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000901 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000902 if (!LinkedGlobalsMap.empty()) {
903 if (const GlobalValue *GVEntry =
904 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
905 if (GVEntry != &*I) // Not the canonical variable.
906 continue;
907 }
908 EmitGlobalVariable(I);
909 }
910 }
911 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000912}
913
914// EmitGlobalVariable - This method emits the specified global variable to the
915// address specified in GlobalAddresses, or allocates new memory if it's not
916// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000917void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000918 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000919 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000920
Chris Lattnerc07ed132003-12-20 03:36:47 +0000921 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands514ab342007-11-01 20:53:16 +0000922 size_t GVSize = (size_t)getTargetData()->getABITypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000923 if (GA == 0) {
924 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000925 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000926 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000927 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000928
Chris Lattner24b0a182003-12-20 02:45:37 +0000929 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000930 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000931 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000932}