blob: 5be3aa87e0a58e38f774f7d1009ab5a3a3a460b9 [file] [log] [blame]
Misha Brukman4afac182003-10-10 17:45:12 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00009//
Chris Lattnerbd199fb2002-12-24 00:01:05 +000010// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Chris Lattnerbd199fb2002-12-24 00:01:05 +000018#include "llvm/Constants.h"
Misha Brukman19684162003-10-16 21:18:05 +000019#include "llvm/DerivedTypes.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000020#include "llvm/Module.h"
Misha Brukman19684162003-10-16 21:18:05 +000021#include "llvm/ModuleProvider.h"
Chris Lattnerfd131292003-09-05 20:08:15 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner9f3ff922009-08-23 22:49:13 +000023#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Torok Edwin31e24662009-07-07 17:32:34 +000025#include "llvm/Support/ErrorHandling.h"
Chris Lattnere7fd5532006-05-08 22:00:52 +000026#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +000027#include "llvm/Support/ValueHandle.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/raw_ostream.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000029#include "llvm/System/DynamicLibrary.h"
Duncan Sands67f1c492007-12-12 23:03:45 +000030#include "llvm/System/Host.h"
Reid Spencerdf5a37e2004-11-29 14:11:29 +000031#include "llvm/Target/TargetData.h"
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +000032#include <cmath>
33#include <cstring>
Chris Lattnerc2ee9b92003-11-19 21:08:57 +000034using namespace llvm;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner36343732006-12-19 22:43:32 +000036STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
37STATISTIC(NumGlobals , "Number of global vars initialized");
Chris Lattnerbd199fb2002-12-24 00:01:05 +000038
Reid Kleckner4b1511b2009-07-18 00:42:18 +000039ExecutionEngine *(*ExecutionEngine::JITCtor)(ModuleProvider *MP,
40 std::string *ErrorStr,
41 JITMemoryManager *JMM,
42 CodeGenOpt::Level OptLevel,
43 bool GVsWithCode) = 0;
44ExecutionEngine *(*ExecutionEngine::InterpCtor)(ModuleProvider *MP,
45 std::string *ErrorStr) = 0;
Nicolas Geoffrayafe6c2b2008-02-13 18:39:37 +000046ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
47
Chris Lattner2fe4bb02006-03-22 06:07:50 +000048
Chris Lattnerd958a5a2007-10-22 02:50:12 +000049ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Chris Lattner3d6e33d2006-11-09 19:31:15 +000050 LazyCompilationDisabled = false;
Evan Cheng446531e2008-09-24 16:25:55 +000051 GVCompilationDisabled = false;
Evan Cheng1b088f32008-06-17 16:49:02 +000052 SymbolSearchingDisabled = false;
Nate Begemand6b7a242009-02-18 08:31:02 +000053 DlsymStubsEnabled = false;
Chris Lattnerfe854032006-08-16 01:24:12 +000054 Modules.push_back(P);
Misha Brukman19684162003-10-16 21:18:05 +000055 assert(P && "ModuleProvider is null?");
56}
57
Brian Gaeke8e539482003-09-04 22:57:27 +000058ExecutionEngine::~ExecutionEngine() {
Reid Spencerd4c0e622007-03-03 18:19:18 +000059 clearAllGlobalMappings();
Chris Lattnerfe854032006-08-16 01:24:12 +000060 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
61 delete Modules[i];
Brian Gaeke8e539482003-09-04 22:57:27 +000062}
63
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000064char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
65 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +000066 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1392008-10-25 15:41:43 +000067 return new char[GVSize];
68}
69
Devang Patel73d0e212007-10-15 19:56:32 +000070/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
Nate Begeman60789e42009-01-23 19:27:28 +000071/// Relases the Module from the ModuleProvider, materializing it in the
72/// process, and returns the materialized Module.
Devang Patel73d0e212007-10-15 19:56:32 +000073Module* ExecutionEngine::removeModuleProvider(ModuleProvider *P,
74 std::string *ErrInfo) {
75 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
76 E = Modules.end(); I != E; ++I) {
77 ModuleProvider *MP = *I;
78 if (MP == P) {
79 Modules.erase(I);
Nate Begemanf049e072008-05-21 16:34:48 +000080 clearGlobalMappingsFromModule(MP->getModule());
Devang Patel73d0e212007-10-15 19:56:32 +000081 return MP->releaseModule(ErrInfo);
82 }
83 }
84 return NULL;
85}
86
Nate Begeman60789e42009-01-23 19:27:28 +000087/// deleteModuleProvider - Remove a ModuleProvider from the list of modules,
88/// and deletes the ModuleProvider and owned Module. Avoids materializing
89/// the underlying module.
90void ExecutionEngine::deleteModuleProvider(ModuleProvider *P,
91 std::string *ErrInfo) {
92 for(SmallVector<ModuleProvider *, 1>::iterator I = Modules.begin(),
93 E = Modules.end(); I != E; ++I) {
94 ModuleProvider *MP = *I;
95 if (MP == P) {
96 Modules.erase(I);
97 clearGlobalMappingsFromModule(MP->getModule());
98 delete MP;
99 return;
100 }
101 }
102}
103
Chris Lattnerfe854032006-08-16 01:24:12 +0000104/// FindFunctionNamed - Search all of the active modules to find the one that
105/// defines FnName. This is very slow operation and shouldn't be used for
106/// general code.
107Function *ExecutionEngine::FindFunctionNamed(const char *FnName) {
108 for (unsigned i = 0, e = Modules.size(); i != e; ++i) {
Reid Spencer688b0492007-02-05 21:19:13 +0000109 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
Chris Lattnerfe854032006-08-16 01:24:12 +0000110 return F;
111 }
112 return 0;
113}
114
115
Chris Lattnere7fd5532006-05-08 22:00:52 +0000116/// addGlobalMapping - Tell the execution engine that the specified global is
117/// at the specified location. This is used internally as functions are JIT'd
118/// and as global variables are laid out in memory. It can and should also be
119/// used by clients of the EE that want to have an LLVM global overlay
120/// existing data in memory.
121void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) {
122 MutexGuard locked(lock);
Evan Chengbc4707a2008-09-18 07:54:21 +0000123
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000124 DEBUG(errs() << "JIT: Map \'" << GV->getName()
125 << "\' to [" << Addr << "]\n";);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000126 void *&CurVal = state.getGlobalAddressMap(locked)[GV];
127 assert((CurVal == 0 || Addr == 0) && "GlobalMapping already established!");
128 CurVal = Addr;
129
130 // If we are using the reverse mapping, add it too
131 if (!state.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000132 AssertingVH<const GlobalValue> &V =
133 state.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000134 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
135 V = GV;
136 }
137}
138
139/// clearAllGlobalMappings - Clear all global mappings and start over again
140/// use in dynamic compilation scenarios when you want to move globals
141void ExecutionEngine::clearAllGlobalMappings() {
142 MutexGuard locked(lock);
143
144 state.getGlobalAddressMap(locked).clear();
145 state.getGlobalAddressReverseMap(locked).clear();
146}
147
Nate Begemanf049e072008-05-21 16:34:48 +0000148/// clearGlobalMappingsFromModule - Clear all global mappings that came from a
149/// particular module, because it has been removed from the JIT.
150void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) {
151 MutexGuard locked(lock);
152
153 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000154 state.getGlobalAddressMap(locked).erase(&*FI);
155 state.getGlobalAddressReverseMap(locked).erase(&*FI);
Nate Begemanf049e072008-05-21 16:34:48 +0000156 }
157 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
158 GI != GE; ++GI) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000159 state.getGlobalAddressMap(locked).erase(&*GI);
160 state.getGlobalAddressReverseMap(locked).erase(&*GI);
Nate Begemanf049e072008-05-21 16:34:48 +0000161 }
162}
163
Chris Lattnere7fd5532006-05-08 22:00:52 +0000164/// updateGlobalMapping - Replace an existing mapping for GV with a new
165/// address. This updates both maps as required. If "Addr" is null, the
166/// entry for the global is removed from the mappings.
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000167void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Chris Lattnere7fd5532006-05-08 22:00:52 +0000168 MutexGuard locked(lock);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000169
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000170 std::map<AssertingVH<const GlobalValue>, void *> &Map =
171 state.getGlobalAddressMap(locked);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000172
Chris Lattnere7fd5532006-05-08 22:00:52 +0000173 // Deleting from the mapping?
174 if (Addr == 0) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000175 std::map<AssertingVH<const GlobalValue>, void *>::iterator I = Map.find(GV);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000176 void *OldVal;
177 if (I == Map.end())
178 OldVal = 0;
179 else {
180 OldVal = I->second;
181 Map.erase(I);
182 }
183
Chris Lattnere7fd5532006-05-08 22:00:52 +0000184 if (!state.getGlobalAddressReverseMap(locked).empty())
Jeffrey Yasskin0a962312009-08-04 23:53:16 +0000185 state.getGlobalAddressReverseMap(locked).erase(OldVal);
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000186 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000187 }
188
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000189 void *&CurVal = Map[GV];
190 void *OldVal = CurVal;
191
Chris Lattnere7fd5532006-05-08 22:00:52 +0000192 if (CurVal && !state.getGlobalAddressReverseMap(locked).empty())
193 state.getGlobalAddressReverseMap(locked).erase(CurVal);
194 CurVal = Addr;
195
196 // If we are using the reverse mapping, add it too
197 if (!state.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000198 AssertingVH<const GlobalValue> &V =
199 state.getGlobalAddressReverseMap(locked)[Addr];
Chris Lattnere7fd5532006-05-08 22:00:52 +0000200 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
201 V = GV;
202 }
Chris Lattnerf4cc3092008-04-04 04:47:41 +0000203 return OldVal;
Chris Lattnere7fd5532006-05-08 22:00:52 +0000204}
205
206/// getPointerToGlobalIfAvailable - This returns the address of the specified
207/// global value if it is has already been codegen'd, otherwise it returns null.
208///
209void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) {
210 MutexGuard locked(lock);
211
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000212 std::map<AssertingVH<const GlobalValue>, void*>::iterator I =
213 state.getGlobalAddressMap(locked).find(GV);
Chris Lattnere7fd5532006-05-08 22:00:52 +0000214 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
215}
216
Chris Lattner55d86482003-12-31 20:21:04 +0000217/// getGlobalValueAtAddress - Return the LLVM global value object that starts
218/// at the specified address.
219///
220const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
Reid Spenceree448632005-07-12 15:51:55 +0000221 MutexGuard locked(lock);
222
Chris Lattner55d86482003-12-31 20:21:04 +0000223 // If we haven't computed the reverse mapping yet, do so first.
Reid Spenceree448632005-07-12 15:51:55 +0000224 if (state.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000225 for (std::map<AssertingVH<const GlobalValue>, void *>::iterator
Chris Lattnere7fd5532006-05-08 22:00:52 +0000226 I = state.getGlobalAddressMap(locked).begin(),
227 E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
228 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second,
229 I->first));
Chris Lattner55d86482003-12-31 20:21:04 +0000230 }
231
Jeffrey Yasskin0d5bd592009-08-07 19:54:29 +0000232 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Reid Spenceree448632005-07-12 15:51:55 +0000233 state.getGlobalAddressReverseMap(locked).find(Addr);
234 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
Chris Lattner55d86482003-12-31 20:21:04 +0000235}
Chris Lattner87f03102003-12-26 06:50:30 +0000236
237// CreateArgv - Turn a vector of strings into a nice argv style array of
238// pointers to null terminated strings.
239//
Owen Anderson1d0be152009-08-13 21:58:54 +0000240static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Chris Lattner87f03102003-12-26 06:50:30 +0000241 const std::vector<std::string> &InputArgv) {
Owen Andersona69571c2006-05-03 01:29:57 +0000242 unsigned PtrSize = EE->getTargetData()->getPointerSize();
Chris Lattner87f03102003-12-26 06:50:30 +0000243 char *Result = new char[(InputArgv.size()+1)*PtrSize];
244
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000245 DEBUG(errs() << "JIT: ARGV = " << (void*)Result << "\n");
Owen Anderson1d0be152009-08-13 21:58:54 +0000246 const Type *SBytePtr = PointerType::getUnqual(Type::getInt8Ty(C));
Chris Lattner87f03102003-12-26 06:50:30 +0000247
248 for (unsigned i = 0; i != InputArgv.size(); ++i) {
249 unsigned Size = InputArgv[i].size()+1;
250 char *Dest = new char[Size];
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000251 DEBUG(errs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Misha Brukmanedf128a2005-04-21 22:36:52 +0000252
Chris Lattner87f03102003-12-26 06:50:30 +0000253 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
254 Dest[Size-1] = 0;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000255
Chris Lattner87f03102003-12-26 06:50:30 +0000256 // Endian safe: Result[i] = (PointerTy)Dest;
257 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
258 SBytePtr);
259 }
260
261 // Null terminate it
262 EE->StoreValueToMemory(PTOGV(0),
263 (GenericValue*)(Result+InputArgv.size()*PtrSize),
264 SBytePtr);
265 return Result;
266}
267
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000268
269/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng18314dc2008-09-30 15:51:21 +0000270/// the static constructors or destructors for a module, depending on the
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000271/// value of isDtors.
Evan Cheng18314dc2008-09-30 15:51:21 +0000272void ExecutionEngine::runStaticConstructorsDestructors(Module *module, bool isDtors) {
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000273 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000274
Chris Lattnerfe854032006-08-16 01:24:12 +0000275 // Execute global ctors/dtors for each module in the program.
Chris Lattnerfe854032006-08-16 01:24:12 +0000276
Evan Cheng18314dc2008-09-30 15:51:21 +0000277 GlobalVariable *GV = module->getNamedGlobal(Name);
278
279 // If this global has internal linkage, or if it has a use, then it must be
280 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
281 // this is the case, don't execute any of the global ctors, __main will do
282 // it.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000283 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng18314dc2008-09-30 15:51:21 +0000284
285 // Should be an array of '{ int, void ()* }' structs. The first value is
286 // the init priority, which we ignore.
287 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
288 if (!InitList) return;
289 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
290 if (ConstantStruct *CS =
291 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
292 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
293
294 Constant *FP = CS->getOperand(1);
295 if (FP->isNullValue())
296 break; // Found a null terminator, exit.
297
298 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
299 if (CE->isCast())
300 FP = CE->getOperand(0);
301 if (Function *F = dyn_cast<Function>(FP)) {
302 // Execute the ctor/dtor function!
303 runFunction(F, std::vector<GenericValue>());
304 }
305 }
306}
307
308/// runStaticConstructorsDestructors - This method is used to execute all of
309/// the static constructors or destructors for a program, depending on the
310/// value of isDtors.
311void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
312 // Execute global ctors/dtors for each module in the program.
313 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
314 runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
Chris Lattner9ca6cda2006-03-08 18:42:46 +0000315}
316
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000317#ifndef NDEBUG
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000318/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
319static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
320 unsigned PtrSize = EE->getTargetData()->getPointerSize();
321 for (unsigned i = 0; i < PtrSize; ++i)
322 if (*(i + (uint8_t*)Loc))
323 return false;
324 return true;
325}
Dan Gohmanb6e3d6c2008-08-26 01:38:29 +0000326#endif
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000327
Chris Lattner87f03102003-12-26 06:50:30 +0000328/// runFunctionAsMain - This is a helper function which wraps runFunction to
329/// handle the common task of starting up main with the specified argc, argv,
330/// and envp parameters.
331int ExecutionEngine::runFunctionAsMain(Function *Fn,
332 const std::vector<std::string> &argv,
333 const char * const * envp) {
334 std::vector<GenericValue> GVArgs;
335 GenericValue GVArgc;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000336 GVArgc.IntVal = APInt(32, argv.size());
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000337
338 // Check main() type
Chris Lattnerf24d0992004-08-16 01:05:35 +0000339 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000340 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lamb43ad6b32007-12-17 01:12:55 +0000341 const Type* PPInt8Ty =
Owen Anderson1d0be152009-08-13 21:58:54 +0000342 PointerType::getUnqual(PointerType::getUnqual(
343 Type::getInt8Ty(Fn->getContext())));
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000344 switch (NumArgs) {
345 case 3:
346 if (FTy->getParamType(2) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000347 llvm_report_error("Invalid type for third argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000348 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000349 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000350 case 2:
351 if (FTy->getParamType(1) != PPInt8Ty) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000352 llvm_report_error("Invalid type for second argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000353 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000354 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000355 case 1:
Owen Anderson1d0be152009-08-13 21:58:54 +0000356 if (FTy->getParamType(0) != Type::getInt32Ty(Fn->getContext())) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000357 llvm_report_error("Invalid type for first argument of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000358 }
Anton Korobeynikovfb450862007-06-03 19:20:49 +0000359 // FALLS THROUGH
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000360 case 0:
Chris Lattner45f36832009-02-04 17:48:18 +0000361 if (!isa<IntegerType>(FTy->getReturnType()) &&
Owen Anderson1d0be152009-08-13 21:58:54 +0000362 FTy->getReturnType() != Type::getVoidTy(FTy->getContext())) {
Torok Edwin7d696d82009-07-11 13:10:19 +0000363 llvm_report_error("Invalid return type of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000364 }
365 break;
366 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000367 llvm_report_error("Invalid number of arguments of main() supplied");
Anton Korobeynikov499d8f02007-06-03 19:17:35 +0000368 }
369
Chris Lattnerf24d0992004-08-16 01:05:35 +0000370 if (NumArgs) {
371 GVArgs.push_back(GVArgc); // Arg #0 = argc.
372 if (NumArgs > 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000373 // Arg #1 = argv.
374 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000375 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Chris Lattnerf24d0992004-08-16 01:05:35 +0000376 "argv[0] was null after CreateArgv");
377 if (NumArgs > 2) {
378 std::vector<std::string> EnvVars;
379 for (unsigned i = 0; envp[i]; ++i)
380 EnvVars.push_back(envp[i]);
Owen Anderson1d0be152009-08-13 21:58:54 +0000381 // Arg #2 = envp.
382 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Chris Lattnerf24d0992004-08-16 01:05:35 +0000383 }
384 }
385 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000386 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
Chris Lattner87f03102003-12-26 06:50:30 +0000387}
388
Misha Brukman19684162003-10-16 21:18:05 +0000389/// If possible, create a JIT, unless the caller specifically requests an
390/// Interpreter or there's an error. If even an Interpreter cannot be created,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000391/// NULL is returned.
Misha Brukman4afac182003-10-10 17:45:12 +0000392///
Misha Brukmanedf128a2005-04-21 22:36:52 +0000393ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
Reid Spencerd4c0e622007-03-03 18:19:18 +0000394 bool ForceInterpreter,
Evan Cheng502f20b2008-08-08 08:11:34 +0000395 std::string *ErrorStr,
Jeffrey Yasskin489393d2009-07-08 21:59:57 +0000396 CodeGenOpt::Level OptLevel,
397 bool GVsWithCode) {
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000398 return EngineBuilder(MP)
399 .setEngineKind(ForceInterpreter
400 ? EngineKind::Interpreter
401 : EngineKind::JIT)
402 .setErrorStr(ErrorStr)
403 .setOptLevel(OptLevel)
404 .setAllocateGVsWithCode(GVsWithCode)
405 .create();
406}
Brian Gaeke82d82772003-09-03 20:34:19 +0000407
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000408ExecutionEngine *ExecutionEngine::create(Module *M) {
409 return EngineBuilder(M).create();
410}
411
412/// EngineBuilder - Overloaded constructor that automatically creates an
413/// ExistingModuleProvider for an existing module.
414EngineBuilder::EngineBuilder(Module *m) : MP(new ExistingModuleProvider(m)) {
415 InitEngine();
416}
417
418ExecutionEngine *EngineBuilder::create() {
Nick Lewycky6456d862008-03-08 02:49:45 +0000419 // Make sure we can resolve symbols in the program as well. The zero arg
420 // to the function tells DynamicLibrary to load the program, not a library.
421 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
422 return 0;
423
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000424 // If the user specified a memory manager but didn't specify which engine to
425 // create, we assume they only want the JIT, and we fail if they only want
426 // the interpreter.
427 if (JMM) {
428 if (WhichEngine & EngineKind::JIT) {
429 WhichEngine = EngineKind::JIT;
430 } else {
431 *ErrorStr = "Cannot create an interpreter with a memory manager.";
432 }
433 }
Brian Gaeke82d82772003-09-03 20:34:19 +0000434
Reid Kleckner4b1511b2009-07-18 00:42:18 +0000435 ExecutionEngine *EE = 0;
436
437 // Unless the interpreter was explicitly selected or the JIT is not linked,
438 // try making a JIT.
439 if (WhichEngine & EngineKind::JIT && ExecutionEngine::JITCtor) {
440 EE = ExecutionEngine::JITCtor(MP, ErrorStr, JMM, OptLevel,
441 AllocateGVsWithCode);
442 }
443
444 // If we can't make a JIT and we didn't request one specifically, try making
445 // an interpreter instead.
446 if (WhichEngine & EngineKind::Interpreter && EE == 0 &&
447 ExecutionEngine::InterpCtor) {
448 EE = ExecutionEngine::InterpCtor(MP, ErrorStr);
449 }
Chris Lattner73011782003-12-28 09:44:37 +0000450
Brian Gaeke82d82772003-09-03 20:34:19 +0000451 return EE;
452}
453
Misha Brukman4afac182003-10-10 17:45:12 +0000454/// getPointerToGlobal - This returns the address of the specified global
455/// value. This may involve code generation if it's a function.
456///
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000457void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
Brian Gaeke37df4602003-08-13 18:16:14 +0000458 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000459 return getPointerToFunction(F);
460
Reid Spenceree448632005-07-12 15:51:55 +0000461 MutexGuard locked(lock);
Jeff Cohen68835dd2006-02-07 05:11:57 +0000462 void *p = state.getGlobalAddressMap(locked)[GV];
463 if (p)
464 return p;
465
466 // Global variable might have been added since interpreter started.
467 if (GlobalVariable *GVar =
468 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
469 EmitGlobalVariable(GVar);
470 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000471 llvm_unreachable("Global hasn't had an address allocated yet!");
Reid Spenceree448632005-07-12 15:51:55 +0000472 return state.getGlobalAddressMap(locked)[GV];
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000473}
474
Reid Spencer3da59db2006-11-27 01:05:10 +0000475/// This function converts a Constant* into a GenericValue. The interesting
476/// part is if C is a ConstantExpr.
Reid Spencerba28cb92007-08-11 15:57:56 +0000477/// @brief Get a GenericValue for a Constant*
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000478GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000479 // If its undefined, return the garbage.
Reid Spencerbce30f12007-03-06 22:23:15 +0000480 if (isa<UndefValue>(C))
481 return GenericValue();
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000482
Reid Spencer3da59db2006-11-27 01:05:10 +0000483 // If the value is a ConstantExpr
484 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Reid Spencerbce30f12007-03-06 22:23:15 +0000485 Constant *Op0 = CE->getOperand(0);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000486 switch (CE->getOpcode()) {
487 case Instruction::GetElementPtr: {
Reid Spencer3da59db2006-11-27 01:05:10 +0000488 // Compute the index
Reid Spencerbce30f12007-03-06 22:23:15 +0000489 GenericValue Result = getConstantValue(Op0);
Chris Lattner829621c2007-02-10 20:35:22 +0000490 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000491 uint64_t Offset =
Reid Spencerbce30f12007-03-06 22:23:15 +0000492 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
Misha Brukmanedf128a2005-04-21 22:36:52 +0000493
Reid Spencer8fb0f192007-03-06 03:04:04 +0000494 char* tmp = (char*) Result.PointerVal;
495 Result = PTOGV(tmp + Offset);
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000496 return Result;
497 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000498 case Instruction::Trunc: {
499 GenericValue GV = getConstantValue(Op0);
500 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
501 GV.IntVal = GV.IntVal.trunc(BitWidth);
502 return GV;
503 }
504 case Instruction::ZExt: {
505 GenericValue GV = getConstantValue(Op0);
506 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
507 GV.IntVal = GV.IntVal.zext(BitWidth);
508 return GV;
509 }
510 case Instruction::SExt: {
511 GenericValue GV = getConstantValue(Op0);
512 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
513 GV.IntVal = GV.IntVal.sext(BitWidth);
514 return GV;
515 }
516 case Instruction::FPTrunc: {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000517 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000518 GenericValue GV = getConstantValue(Op0);
519 GV.FloatVal = float(GV.DoubleVal);
520 return GV;
521 }
522 case Instruction::FPExt:{
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000523 // FIXME long double
Reid Spencerbce30f12007-03-06 22:23:15 +0000524 GenericValue GV = getConstantValue(Op0);
525 GV.DoubleVal = double(GV.FloatVal);
526 return GV;
527 }
528 case Instruction::UIToFP: {
529 GenericValue GV = getConstantValue(Op0);
Owen Anderson1d0be152009-08-13 21:58:54 +0000530 if (CE->getType() == Type::getFloatTy(CE->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000531 GV.FloatVal = float(GV.IntVal.roundToDouble());
Owen Anderson1d0be152009-08-13 21:58:54 +0000532 else if (CE->getType() == Type::getDoubleTy(CE->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000533 GV.DoubleVal = GV.IntVal.roundToDouble();
Owen Anderson1d0be152009-08-13 21:58:54 +0000534 else if (CE->getType() == Type::getX86_FP80Ty(Op0->getContext())) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000535 const uint64_t zero[] = {0, 0};
536 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000537 (void)apf.convertFromAPInt(GV.IntVal,
538 false,
539 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000540 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000541 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000542 return GV;
543 }
544 case Instruction::SIToFP: {
545 GenericValue GV = getConstantValue(Op0);
Owen Anderson1d0be152009-08-13 21:58:54 +0000546 if (CE->getType() == Type::getFloatTy(CE->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000547 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Owen Anderson1d0be152009-08-13 21:58:54 +0000548 else if (CE->getType() == Type::getDoubleTy(CE->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000549 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Owen Anderson1d0be152009-08-13 21:58:54 +0000550 else if (CE->getType() == Type::getX86_FP80Ty(CE->getContext())) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000551 const uint64_t zero[] = { 0, 0};
552 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman62824062008-02-29 01:27:13 +0000553 (void)apf.convertFromAPInt(GV.IntVal,
554 true,
555 APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000556 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000557 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000558 return GV;
559 }
560 case Instruction::FPToUI: // double->APInt conversion handles sign
561 case Instruction::FPToSI: {
562 GenericValue GV = getConstantValue(Op0);
563 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Owen Anderson1d0be152009-08-13 21:58:54 +0000564 if (Op0->getType() == Type::getFloatTy(Op0->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000565 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Owen Anderson1d0be152009-08-13 21:58:54 +0000566 else if (Op0->getType() == Type::getDoubleTy(Op0->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000567 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Owen Anderson1d0be152009-08-13 21:58:54 +0000568 else if (Op0->getType() == Type::getX86_FP80Ty(Op0->getContext())) {
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000569 APFloat apf = APFloat(GV.IntVal);
570 uint64_t v;
Dale Johannesen23a98552008-10-09 23:00:39 +0000571 bool ignored;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000572 (void)apf.convertToInteger(&v, BitWidth,
573 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen23a98552008-10-09 23:00:39 +0000574 APFloat::rmTowardZero, &ignored);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000575 GV.IntVal = v; // endian?
576 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000577 return GV;
578 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000579 case Instruction::PtrToInt: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000580 GenericValue GV = getConstantValue(Op0);
581 uint32_t PtrWidth = TD->getPointerSizeInBits();
582 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
583 return GV;
584 }
585 case Instruction::IntToPtr: {
586 GenericValue GV = getConstantValue(Op0);
587 uint32_t PtrWidth = TD->getPointerSizeInBits();
588 if (PtrWidth != GV.IntVal.getBitWidth())
589 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
590 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
591 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
Reid Spencer3da59db2006-11-27 01:05:10 +0000592 return GV;
593 }
594 case Instruction::BitCast: {
Reid Spencerbce30f12007-03-06 22:23:15 +0000595 GenericValue GV = getConstantValue(Op0);
596 const Type* DestTy = CE->getType();
597 switch (Op0->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000598 default: llvm_unreachable("Invalid bitcast operand");
Reid Spencerbce30f12007-03-06 22:23:15 +0000599 case Type::IntegerTyID:
600 assert(DestTy->isFloatingPoint() && "invalid bitcast");
Owen Anderson1d0be152009-08-13 21:58:54 +0000601 if (DestTy == Type::getFloatTy(Op0->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000602 GV.FloatVal = GV.IntVal.bitsToFloat();
Owen Anderson1d0be152009-08-13 21:58:54 +0000603 else if (DestTy == Type::getDoubleTy(DestTy->getContext()))
Reid Spencerbce30f12007-03-06 22:23:15 +0000604 GV.DoubleVal = GV.IntVal.bitsToDouble();
605 break;
606 case Type::FloatTyID:
Owen Anderson1d0be152009-08-13 21:58:54 +0000607 assert(DestTy == Type::getInt32Ty(DestTy->getContext()) &&
608 "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000609 GV.IntVal.floatToBits(GV.FloatVal);
610 break;
611 case Type::DoubleTyID:
Owen Anderson1d0be152009-08-13 21:58:54 +0000612 assert(DestTy == Type::getInt64Ty(DestTy->getContext()) &&
613 "Invalid bitcast");
Reid Spencerbce30f12007-03-06 22:23:15 +0000614 GV.IntVal.doubleToBits(GV.DoubleVal);
615 break;
616 case Type::PointerTyID:
617 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
618 break; // getConstantValue(Op0) above already converted it
619 }
620 return GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000621 }
Chris Lattner9a231222003-05-14 17:51:49 +0000622 case Instruction::Add:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000623 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000624 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000625 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000626 case Instruction::Mul:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000627 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000628 case Instruction::UDiv:
629 case Instruction::SDiv:
630 case Instruction::URem:
631 case Instruction::SRem:
632 case Instruction::And:
633 case Instruction::Or:
634 case Instruction::Xor: {
635 GenericValue LHS = getConstantValue(Op0);
636 GenericValue RHS = getConstantValue(CE->getOperand(1));
637 GenericValue GV;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000638 switch (CE->getOperand(0)->getType()->getTypeID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000639 default: llvm_unreachable("Bad add type!");
Reid Spencera54b7cb2007-01-12 07:05:14 +0000640 case Type::IntegerTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000641 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000642 default: llvm_unreachable("Invalid integer opcode");
Reid Spencerbce30f12007-03-06 22:23:15 +0000643 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
644 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
645 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
646 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
647 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
648 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
649 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
650 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
651 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
652 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
653 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000654 break;
655 case Type::FloatTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000656 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000657 default: llvm_unreachable("Invalid float opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000658 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000659 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000660 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000661 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000662 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000663 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
664 case Instruction::FDiv:
665 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
666 case Instruction::FRem:
667 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
668 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000669 break;
670 case Type::DoubleTyID:
Reid Spencerbce30f12007-03-06 22:23:15 +0000671 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000672 default: llvm_unreachable("Invalid double opcode");
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000673 case Instruction::FAdd:
Reid Spencerbce30f12007-03-06 22:23:15 +0000674 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000675 case Instruction::FSub:
Reid Spencerbce30f12007-03-06 22:23:15 +0000676 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000677 case Instruction::FMul:
Reid Spencerbce30f12007-03-06 22:23:15 +0000678 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
679 case Instruction::FDiv:
680 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
681 case Instruction::FRem:
682 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
683 }
Chris Lattner5f90cb82004-07-11 08:01:11 +0000684 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000685 case Type::X86_FP80TyID:
686 case Type::PPC_FP128TyID:
687 case Type::FP128TyID: {
688 APFloat apfLHS = APFloat(LHS.IntVal);
689 switch (CE->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000690 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000691 case Instruction::FAdd:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000692 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000693 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000694 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000695 case Instruction::FSub:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000696 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000697 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000698 break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000699 case Instruction::FMul:
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000700 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000701 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000702 break;
703 case Instruction::FDiv:
704 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000705 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000706 break;
707 case Instruction::FRem:
708 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen7111b022008-10-09 18:53:47 +0000709 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000710 break;
711 }
712 }
713 break;
Chris Lattner5f90cb82004-07-11 08:01:11 +0000714 }
Reid Spencerbce30f12007-03-06 22:23:15 +0000715 return GV;
716 }
Chris Lattner9a231222003-05-14 17:51:49 +0000717 default:
718 break;
719 }
Torok Edwin7d696d82009-07-11 13:10:19 +0000720 std::string msg;
721 raw_string_ostream Msg(msg);
722 Msg << "ConstantExpr not handled: " << *CE;
723 llvm_report_error(Msg.str());
Chris Lattner9a231222003-05-14 17:51:49 +0000724 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000725
Reid Spencerbce30f12007-03-06 22:23:15 +0000726 GenericValue Result;
Chris Lattnerf70c22b2004-06-17 18:19:28 +0000727 switch (C->getType()->getTypeID()) {
Reid Spencer8fb0f192007-03-06 03:04:04 +0000728 case Type::FloatTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000729 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Reid Spencera54b7cb2007-01-12 07:05:14 +0000730 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000731 case Type::DoubleTyID:
Dale Johannesen43421b32007-09-06 18:13:44 +0000732 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Reid Spencer8fb0f192007-03-06 03:04:04 +0000733 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000734 case Type::X86_FP80TyID:
735 case Type::FP128TyID:
736 case Type::PPC_FP128TyID:
Dale Johannesen7111b022008-10-09 18:53:47 +0000737 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000738 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000739 case Type::IntegerTyID:
740 Result.IntVal = cast<ConstantInt>(C)->getValue();
741 break;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000742 case Type::PointerTyID:
Reid Spencer40cf2f92004-07-18 00:41:27 +0000743 if (isa<ConstantPointerNull>(C))
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000744 Result.PointerVal = 0;
Reid Spencer40cf2f92004-07-18 00:41:27 +0000745 else if (const Function *F = dyn_cast<Function>(C))
746 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
747 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
748 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
749 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000750 llvm_unreachable("Unknown constant pointer type!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000751 break;
752 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000753 std::string msg;
754 raw_string_ostream Msg(msg);
755 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
756 llvm_report_error(Msg.str());
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000757 }
758 return Result;
759}
760
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000761/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
762/// with the integer held in IntVal.
763static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
764 unsigned StoreBytes) {
765 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
766 uint8_t *Src = (uint8_t *)IntVal.getRawData();
767
Chris Lattnerb67c9582009-01-22 19:53:00 +0000768 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000769 // Little-endian host - the source is ordered from LSB to MSB. Order the
770 // destination from LSB to MSB: Do a straight copy.
771 memcpy(Dst, Src, StoreBytes);
772 else {
773 // Big-endian host - the source is an array of 64 bit words ordered from
774 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
775 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
776 while (StoreBytes > sizeof(uint64_t)) {
777 StoreBytes -= sizeof(uint64_t);
778 // May not be aligned so use memcpy.
779 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
780 Src += sizeof(uint64_t);
781 }
782
783 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
784 }
785}
786
Nate Begeman37efe672006-04-22 18:53:45 +0000787/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
788/// is the address of the memory at which to store Val, cast to GenericValue *.
789/// It is not a pointer to a GenericValue containing the address at which to
790/// store Val.
Evan Cheng89687e32008-11-04 06:10:31 +0000791void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
792 GenericValue *Ptr, const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000793 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
794
Reid Spencer8fb0f192007-03-06 03:04:04 +0000795 switch (Ty->getTypeID()) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000796 case Type::IntegerTyID:
797 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000798 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000799 case Type::FloatTyID:
800 *((float*)Ptr) = Val.FloatVal;
801 break;
802 case Type::DoubleTyID:
803 *((double*)Ptr) = Val.DoubleVal;
804 break;
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000805 case Type::X86_FP80TyID:
806 memcpy(Ptr, Val.IntVal.getRawData(), 10);
807 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000808 case Type::PointerTyID:
809 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
810 if (StoreBytes != sizeof(PointerTy))
811 memset(Ptr, 0, StoreBytes);
812
Reid Spencer8fb0f192007-03-06 03:04:04 +0000813 *((PointerTy*)Ptr) = Val.PointerVal;
814 break;
815 default:
Chris Lattner79c5d3f2009-08-23 04:52:46 +0000816 errs() << "Cannot store value of type " << *Ty << "!\n";
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000817 }
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000818
Chris Lattnerb67c9582009-01-22 19:53:00 +0000819 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000820 // Host and target are different endian - reverse the stored bytes.
821 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
822}
823
824/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
825/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
826static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
827 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
828 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
829
Chris Lattnerb67c9582009-01-22 19:53:00 +0000830 if (sys::isLittleEndianHost())
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000831 // Little-endian host - the destination must be ordered from LSB to MSB.
832 // The source is ordered from LSB to MSB: Do a straight copy.
833 memcpy(Dst, Src, LoadBytes);
834 else {
835 // Big-endian - the destination is an array of 64 bit words ordered from
836 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
837 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
838 // a word.
839 while (LoadBytes > sizeof(uint64_t)) {
840 LoadBytes -= sizeof(uint64_t);
841 // May not be aligned so use memcpy.
842 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
843 Dst += sizeof(uint64_t);
844 }
845
846 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
847 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000848}
849
Misha Brukman4afac182003-10-10 17:45:12 +0000850/// FIXME: document
851///
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000852void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sands08bfe262008-03-10 16:38:37 +0000853 GenericValue *Ptr,
854 const Type *Ty) {
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000855 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands1eff7042007-12-10 17:43:13 +0000856
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000857 switch (Ty->getTypeID()) {
858 case Type::IntegerTyID:
859 // An APInt with all words initially zero.
860 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
861 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
862 break;
Reid Spencer8fb0f192007-03-06 03:04:04 +0000863 case Type::FloatTyID:
864 Result.FloatVal = *((float*)Ptr);
865 break;
866 case Type::DoubleTyID:
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000867 Result.DoubleVal = *((double*)Ptr);
Reid Spencer8fb0f192007-03-06 03:04:04 +0000868 break;
Duncan Sands8a43e9e2007-12-14 19:38:31 +0000869 case Type::PointerTyID:
Reid Spencer8fb0f192007-03-06 03:04:04 +0000870 Result.PointerVal = *((PointerTy*)Ptr);
871 break;
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000872 case Type::X86_FP80TyID: {
873 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands9e4635a2007-12-15 17:37:40 +0000874 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen1f8c5642009-03-24 18:16:17 +0000875 uint64_t y[2];
876 memcpy(y, Ptr, 10);
Duncan Sandsdd65a732007-11-28 10:36:19 +0000877 Result.IntVal = APInt(80, 2, y);
Dale Johannesen1abac0d2007-09-17 18:44:13 +0000878 break;
879 }
Reid Spencer8fb0f192007-03-06 03:04:04 +0000880 default:
Torok Edwin7d696d82009-07-11 13:10:19 +0000881 std::string msg;
882 raw_string_ostream Msg(msg);
883 Msg << "Cannot load value of type " << *Ty << "!";
884 llvm_report_error(Msg.str());
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000885 }
Chris Lattnerf88b9a62003-05-08 16:52:16 +0000886}
887
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000888// InitializeMemory - Recursive function to apply a Constant value into the
889// specified memory location...
890//
891void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattnerbbbfa992009-08-23 06:35:02 +0000892 DEBUG(errs() << "JIT: Initializing " << Addr << " ");
Dale Johannesendd947ea2008-08-07 01:30:15 +0000893 DEBUG(Init->dump());
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000894 if (isa<UndefValue>(Init)) {
895 return;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000896 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000897 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000898 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Robert Bocchino7c2b7c72006-01-20 18:18:40 +0000899 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
900 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
901 return;
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000902 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000903 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerb6e1dd72008-02-15 00:57:28 +0000904 return;
Dan Gohman638e3782008-05-20 03:20:09 +0000905 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
906 unsigned ElementSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000907 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman638e3782008-05-20 03:20:09 +0000908 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
909 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
910 return;
911 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
912 const StructLayout *SL =
913 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
914 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
915 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
916 return;
Chris Lattnerbd1d3822004-10-16 18:19:26 +0000917 } else if (Init->getType()->isFirstClassType()) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000918 GenericValue Val = getConstantValue(Init);
919 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
920 return;
921 }
922
Chris Lattner79c5d3f2009-08-23 04:52:46 +0000923 errs() << "Bad Type: " << *Init->getType() << "\n";
Torok Edwinc23197a2009-07-14 16:55:14 +0000924 llvm_unreachable("Unknown constant type to initialize memory with!");
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000925}
926
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000927/// EmitGlobals - Emit all of the global variables to memory, storing their
928/// addresses into GlobalAddress. This must make sure to copy the contents of
929/// their initializers into the memory.
930///
931void ExecutionEngine::emitGlobals() {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000932
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000933 // Loop over all of the global variables in the program, allocating the memory
Chris Lattnerfe854032006-08-16 01:24:12 +0000934 // to hold them. If there is more than one module, do a prepass over globals
935 // to figure out how the different modules should link together.
936 //
937 std::map<std::pair<std::string, const Type*>,
938 const GlobalValue*> LinkedGlobalsMap;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000939
Chris Lattnerfe854032006-08-16 01:24:12 +0000940 if (Modules.size() != 1) {
941 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
942 Module &M = *Modules[m]->getModule();
943 for (Module::const_global_iterator I = M.global_begin(),
944 E = M.global_end(); I != E; ++I) {
945 const GlobalValue *GV = I;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000946 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Chris Lattnerfe854032006-08-16 01:24:12 +0000947 GV->hasAppendingLinkage() || !GV->hasName())
948 continue;// Ignore external globals and globals with internal linkage.
949
950 const GlobalValue *&GVEntry =
951 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
952
953 // If this is the first time we've seen this global, it is the canonical
954 // version.
955 if (!GVEntry) {
956 GVEntry = GV;
957 continue;
958 }
959
960 // If the existing global is strong, never replace it.
Anton Korobeynikovb74ed072006-09-14 18:23:27 +0000961 if (GVEntry->hasExternalLinkage() ||
962 GVEntry->hasDLLImportLinkage() ||
963 GVEntry->hasDLLExportLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000964 continue;
965
966 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesenaafce772008-05-14 20:12:51 +0000967 // symbol. FIXME is this right for common?
Anton Korobeynikov78ee7b72006-12-01 00:25:12 +0000968 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
Chris Lattnerfe854032006-08-16 01:24:12 +0000969 GVEntry = GV;
Chris Lattnerd8c03bf2003-04-23 19:01:49 +0000970 }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000971 }
Chris Lattnerfe854032006-08-16 01:24:12 +0000972 }
973
974 std::vector<const GlobalValue*> NonCanonicalGlobals;
975 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
976 Module &M = *Modules[m]->getModule();
977 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
978 I != E; ++I) {
979 // In the multi-module case, see what this global maps to.
980 if (!LinkedGlobalsMap.empty()) {
981 if (const GlobalValue *GVEntry =
982 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
983 // If something else is the canonical global, ignore this one.
984 if (GVEntry != &*I) {
985 NonCanonicalGlobals.push_back(I);
986 continue;
987 }
988 }
989 }
990
Reid Spencer5cbf9852007-01-30 20:08:39 +0000991 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1392008-10-25 15:41:43 +0000992 addGlobalMapping(I, getMemoryForGV(I));
Chris Lattnerfe854032006-08-16 01:24:12 +0000993 } else {
994 // External variable reference. Try to use the dynamic loader to
995 // get a pointer to it.
996 if (void *SymAddr =
Daniel Dunbarfbee5792009-07-21 08:54:24 +0000997 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Chris Lattnerfe854032006-08-16 01:24:12 +0000998 addGlobalMapping(I, SymAddr);
999 else {
Torok Edwin31e24662009-07-07 17:32:34 +00001000 llvm_report_error("Could not resolve external global address: "
1001 +I->getName());
Chris Lattnerfe854032006-08-16 01:24:12 +00001002 }
1003 }
1004 }
1005
1006 // If there are multiple modules, map the non-canonical globals to their
1007 // canonical location.
1008 if (!NonCanonicalGlobals.empty()) {
1009 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1010 const GlobalValue *GV = NonCanonicalGlobals[i];
1011 const GlobalValue *CGV =
1012 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1013 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1014 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesc8ed9022008-10-14 10:04:52 +00001015 addGlobalMapping(GV, Ptr);
Chris Lattnerfe854032006-08-16 01:24:12 +00001016 }
1017 }
1018
Reid Spencera54b7cb2007-01-12 07:05:14 +00001019 // Now that all of the globals are set up in memory, loop through them all
1020 // and initialize their contents.
Chris Lattnerfe854032006-08-16 01:24:12 +00001021 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1022 I != E; ++I) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001023 if (!I->isDeclaration()) {
Chris Lattnerfe854032006-08-16 01:24:12 +00001024 if (!LinkedGlobalsMap.empty()) {
1025 if (const GlobalValue *GVEntry =
1026 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1027 if (GVEntry != &*I) // Not the canonical variable.
1028 continue;
1029 }
1030 EmitGlobalVariable(I);
1031 }
1032 }
1033 }
Chris Lattner24b0a182003-12-20 02:45:37 +00001034}
1035
1036// EmitGlobalVariable - This method emits the specified global variable to the
1037// address specified in GlobalAddresses, or allocates new memory if it's not
1038// already in the map.
Chris Lattnerc07ed132003-12-20 03:36:47 +00001039void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
Chris Lattner55d86482003-12-31 20:21:04 +00001040 void *GA = getPointerToGlobalIfAvailable(GV);
Chris Lattner23c47242004-02-08 19:33:23 +00001041
Chris Lattner24b0a182003-12-20 02:45:37 +00001042 if (GA == 0) {
1043 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001044 GA = getMemoryForGV(GV);
Chris Lattner55d86482003-12-31 20:21:04 +00001045 addGlobalMapping(GV, GA);
Chris Lattner24b0a182003-12-20 02:45:37 +00001046 }
Nicolas Geoffray46fa1392008-10-25 15:41:43 +00001047
1048 // Don't initialize if it's thread local, let the client do it.
1049 if (!GV->isThreadLocal())
1050 InitializeMemory(GV->getInitializer(), GA);
1051
1052 const Type *ElTy = GV->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001053 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Chris Lattner813c8152005-01-08 20:13:19 +00001054 NumInitBytes += (unsigned)GVSize;
Chris Lattner24b0a182003-12-20 02:45:37 +00001055 ++NumGlobals;
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001056}