blob: afff142f9f5b6d27c072c243c426e4d508366fa8 [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"
26#include "llvm/Target/TargetData.h"
Jeff Cohen2b7d7b52007-03-12 17:57:00 +000027#include <math.h>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000028using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000029
Chris Lattner36343732006-12-19 22:43:32 +000030STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
31STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000032
Chris Lattner2fe4bb02006-03-22 06:07:50 +000033ExecutionEngine::EECtorFn ExecutionEngine::JITCtor = 0;
34ExecutionEngine::EECtorFn ExecutionEngine::InterpCtor = 0;
35
Chris Lattnerfe854032006-08-16 01:24:12 +000036ExecutionEngine::ExecutionEngine(ModuleProvider *P) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000037 LazyCompilationDisabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000038 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000039 assert(P && "ModuleProvider is null?");
40}
41
Chris Lattnerfe854032006-08-16 01:24:12 +000042ExecutionEngine::ExecutionEngine(Module *M) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000043 LazyCompilationDisabled = false;
Misha Brukman05701572003-10-17 18:31:59 +000044 assert(M && "Module is null?");
Chris Lattnerfe854032006-08-16 01:24:12 +000045 Modules.push_back(new ExistingModuleProvider(M));
Misha Brukman19684162003-10-16 21:18:05 +000046}
47
Brian Gaeke8e539482003-09-04 22:57:27 +000048ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000049 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000050 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
51 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000052}
53
Chris Lattnerfe854032006-08-16 01:24:12 +000054/// FindFunctionNamed - Search all of the active modules to find the one that
55/// defines FnName. This is very slow operation and shouldn't be used for
56/// general code.
57Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
58 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +000059 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +000060 return F;
61 }
62 return 0;
63}
64
65
Chris Lattnere7fd5532006-05-08 22:00:52 +000066/// addGlobalMapping - Tell the execution engine that the specified global is
67/// at the specified location. This is used internally as functions are JIT'd
68/// and as global variables are laid out in memory. It can and should also be
69/// used by clients of the EE that want to have an LLVM global overlay
70/// existing data in memory.
71void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
72 MutexGuard locked(lock);
73
74 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
75 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
76 CurVal = Addr;
77
78 // If we are using the reverse mapping, add it too
79 if (!state.getGlobalAddressReverseMap(locked).empty()) {
80 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
81 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
82 V = GV;
83 }
84}
85
86/// clearAllGlobalMappings - Clear all global mappings and start over again
87/// use in dynamic compilation scenarios when you want to move globals
88void ExecutionEngine::clearAllGlobalMappings() {
89 MutexGuard locked(lock);
90
91 state.getGlobalAddressMap(locked).clear();
92 state.getGlobalAddressReverseMap(locked).clear();
93}
94
95/// updateGlobalMapping - Replace an existing mapping for GV with a new
96/// address. This updates both maps as required. If "Addr" is null, the
97/// entry for the global is removed from the mappings.
98void ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
99 MutexGuard locked(lock);
100
101 // Deleting from the mapping?
102 if (Addr == 0) {
103 state.getGlobalAddressMap(locked).erase(GV);
104 if (!state.getGlobalAddressReverseMap(locked).empty())
105 state.getGlobalAddressReverseMap(locked).erase(Addr);
106 return;
107 }
108
109 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
110 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
111 state.getGlobalAddressReverseMap(locked).erase(CurVal);
112 CurVal = Addr;
113
114 // If we are using the reverse mapping, add it too
115 if (!state.getGlobalAddressReverseMap(locked).empty()) {
116 const GlobalValue *&V = state.getGlobalAddressReverseMap(locked)[Addr];
117 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
118 V = GV;
119 }
120}
121
122/// getPointerToGlobalIfAvailable - This returns the address of the specified
123/// global value if it is has already been codegen'd, otherwise it returns null.
124///
125void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
126 MutexGuard locked(lock);
127
128 std::map<const GlobalValue*, void*>::iterator I =
129 state.getGlobalAddressMap(locked).find(GV);
130 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
131}
132
Chris Lattner55d86482003-12-31 20:21:04 +0000133/// getGlobalValueAtAddress - Return the LLVM global value object that starts
134/// at the specified address.
135///
136const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000137 MutexGuard locked(lock);
138
Chris Lattner55d86482003-12-31 20:21:04 +0000139 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000140 if (state.getGlobalAddressReverseMap(locked).empty()) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000141 for (std::map<const GlobalValue*, void *>::iterator
142 I = state.getGlobalAddressMap(locked).begin(),
143 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
144 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
145 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000146 }
147
148 std::map<void *, const GlobalValue*>::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000149 state.getGlobalAddressReverseMap(locked).find(Addr);
150 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000151}
Chris Lattner87f03102003-12-26 06:50:30 +0000152
153// CreateArgv - Turn a vector of strings into a nice argv style array of
154// pointers to null terminated strings.
155//
156static void *CreateArgv(ExecutionEngine *EE,
157 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000158 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000159 char *Result = new char[(InputArgv.size()+1)*PtrSize];
160
Bill Wendling480f0932006-11-27 23:54:50 +0000161 DOUT << "ARGV = " << (void*)Result << "\n";
Reid Spencere49661b2006-12-31 05:51:36 +0000162 const Type *SBytePtr = PointerType::get(Type::Int8Ty);
Chris Lattner87f03102003-12-26 06:50:30 +0000163
164 for (unsigned i = 0; i != InputArgv.size(); ++i) {
165 unsigned Size = InputArgv[i].size()+1;
166 char *Dest = new char[Size];
Bill Wendling480f0932006-11-27 23:54:50 +0000167 DOUT << "ARGV[" << i << "] = " << (void*)Dest << "\n";
Misha Brukmanedf128a2005-04-21 22:36:52 +0000168
Chris Lattner87f03102003-12-26 06:50:30 +0000169 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
170 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000171
Chris Lattner87f03102003-12-26 06:50:30 +0000172 // Endian safe: Result[i] = (PointerTy)Dest;
173 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
174 SBytePtr);
175 }
176
177 // Null terminate it
178 EE->StoreValueToMemory(PTOGV(0),
179 (GenericValue*)(Result+InputArgv.size()*PtrSize),
180 SBytePtr);
181 return Result;
182}
183
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000184
185/// runStaticConstructorsDestructors - This method is used to execute all of
Chris Lattnerfe854032006-08-16 01:24:12 +0000186/// the static constructors or destructors for a program, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000187/// value of isDtors.
188void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
189 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000190
Chris Lattnerfe854032006-08-16 01:24:12 +0000191 // Execute global ctors/dtors for each module in the program.
192 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
193 GlobalVariable *GV = Modules[m]->getModule()->getNamedGlobal(Name);
194
195 // If this global has internal linkage, or if it has a use, then it must be
196 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
197 // this is the case, don't execute any of the global ctors, __main will do
198 // it.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000199 if (!GV || GV->isDeclaration() || GV->hasInternalLinkage()) continue;
Chris Lattnerfe854032006-08-16 01:24:12 +0000200
201 // Should be an array of '{ int, void ()* }' structs. The first value is
202 // the init priority, which we ignore.
203 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
204 if (!InitList) continue;
205 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
206 if (ConstantStruct *CS =
207 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
208 if (CS->getNumOperands() != 2) break; // Not array of 2-element structs.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000209
Chris Lattnerfe854032006-08-16 01:24:12 +0000210 Constant *FP = CS->getOperand(1);
211 if (FP->isNullValue())
212 break; // Found a null terminator, exit.
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000213
Chris Lattnerfe854032006-08-16 01:24:12 +0000214 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000215 if (CE->isCast())
Chris Lattnerfe854032006-08-16 01:24:12 +0000216 FP = CE->getOperand(0);
217 if (Function *F = dyn_cast<Function>(FP)) {
218 // Execute the ctor/dtor function!
219 runFunction(F, std::vector<GenericValue>());
220 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000221 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000222 }
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000223}
224
Chris Lattner87f03102003-12-26 06:50:30 +0000225/// runFunctionAsMain - This is a helper function which wraps runFunction to
226/// handle the common task of starting up main with the specified argc, argv,
227/// and envp parameters.
228int ExecutionEngine::runFunctionAsMain(Function *Fn,
229 const std::vector<std::string> &argv,
230 const char * const * envp) {
231 std::vector<GenericValue> GVArgs;
232 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000233 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000234
235 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000236 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000237 const FunctionType *FTy = Fn->getFunctionType();
238 const Type* PPInt8Ty = PointerType::get(PointerType::get(Type::Int8Ty));
239 switch (NumArgs) {
240 case 3:
241 if (FTy->getParamType(2) != PPInt8Ty) {
242 cerr << "Invalid type for third argument of main() supplied\n";
243 abort();
244 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000245 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000246 case 2:
247 if (FTy->getParamType(1) != PPInt8Ty) {
248 cerr << "Invalid type for second argument of main() supplied\n";
249 abort();
250 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000251 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000252 case 1:
253 if (FTy->getParamType(0) != Type::Int32Ty) {
254 cerr << "Invalid type for first argument of main() supplied\n";
255 abort();
256 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000257 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000258 case 0:
259 if (FTy->getReturnType() != Type::Int32Ty &&
260 FTy->getReturnType() != Type::VoidTy) {
261 cerr << "Invalid return type of main() supplied\n";
262 abort();
263 }
264 break;
265 default:
266 cerr << "Invalid number of arguments of main() supplied\n";
267 abort();
268 }
269
Chris Lattnerf24d0992004-08-16 01:05:35 +0000270 if (NumArgs) {
271 GVArgs.push_back(GVArgc); // Arg #0 = argc.
272 if (NumArgs > 1) {
273 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
274 assert(((char **)GVTOP(GVArgs[1]))[0] &&
275 "argv[0] was null after CreateArgv");
276 if (NumArgs > 2) {
277 std::vector<std::string> EnvVars;
278 for (unsigned i = 0; envp[i]; ++i)
279 EnvVars.push_back(envp[i]);
280 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
281 }
282 }
283 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000284 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000285}
286
Misha Brukman19684162003-10-16 21:18:05 +0000287/// If possible, create a JIT, unless the caller specifically requests an
288/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000289/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000290///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000291ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000292 bool ForceInterpreter,
293 std::string *ErrorStr) {
Brian Gaeke82d82772003-09-03 20:34:19 +0000294 ExecutionEngine *EE = 0;
295
Chris Lattner73011782003-12-28 09:44:37 +0000296 // Unless the interpreter was explicitly selected, try making a JIT.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000297 if (!ForceInterpreter && JITCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000298 EE = JITCtor(MP, ErrorStr);
Brian Gaeke82d82772003-09-03 20:34:19 +0000299
300 // If we can't make a JIT, make an interpreter instead.
Chris Lattner2fe4bb02006-03-22 06:07:50 +0000301 if (EE == 0 && InterpCtor)
Reid Spencerd4c0e622007-03-03 18:19:18 +0000302 EE = InterpCtor(MP, ErrorStr);
Chris Lattner73011782003-12-28 09:44:37 +0000303
Chris Lattner726c1ef2006-03-23 05:22:51 +0000304 if (EE) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000305 // Make sure we can resolve symbols in the program as well. The zero arg
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000306 // to the function tells DynamicLibrary to load the program, not a library.
Chris Lattner6f3ada52006-05-14 19:01:55 +0000307 try {
308 sys::DynamicLibrary::LoadLibraryPermanently(0);
309 } catch (...) {
310 }
Chris Lattner726c1ef2006-03-23 05:22:51 +0000311 }
Reid Spencerdf5a37e2004-11-29 14:11:29 +0000312
Brian Gaeke82d82772003-09-03 20:34:19 +0000313 return EE;
314}
315
Misha Brukman4afac182003-10-10 17:45:12 +0000316/// getPointerToGlobal - This returns the address of the specified global
317/// value. This may involve code generation if it's a function.
318///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000319void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000320 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000321 return getPointerToFunction(F);
322
Reid Spenceree448632005-07-12 15:51:55 +0000323 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000324 void *p = state.getGlobalAddressMap(locked)[GV];
325 if (p)
326 return p;
327
328 // Global variable might have been added since interpreter started.
329 if (GlobalVariable *GVar =
330 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
331 EmitGlobalVariable(GVar);
332 else
Chris Lattner64f150f2007-02-14 06:20:04 +0000333 assert(0 && "Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000334 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000335}
336
Reid Spencer3da59db2006-11-27 01:05:10 +0000337/// This function converts a Constant* into a GenericValue. The interesting
338/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000339/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000340GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000341 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000342 if (isa<UndefValue>(C))
343 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000344
Reid Spencer3da59db2006-11-27 01:05:10 +0000345 // If the value is a ConstantExpr
346 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000347 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000348 switch (CE->getOpcode()) {
349 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000350 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000351 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000352 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000353 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000354 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000355
Reid Spencer8fb0f192007-03-06 03:04:04 +0000356 char* tmp = (char*) Result.PointerVal;
357 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000358 return Result;
359 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000360 case Instruction::Trunc: {
361 GenericValue GV = getConstantValue(Op0);
362 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
363 GV.IntVal = GV.IntVal.trunc(BitWidth);
364 return GV;
365 }
366 case Instruction::ZExt: {
367 GenericValue GV = getConstantValue(Op0);
368 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
369 GV.IntVal = GV.IntVal.zext(BitWidth);
370 return GV;
371 }
372 case Instruction::SExt: {
373 GenericValue GV = getConstantValue(Op0);
374 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
375 GV.IntVal = GV.IntVal.sext(BitWidth);
376 return GV;
377 }
378 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000379 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000380 GenericValue GV = getConstantValue(Op0);
381 GV.FloatVal = float(GV.DoubleVal);
382 return GV;
383 }
384 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000385 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000386 GenericValue GV = getConstantValue(Op0);
387 GV.DoubleVal = double(GV.FloatVal);
388 return GV;
389 }
390 case Instruction::UIToFP: {
391 GenericValue GV = getConstantValue(Op0);
392 if (CE->getType() == Type::FloatTy)
393 GV.FloatVal = float(GV.IntVal.roundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000394 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000395 GV.DoubleVal = GV.IntVal.roundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000396 else if (CE->getType() == Type::X86_FP80Ty) {
397 const uint64_t zero[] = {0, 0};
398 APFloat apf = APFloat(APInt(80, 2, zero));
399 (void)apf.convertFromInteger(GV.IntVal.getRawData(), 2, false,
400 APFloat::rmTowardZero);
401 GV.IntVal = apf.convertToAPInt();
402 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000403 return GV;
404 }
405 case Instruction::SIToFP: {
406 GenericValue GV = getConstantValue(Op0);
407 if (CE->getType() == Type::FloatTy)
408 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000409 else if (CE->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000410 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000411 else if (CE->getType() == Type::X86_FP80Ty) {
412 const uint64_t zero[] = { 0, 0};
413 APFloat apf = APFloat(APInt(80, 2, zero));
414 (void)apf.convertFromInteger(GV.IntVal.getRawData(), 2, true,
415 APFloat::rmTowardZero);
416 GV.IntVal = apf.convertToAPInt();
417 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000418 return GV;
419 }
420 case Instruction::FPToUI: // double->APInt conversion handles sign
421 case Instruction::FPToSI: {
422 GenericValue GV = getConstantValue(Op0);
423 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
424 if (Op0->getType() == Type::FloatTy)
425 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000426 else if (Op0->getType() == Type::DoubleTy)
Reid Spencerbce30f12007-03-06 22:23:15 +0000427 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000428 else if (Op0->getType() == Type::X86_FP80Ty) {
429 APFloat apf = APFloat(GV.IntVal);
430 uint64_t v;
431 (void)apf.convertToInteger(&v, BitWidth,
432 CE->getOpcode()==Instruction::FPToSI,
433 APFloat::rmTowardZero);
434 GV.IntVal = v; // endian?
435 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000436 return GV;
437 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000438 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000439 GenericValue GV = getConstantValue(Op0);
440 uint32_t PtrWidth = TD->getPointerSizeInBits();
441 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
442 return GV;
443 }
444 case Instruction::IntToPtr: {
445 GenericValue GV = getConstantValue(Op0);
446 uint32_t PtrWidth = TD->getPointerSizeInBits();
447 if (PtrWidth != GV.IntVal.getBitWidth())
448 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
449 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
450 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000451 return GV;
452 }
453 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000454 GenericValue GV = getConstantValue(Op0);
455 const Type* DestTy = CE->getType();
456 switch (Op0->getType()->getTypeID()) {
457 default: assert(0 && "Invalid bitcast operand");
458 case Type::IntegerTyID:
459 assert(DestTy->isFloatingPoint() && "invalid bitcast");
460 if (DestTy == Type::FloatTy)
461 GV.FloatVal = GV.IntVal.bitsToFloat();
462 else if (DestTy == Type::DoubleTy)
463 GV.DoubleVal = GV.IntVal.bitsToDouble();
464 break;
465 case Type::FloatTyID:
466 assert(DestTy == Type::Int32Ty && "Invalid bitcast");
467 GV.IntVal.floatToBits(GV.FloatVal);
468 break;
469 case Type::DoubleTyID:
470 assert(DestTy == Type::Int64Ty && "Invalid bitcast");
471 GV.IntVal.doubleToBits(GV.DoubleVal);
472 break;
473 case Type::PointerTyID:
474 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
475 break; // getConstantValue(Op0) above already converted it
476 }
477 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000478 }
Chris Lattner9a231222003-05-14 17:51:49 +0000479 case Instruction::Add:
Reid Spencerbce30f12007-03-06 22:23:15 +0000480 case Instruction::Sub:
481 case Instruction::Mul:
482 case Instruction::UDiv:
483 case Instruction::SDiv:
484 case Instruction::URem:
485 case Instruction::SRem:
486 case Instruction::And:
487 case Instruction::Or:
488 case Instruction::Xor: {
489 GenericValue LHS = getConstantValue(Op0);
490 GenericValue RHS = getConstantValue(CE->getOperand(1));
491 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000492 switch (CE->getOperand(0)->getType()->getTypeID()) {
493 default: assert(0 && "Bad add type!"); abort();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000494 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000495 switch (CE->getOpcode()) {
496 default: assert(0 && "Invalid integer opcode");
497 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
498 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
499 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
500 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
501 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
502 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
503 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
504 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
505 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
506 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
507 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000508 break;
509 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000510 switch (CE->getOpcode()) {
511 default: assert(0 && "Invalid float opcode"); abort();
512 case Instruction::Add:
513 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
514 case Instruction::Sub:
515 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
516 case Instruction::Mul:
517 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
518 case Instruction::FDiv:
519 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
520 case Instruction::FRem:
521 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
522 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000523 break;
524 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000525 switch (CE->getOpcode()) {
526 default: assert(0 && "Invalid double opcode"); abort();
527 case Instruction::Add:
528 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
529 case Instruction::Sub:
530 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
531 case Instruction::Mul:
532 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
533 case Instruction::FDiv:
534 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
535 case Instruction::FRem:
536 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
537 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000538 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000539 case Type::X86_FP80TyID:
540 case Type::PPC_FP128TyID:
541 case Type::FP128TyID: {
542 APFloat apfLHS = APFloat(LHS.IntVal);
543 switch (CE->getOpcode()) {
544 default: assert(0 && "Invalid long double opcode"); abort();
545 case Instruction::Add:
546 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
547 GV.IntVal = apfLHS.convertToAPInt();
548 break;
549 case Instruction::Sub:
550 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
551 GV.IntVal = apfLHS.convertToAPInt();
552 break;
553 case Instruction::Mul:
554 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
555 GV.IntVal = apfLHS.convertToAPInt();
556 break;
557 case Instruction::FDiv:
558 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
559 GV.IntVal = apfLHS.convertToAPInt();
560 break;
561 case Instruction::FRem:
562 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
563 GV.IntVal = apfLHS.convertToAPInt();
564 break;
565 }
566 }
567 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000568 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000569 return GV;
570 }
Chris Lattner9a231222003-05-14 17:51:49 +0000571 default:
572 break;
573 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000574 cerr << "ConstantExpr not handled: " << *CE << "\n";
Chris Lattner9a231222003-05-14 17:51:49 +0000575 abort();
576 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000577
Reid Spencerbce30f12007-03-06 22:23:15 +0000578 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000579 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000580 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000581 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000582 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000583 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000584 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000585 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000586 case Type::X86_FP80TyID:
587 case Type::FP128TyID:
588 case Type::PPC_FP128TyID:
589 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().convertToAPInt();
590 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000591 case Type::IntegerTyID:
592 Result.IntVal = cast<ConstantInt>(C)->getValue();
593 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000594 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000595 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000596 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000597 else if (const Function *F = dyn_cast<Function>(C))
598 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
599 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
600 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
601 else
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000602 assert(0 && "Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000603 break;
604 default:
Reid Spencerbce30f12007-03-06 22:23:15 +0000605 cerr << "ERROR: Constant unimplemented for type: " << *C->getType() << "\n";
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000606 abort();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000607 }
608 return Result;
609}
610
Nate Begeman37efe672006-04-22 18:53:45 +0000611/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
612/// is the address of the memory at which to store Val, cast to GenericValue *.
613/// It is not a pointer to a GenericValue containing the address at which to
614/// store Val.
Misha Brukman4afac182003-10-10 17:45:12 +0000615///
Reid Spencer415c1f72007-03-06 05:03:16 +0000616void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, GenericValue *Ptr,
Misha Brukman4afac182003-10-10 17:45:12 +0000617 const Type *Ty) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000618 switch (Ty->getTypeID()) {
619 case Type::IntegerTyID: {
620 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
621 GenericValue TmpVal = Val;
622 if (BitWidth <= 8)
623 *((uint8_t*)Ptr) = uint8_t(Val.IntVal.getZExtValue());
624 else if (BitWidth <= 16) {
625 *((uint16_t*)Ptr) = uint16_t(Val.IntVal.getZExtValue());
626 } else if (BitWidth <= 32) {
627 *((uint32_t*)Ptr) = uint32_t(Val.IntVal.getZExtValue());
628 } else if (BitWidth <= 64) {
Reid Spencer415c1f72007-03-06 05:03:16 +0000629 *((uint64_t*)Ptr) = uint64_t(Val.IntVal.getZExtValue());
Reid Spencer8fb0f192007-03-06 03:04:04 +0000630 } else {
631 uint64_t *Dest = (uint64_t*)Ptr;
632 const uint64_t *Src = Val.IntVal.getRawData();
633 for (uint32_t i = 0; i < Val.IntVal.getNumWords(); ++i)
634 Dest[i] = Src[i];
Reid Spencera54b7cb2007-01-12 07:05:14 +0000635 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000636 break;
637 }
638 case Type::FloatTyID:
639 *((float*)Ptr) = Val.FloatVal;
640 break;
641 case Type::DoubleTyID:
642 *((double*)Ptr) = Val.DoubleVal;
643 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000644 case Type::X86_FP80TyID: {
645 uint16_t *Dest = (uint16_t*)Ptr;
646 const uint16_t *Src = (uint16_t*)Val.IntVal.getRawData();
647 // This is endian dependent, but it will only work on x86 anyway.
648 Dest[0] = Src[4];
649 Dest[1] = Src[0];
650 Dest[2] = Src[1];
651 Dest[3] = Src[2];
652 Dest[4] = Src[3];
653 break;
654 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000655 case Type::PointerTyID:
656 *((PointerTy*)Ptr) = Val.PointerVal;
657 break;
658 default:
659 cerr << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000660 }
661}
662
Misha Brukman4afac182003-10-10 17:45:12 +0000663/// FIXME: document
664///
Reid Spencerf0f09a92007-03-03 08:36:29 +0000665void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
666 GenericValue *Ptr,
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000667 const Type *Ty) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000668 switch (Ty->getTypeID()) {
669 case Type::IntegerTyID: {
670 unsigned BitWidth = cast<IntegerType>(Ty)->getBitWidth();
671 if (BitWidth <= 8)
672 Result.IntVal = APInt(BitWidth, *((uint8_t*)Ptr));
673 else if (BitWidth <= 16) {
674 Result.IntVal = APInt(BitWidth, *((uint16_t*)Ptr));
675 } else if (BitWidth <= 32) {
676 Result.IntVal = APInt(BitWidth, *((uint32_t*)Ptr));
677 } else if (BitWidth <= 64) {
678 Result.IntVal = APInt(BitWidth, *((uint64_t*)Ptr));
679 } else
Zhou Sheng849c5b42007-05-24 15:03:18 +0000680 Result.IntVal = APInt(BitWidth, (BitWidth+63)/64, (uint64_t*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000681 break;
682 }
683 case Type::FloatTyID:
684 Result.FloatVal = *((float*)Ptr);
685 break;
686 case Type::DoubleTyID:
687 Result.DoubleVal = *((double*)Ptr);
688 break;
689 case Type::PointerTyID:
690 Result.PointerVal = *((PointerTy*)Ptr);
691 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000692 case Type::X86_FP80TyID: {
693 // This is endian dependent, but it will only work on x86 anyway.
694 uint16_t x[8], *p = (uint16_t*)Ptr;
695 x[0] = p[1];
696 x[1] = p[2];
697 x[2] = p[3];
698 x[3] = p[4];
699 x[4] = p[0];
700 Result.IntVal = APInt(80, 2, x);
701 break;
702 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000703 default:
704 cerr << "Cannot load value of type " << *Ty << "!\n";
705 abort();
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000706 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000707}
708
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000709// InitializeMemory - Recursive function to apply a Constant value into the
710// specified memory location...
711//
712void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000713 if (isa<UndefValue>(Init)) {
714 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000715 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000716 unsigned ElementSize =
Owen Andersona69571c2006-05-03 01:29:57 +0000717 getTargetData()->getTypeSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000718 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
719 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
720 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000721 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000722 GenericValue Val = getConstantValue(Init);
723 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
724 return;
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000725 } else if (isa<ConstantAggregateZero>(Init)) {
Owen Andersona69571c2006-05-03 01:29:57 +0000726 memset(Addr, 0, (size_t)getTargetData()->getTypeSize(Init->getType()));
Chris Lattnerdd2c82a2004-02-15 05:54:06 +0000727 return;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000728 }
729
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000730 switch (Init->getType()->getTypeID()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000731 case Type::ArrayTyID: {
732 const ConstantArray *CPA = cast<ConstantArray>(Init);
Misha Brukmanedf128a2005-04-21 22:36:52 +0000733 unsigned ElementSize =
Owen Andersona69571c2006-05-03 01:29:57 +0000734 getTargetData()->getTypeSize(CPA->getType()->getElementType());
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000735 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
736 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000737 return;
738 }
739
740 case Type::StructTyID: {
741 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
742 const StructLayout *SL =
Owen Andersona69571c2006-05-03 01:29:57 +0000743 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +0000744 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000745 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000746 return;
747 }
748
749 default:
Bill Wendlinge8156192006-12-07 01:30:32 +0000750 cerr << "Bad Type: " << *Init->getType() << "\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000751 assert(0 && "Unknown constant type to initialize memory with!");
752 }
753}
754
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000755/// EmitGlobals - Emit all of the global variables to memory, storing their
756/// addresses into GlobalAddress. This must make sure to copy the contents of
757/// their initializers into the memory.
758///
759void ExecutionEngine::emitGlobals() {
Owen Andersona69571c2006-05-03 01:29:57 +0000760 const TargetData *TD = getTargetData();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000761
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000762 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000763 // to hold them. If there is more than one module, do a prepass over globals
764 // to figure out how the different modules should link together.
765 //
766 std::map<std::pair<std::string, const Type*>,
767 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000768
Chris Lattnerfe854032006-08-16 01:24:12 +0000769 if (Modules.size() != 1) {
770 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
771 Module &M = *Modules[m]->getModule();
772 for (Module::const_global_iterator I = M.global_begin(),
773 E = M.global_end(); I != E; ++I) {
774 const GlobalValue *GV = I;
Reid Spencer5cbf9852007-01-30 20:08:39 +0000775 if (GV->hasInternalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000776 GV->hasAppendingLinkage() || !GV->hasName())
777 continue;// Ignore external globals and globals with internal linkage.
778
779 const GlobalValue *&GVEntry =
780 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
781
782 // If this is the first time we've seen this global, it is the canonical
783 // version.
784 if (!GVEntry) {
785 GVEntry = GV;
786 continue;
787 }
788
789 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000790 if (GVEntry->hasExternalLinkage() ||
791 GVEntry->hasDLLImportLinkage() ||
792 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000793 continue;
794
795 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
796 // symbol.
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000797 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000798 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000799 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000800 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000801 }
802
803 std::vector<const GlobalValue*> NonCanonicalGlobals;
804 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
805 Module &M = *Modules[m]->getModule();
806 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
807 I != E; ++I) {
808 // In the multi-module case, see what this global maps to.
809 if (!LinkedGlobalsMap.empty()) {
810 if (const GlobalValue *GVEntry =
811 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
812 // If something else is the canonical global, ignore this one.
813 if (GVEntry != &*I) {
814 NonCanonicalGlobals.push_back(I);
815 continue;
816 }
817 }
818 }
819
Reid Spencer5cbf9852007-01-30 20:08:39 +0000820 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000821 // Get the type of the global.
822 const Type *Ty = I->getType()->getElementType();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000823
Chris Lattnerfe854032006-08-16 01:24:12 +0000824 // Allocate some memory for it!
825 unsigned Size = TD->getTypeSize(Ty);
826 addGlobalMapping(I, new char[Size]);
827 } else {
828 // External variable reference. Try to use the dynamic loader to
829 // get a pointer to it.
830 if (void *SymAddr =
831 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName().c_str()))
832 addGlobalMapping(I, SymAddr);
833 else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000834 cerr << "Could not resolve external global address: "
835 << I->getName() << "\n";
Chris Lattnerfe854032006-08-16 01:24:12 +0000836 abort();
837 }
838 }
839 }
840
841 // If there are multiple modules, map the non-canonical globals to their
842 // canonical location.
843 if (!NonCanonicalGlobals.empty()) {
844 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
845 const GlobalValue *GV = NonCanonicalGlobals[i];
846 const GlobalValue *CGV =
847 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
848 void *Ptr = getPointerToGlobalIfAvailable(CGV);
849 assert(Ptr && "Canonical global wasn't codegen'd!");
850 addGlobalMapping(GV, getPointerToGlobalIfAvailable(CGV));
851 }
852 }
853
Reid Spencera54b7cb2007-01-12 07:05:14 +0000854 // Now that all of the globals are set up in memory, loop through them all
855 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +0000856 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
857 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000858 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +0000859 if (!LinkedGlobalsMap.empty()) {
860 if (const GlobalValue *GVEntry =
861 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
862 if (GVEntry != &*I) // Not the canonical variable.
863 continue;
864 }
865 EmitGlobalVariable(I);
866 }
867 }
868 }
Chris Lattner24b0a182003-12-20 02:45:37 +0000869}
870
871// EmitGlobalVariable - This method emits the specified global variable to the
872// address specified in GlobalAddresses, or allocates new memory if it's not
873// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000874void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +0000875 void *GA = getPointerToGlobalIfAvailable(GV);
Bill Wendling480f0932006-11-27 23:54:50 +0000876 DOUT << "Global '" << GV->getName() << "' -> " << GA << "\n";
Chris Lattner23c47242004-02-08 19:33:23 +0000877
Chris Lattnerc07ed132003-12-20 03:36:47 +0000878 const Type *ElTy = GV->getType()->getElementType();
Owen Andersona69571c2006-05-03 01:29:57 +0000879 size_t GVSize = (size_t)getTargetData()->getTypeSize(ElTy);
Chris Lattner24b0a182003-12-20 02:45:37 +0000880 if (GA == 0) {
881 // If it's not already specified, allocate memory for the global.
Chris Lattnera98c5452004-11-19 08:44:07 +0000882 GA = new char[GVSize];
Chris Lattner55d86482003-12-31 20:21:04 +0000883 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +0000884 }
Chris Lattnerc07ed132003-12-20 03:36:47 +0000885
Chris Lattner24b0a182003-12-20 02:45:37 +0000886 InitializeMemory(GV->getInitializer(), GA);
Chris Lattner813c8152005-01-08 20:13:19 +0000887 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +0000888 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000889}