blob: 52718ebb875be96ecef805d71bfc1c21461e27d5 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the common interface used by the various execution engine
11// subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +000016#include "llvm/ExecutionEngine/ExecutionEngine.h"
17
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Module.h"
21#include "llvm/ModuleProvider.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/ExecutionEngine/GenericValue.h"
Chris Lattner5ea5b5c2009-08-23 22:49:13 +000023#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Support/Debug.h"
Edwin Törökf7cbfea2009-07-07 17:32:34 +000025#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/Support/MutexGuard.h"
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +000027#include "llvm/Support/ValueHandle.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000028#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/System/DynamicLibrary.h"
Duncan Sands2e6d3422007-12-12 23:03:45 +000030#include "llvm/System/Host.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Target/TargetData.h"
Anton Korobeynikov357a27d2008-02-20 11:08:44 +000032#include <cmath>
33#include <cstring>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034using namespace llvm;
35
36STATISTIC(NumInitBytes, "Number of bytes of global vars initialized");
37STATISTIC(NumGlobals , "Number of global vars initialized");
38
Reid Klecknerfa3585b2009-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 Geoffray0e757e12008-02-13 18:39:37 +000046ExecutionEngine::EERegisterFn ExecutionEngine::ExceptionTableRegister = 0;
47
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
Chris Lattner5c507602007-10-22 02:50:12 +000049ExecutionEngine::ExecutionEngine(ModuleProvider *P) : LazyFunctionCreator(0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 LazyCompilationDisabled = false;
Evan Cheng9b8bc832008-09-24 16:25:55 +000051 GVCompilationDisabled = false;
Evan Cheng5c62a692008-06-17 16:49:02 +000052 SymbolSearchingDisabled = false;
Nate Begeman7b1a8472009-02-18 08:31:02 +000053 DlsymStubsEnabled = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 Modules.push_back(P);
55 assert(P && "ModuleProvider is null?");
56}
57
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058ExecutionEngine::~ExecutionEngine() {
59 clearAllGlobalMappings();
60 for (unsigned i = 0, e = Modules.size(); i != e; ++i)
61 delete Modules[i];
62}
63
Nicolas Geoffray46fa1532008-10-25 15:41:43 +000064char* ExecutionEngine::getMemoryForGV(const GlobalVariable* GV) {
65 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +000066 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Nicolas Geoffray46fa1532008-10-25 15:41:43 +000067 return new char[GVSize];
68}
69
Devang Patel5d0d0d02007-10-15 19:56:32 +000070/// removeModuleProvider - Remove a ModuleProvider from the list of modules.
Nate Begemanb34045e2009-01-23 19:27:28 +000071/// Relases the Module from the ModuleProvider, materializing it in the
72/// process, and returns the materialized Module.
Devang Patel5d0d0d02007-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 Begemanf7113d92008-05-21 16:34:48 +000080 clearGlobalMappingsFromModule(MP->getModule());
Devang Patel5d0d0d02007-10-15 19:56:32 +000081 return MP->releaseModule(ErrInfo);
82 }
83 }
84 return NULL;
85}
86
Nate Begemanb34045e2009-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +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) {
109 if (Function *F = Modules[i]->getModule()->getFunction(FnName))
110 return F;
111 }
112 return 0;
113}
114
115
116/// 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 Chengb83f6972008-09-18 07:54:21 +0000123
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000124 DEBUG(errs() << "JIT: Map \'" << GV->getName()
125 << "\' to [" << Addr << "]\n";);
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin291d66a2009-08-07 19:54:29 +0000132 AssertingVH<const GlobalValue> &V =
133 state.getGlobalAddressReverseMap(locked)[Addr];
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Begemanf7113d92008-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 Yasskin291d66a2009-08-07 19:54:29 +0000154 state.getGlobalAddressMap(locked).erase(&*FI);
155 state.getGlobalAddressReverseMap(locked).erase(&*FI);
Nate Begemanf7113d92008-05-21 16:34:48 +0000156 }
157 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end();
158 GI != GE; ++GI) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000159 state.getGlobalAddressMap(locked).erase(&*GI);
160 state.getGlobalAddressReverseMap(locked).erase(&*GI);
Nate Begemanf7113d92008-05-21 16:34:48 +0000161 }
162}
163
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Lattnerfb3f0f82008-04-04 04:47:41 +0000167void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168 MutexGuard locked(lock);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000169
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000170 std::map<AssertingVH<const GlobalValue>, void *> &Map =
171 state.getGlobalAddressMap(locked);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000172
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 // Deleting from the mapping?
174 if (Addr == 0) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000175 std::map<AssertingVH<const GlobalValue>, void *>::iterator I = Map.find(GV);
Chris Lattnerfb3f0f82008-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 if (!state.getGlobalAddressReverseMap(locked).empty())
Jeffrey Yasskin76efb342009-08-04 23:53:16 +0000185 state.getGlobalAddressReverseMap(locked).erase(OldVal);
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000186 return OldVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 }
188
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000189 void *&CurVal = Map[GV];
190 void *OldVal = CurVal;
191
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin291d66a2009-08-07 19:54:29 +0000198 AssertingVH<const GlobalValue> &V =
199 state.getGlobalAddressReverseMap(locked)[Addr];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 assert((V == 0 || GV == 0) && "GlobalMapping already established!");
201 V = GV;
202 }
Chris Lattnerfb3f0f82008-04-04 04:47:41 +0000203 return OldVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Yasskin291d66a2009-08-07 19:54:29 +0000212 std::map<AssertingVH<const GlobalValue>, void*>::iterator I =
213 state.getGlobalAddressMap(locked).find(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 return I != state.getGlobalAddressMap(locked).end() ? I->second : 0;
215}
216
217/// getGlobalValueAtAddress - Return the LLVM global value object that starts
218/// at the specified address.
219///
220const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
221 MutexGuard locked(lock);
222
223 // If we haven't computed the reverse mapping yet, do so first.
224 if (state.getGlobalAddressReverseMap(locked).empty()) {
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000225 for (std::map<AssertingVH<const GlobalValue>, void *>::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +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));
230 }
231
Jeffrey Yasskin291d66a2009-08-07 19:54:29 +0000232 std::map<void *, AssertingVH<const GlobalValue> >::iterator I =
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 state.getGlobalAddressReverseMap(locked).find(Addr);
234 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
235}
236
237// CreateArgv - Turn a vector of strings into a nice argv style array of
238// pointers to null terminated strings.
239//
Owen Anderson35b47072009-08-13 21:58:54 +0000240static void *CreateArgv(LLVMContext &C, ExecutionEngine *EE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241 const std::vector<std::string> &InputArgv) {
242 unsigned PtrSize = EE->getTargetData()->getPointerSize();
243 char *Result = new char[(InputArgv.size()+1)*PtrSize];
244
Chris Lattner2b40c562009-08-23 06:35:02 +0000245 DEBUG(errs() << "JIT: ARGV = " << (void*)Result << "\n");
Duncan Sandsf2519d62009-10-06 15:40:36 +0000246 const Type *SBytePtr = Type::getInt8PtrTy(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247
248 for (unsigned i = 0; i != InputArgv.size(); ++i) {
249 unsigned Size = InputArgv[i].size()+1;
250 char *Dest = new char[Size];
Chris Lattner2b40c562009-08-23 06:35:02 +0000251 DEBUG(errs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252
253 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
254 Dest[Size-1] = 0;
255
256 // 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
268
269/// runStaticConstructorsDestructors - This method is used to execute all of
Evan Cheng50a58822008-09-30 15:51:21 +0000270/// the static constructors or destructors for a module, depending on the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271/// value of isDtors.
Chris Lattnercd0d9372009-09-23 01:46:04 +0000272void ExecutionEngine::runStaticConstructorsDestructors(Module *module,
273 bool isDtors) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors";
275
276 // Execute global ctors/dtors for each module in the program.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277
Evan Cheng50a58822008-09-30 15:51:21 +0000278 GlobalVariable *GV = module->getNamedGlobal(Name);
279
280 // If this global has internal linkage, or if it has a use, then it must be
281 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If
282 // this is the case, don't execute any of the global ctors, __main will do
283 // it.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000284 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return;
Evan Cheng50a58822008-09-30 15:51:21 +0000285
286 // Should be an array of '{ int, void ()* }' structs. The first value is
287 // the init priority, which we ignore.
288 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
289 if (!InitList) return;
290 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
291 if (ConstantStruct *CS =
292 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
293 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
294
295 Constant *FP = CS->getOperand(1);
296 if (FP->isNullValue())
297 break; // Found a null terminator, exit.
298
299 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
300 if (CE->isCast())
301 FP = CE->getOperand(0);
302 if (Function *F = dyn_cast<Function>(FP)) {
303 // Execute the ctor/dtor function!
304 runFunction(F, std::vector<GenericValue>());
305 }
306 }
307}
308
309/// runStaticConstructorsDestructors - This method is used to execute all of
310/// the static constructors or destructors for a program, depending on the
311/// value of isDtors.
312void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) {
313 // Execute global ctors/dtors for each module in the program.
314 for (unsigned m = 0, e = Modules.size(); m != e; ++m)
315 runStaticConstructorsDestructors(Modules[m]->getModule(), isDtors);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316}
317
Dan Gohmanc7e1ad02008-08-26 01:38:29 +0000318#ifndef NDEBUG
Duncan Sandse0a2b302007-12-14 19:38:31 +0000319/// isTargetNullPtr - Return whether the target pointer stored at Loc is null.
320static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) {
321 unsigned PtrSize = EE->getTargetData()->getPointerSize();
322 for (unsigned i = 0; i < PtrSize; ++i)
323 if (*(i + (uint8_t*)Loc))
324 return false;
325 return true;
326}
Dan Gohmanc7e1ad02008-08-26 01:38:29 +0000327#endif
Duncan Sandse0a2b302007-12-14 19:38:31 +0000328
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329/// runFunctionAsMain - This is a helper function which wraps runFunction to
330/// handle the common task of starting up main with the specified argc, argv,
331/// and envp parameters.
332int ExecutionEngine::runFunctionAsMain(Function *Fn,
333 const std::vector<std::string> &argv,
334 const char * const * envp) {
335 std::vector<GenericValue> GVArgs;
336 GenericValue GVArgc;
337 GVArgc.IntVal = APInt(32, argv.size());
338
339 // Check main() type
340 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
341 const FunctionType *FTy = Fn->getFunctionType();
Christopher Lambbb2f2222007-12-17 01:12:55 +0000342 const Type* PPInt8Ty =
Owen Anderson35b47072009-08-13 21:58:54 +0000343 PointerType::getUnqual(PointerType::getUnqual(
344 Type::getInt8Ty(Fn->getContext())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 switch (NumArgs) {
346 case 3:
347 if (FTy->getParamType(2) != PPInt8Ty) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000348 llvm_report_error("Invalid type for third argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 }
350 // FALLS THROUGH
351 case 2:
352 if (FTy->getParamType(1) != PPInt8Ty) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000353 llvm_report_error("Invalid type for second argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 }
355 // FALLS THROUGH
356 case 1:
Owen Anderson35b47072009-08-13 21:58:54 +0000357 if (FTy->getParamType(0) != Type::getInt32Ty(Fn->getContext())) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000358 llvm_report_error("Invalid type for first argument of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 }
360 // FALLS THROUGH
361 case 0:
Chris Lattner39bc61c2009-02-04 17:48:18 +0000362 if (!isa<IntegerType>(FTy->getReturnType()) &&
Owen Anderson35b47072009-08-13 21:58:54 +0000363 FTy->getReturnType() != Type::getVoidTy(FTy->getContext())) {
Edwin Törökced9ff82009-07-11 13:10:19 +0000364 llvm_report_error("Invalid return type of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 }
366 break;
367 default:
Edwin Törökced9ff82009-07-11 13:10:19 +0000368 llvm_report_error("Invalid number of arguments of main() supplied");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 }
370
371 if (NumArgs) {
372 GVArgs.push_back(GVArgc); // Arg #0 = argc.
373 if (NumArgs > 1) {
Owen Anderson35b47072009-08-13 21:58:54 +0000374 // Arg #1 = argv.
375 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, argv)));
Duncan Sandse0a2b302007-12-14 19:38:31 +0000376 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 "argv[0] was null after CreateArgv");
378 if (NumArgs > 2) {
379 std::vector<std::string> EnvVars;
380 for (unsigned i = 0; envp[i]; ++i)
381 EnvVars.push_back(envp[i]);
Owen Anderson35b47072009-08-13 21:58:54 +0000382 // Arg #2 = envp.
383 GVArgs.push_back(PTOGV(CreateArgv(Fn->getContext(), this, EnvVars)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 }
385 }
386 }
387 return runFunction(Fn, GVArgs).IntVal.getZExtValue();
388}
389
390/// If possible, create a JIT, unless the caller specifically requests an
391/// Interpreter or there's an error. If even an Interpreter cannot be created,
392/// NULL is returned.
393///
394ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
395 bool ForceInterpreter,
Evan Chenga6394fc2008-08-08 08:11:34 +0000396 std::string *ErrorStr,
Jeffrey Yasskin892956a2009-07-08 21:59:57 +0000397 CodeGenOpt::Level OptLevel,
398 bool GVsWithCode) {
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000399 return EngineBuilder(MP)
400 .setEngineKind(ForceInterpreter
401 ? EngineKind::Interpreter
402 : EngineKind::JIT)
403 .setErrorStr(ErrorStr)
404 .setOptLevel(OptLevel)
405 .setAllocateGVsWithCode(GVsWithCode)
406 .create();
407}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000409ExecutionEngine *ExecutionEngine::create(Module *M) {
410 return EngineBuilder(M).create();
411}
412
413/// EngineBuilder - Overloaded constructor that automatically creates an
414/// ExistingModuleProvider for an existing module.
415EngineBuilder::EngineBuilder(Module *m) : MP(new ExistingModuleProvider(m)) {
416 InitEngine();
417}
418
419ExecutionEngine *EngineBuilder::create() {
Nick Lewyckybaa3a032008-03-08 02:49:45 +0000420 // Make sure we can resolve symbols in the program as well. The zero arg
421 // to the function tells DynamicLibrary to load the program, not a library.
422 if (sys::DynamicLibrary::LoadLibraryPermanently(0, ErrorStr))
423 return 0;
424
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000425 // If the user specified a memory manager but didn't specify which engine to
426 // create, we assume they only want the JIT, and we fail if they only want
427 // the interpreter.
428 if (JMM) {
Chris Lattnercd0d9372009-09-23 01:46:04 +0000429 if (WhichEngine & EngineKind::JIT)
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000430 WhichEngine = EngineKind::JIT;
Chris Lattnercd0d9372009-09-23 01:46:04 +0000431 else {
Chris Lattner03344a22009-09-23 02:03:49 +0000432 if (ErrorStr)
433 *ErrorStr = "Cannot create an interpreter with a memory manager.";
Chris Lattnercd0d9372009-09-23 01:46:04 +0000434 return 0;
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000435 }
436 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000438 // Unless the interpreter was explicitly selected or the JIT is not linked,
439 // try making a JIT.
Chris Lattnercd0d9372009-09-23 01:46:04 +0000440 if (WhichEngine & EngineKind::JIT) {
441 if (ExecutionEngine::JITCtor) {
442 ExecutionEngine *EE =
443 ExecutionEngine::JITCtor(MP, ErrorStr, JMM, OptLevel,
444 AllocateGVsWithCode);
445 if (EE) return EE;
Chris Lattnercd0d9372009-09-23 01:46:04 +0000446 }
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000447 }
448
449 // If we can't make a JIT and we didn't request one specifically, try making
450 // an interpreter instead.
Chris Lattnercd0d9372009-09-23 01:46:04 +0000451 if (WhichEngine & EngineKind::Interpreter) {
452 if (ExecutionEngine::InterpCtor)
453 return ExecutionEngine::InterpCtor(MP, ErrorStr);
Chris Lattner03344a22009-09-23 02:03:49 +0000454 if (ErrorStr)
455 *ErrorStr = "Interpreter has not been linked in.";
Chris Lattnercd0d9372009-09-23 01:46:04 +0000456 return 0;
Reid Klecknerfa3585b2009-07-18 00:42:18 +0000457 }
Chris Lattner03344a22009-09-23 02:03:49 +0000458
459 if ((WhichEngine & EngineKind::JIT) && ExecutionEngine::JITCtor == 0) {
460 if (ErrorStr)
461 *ErrorStr = "JIT has not been linked in.";
462 }
Chris Lattnercd0d9372009-09-23 01:46:04 +0000463 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464}
465
466/// getPointerToGlobal - This returns the address of the specified global
467/// value. This may involve code generation if it's a function.
468///
469void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
470 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
471 return getPointerToFunction(F);
472
473 MutexGuard locked(lock);
474 void *p = state.getGlobalAddressMap(locked)[GV];
475 if (p)
476 return p;
477
478 // Global variable might have been added since interpreter started.
479 if (GlobalVariable *GVar =
480 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV)))
481 EmitGlobalVariable(GVar);
482 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000483 llvm_unreachable("Global hasn't had an address allocated yet!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000484 return state.getGlobalAddressMap(locked)[GV];
485}
486
487/// This function converts a Constant* into a GenericValue. The interesting
488/// part is if C is a ConstantExpr.
Reid Spencer10ffdf12007-08-11 15:57:56 +0000489/// @brief Get a GenericValue for a Constant*
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000490GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
491 // If its undefined, return the garbage.
492 if (isa<UndefValue>(C))
493 return GenericValue();
494
495 // If the value is a ConstantExpr
496 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
497 Constant *Op0 = CE->getOperand(0);
498 switch (CE->getOpcode()) {
499 case Instruction::GetElementPtr: {
500 // Compute the index
501 GenericValue Result = getConstantValue(Op0);
502 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
503 uint64_t Offset =
504 TD->getIndexedOffset(Op0->getType(), &Indices[0], Indices.size());
505
506 char* tmp = (char*) Result.PointerVal;
507 Result = PTOGV(tmp + Offset);
508 return Result;
509 }
510 case Instruction::Trunc: {
511 GenericValue GV = getConstantValue(Op0);
512 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
513 GV.IntVal = GV.IntVal.trunc(BitWidth);
514 return GV;
515 }
516 case Instruction::ZExt: {
517 GenericValue GV = getConstantValue(Op0);
518 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
519 GV.IntVal = GV.IntVal.zext(BitWidth);
520 return GV;
521 }
522 case Instruction::SExt: {
523 GenericValue GV = getConstantValue(Op0);
524 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
525 GV.IntVal = GV.IntVal.sext(BitWidth);
526 return GV;
527 }
528 case Instruction::FPTrunc: {
Dale Johannesenc560da62007-09-17 18:44:13 +0000529 // FIXME long double
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 GenericValue GV = getConstantValue(Op0);
531 GV.FloatVal = float(GV.DoubleVal);
532 return GV;
533 }
534 case Instruction::FPExt:{
Dale Johannesenc560da62007-09-17 18:44:13 +0000535 // FIXME long double
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 GenericValue GV = getConstantValue(Op0);
537 GV.DoubleVal = double(GV.FloatVal);
538 return GV;
539 }
540 case Instruction::UIToFP: {
541 GenericValue GV = getConstantValue(Op0);
Chris Lattner82cdc062009-10-05 05:54:46 +0000542 if (CE->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 GV.FloatVal = float(GV.IntVal.roundToDouble());
Chris Lattner82cdc062009-10-05 05:54:46 +0000544 else if (CE->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 GV.DoubleVal = GV.IntVal.roundToDouble();
Chris Lattner82cdc062009-10-05 05:54:46 +0000546 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000547 const uint64_t zero[] = {0, 0};
548 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman8faf8682008-02-29 01:27:13 +0000549 (void)apf.convertFromAPInt(GV.IntVal,
550 false,
551 APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000552 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000553 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 return GV;
555 }
556 case Instruction::SIToFP: {
557 GenericValue GV = getConstantValue(Op0);
Chris Lattner82cdc062009-10-05 05:54:46 +0000558 if (CE->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 GV.FloatVal = float(GV.IntVal.signedRoundToDouble());
Chris Lattner82cdc062009-10-05 05:54:46 +0000560 else if (CE->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 GV.DoubleVal = GV.IntVal.signedRoundToDouble();
Chris Lattner82cdc062009-10-05 05:54:46 +0000562 else if (CE->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000563 const uint64_t zero[] = { 0, 0};
564 APFloat apf = APFloat(APInt(80, 2, zero));
Dan Gohman8faf8682008-02-29 01:27:13 +0000565 (void)apf.convertFromAPInt(GV.IntVal,
566 true,
567 APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000568 GV.IntVal = apf.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000569 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000570 return GV;
571 }
572 case Instruction::FPToUI: // double->APInt conversion handles sign
573 case Instruction::FPToSI: {
574 GenericValue GV = getConstantValue(Op0);
575 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth();
Chris Lattner82cdc062009-10-05 05:54:46 +0000576 if (Op0->getType()->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000577 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth);
Chris Lattner82cdc062009-10-05 05:54:46 +0000578 else if (Op0->getType()->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth);
Chris Lattner82cdc062009-10-05 05:54:46 +0000580 else if (Op0->getType()->isX86_FP80Ty()) {
Dale Johannesenc560da62007-09-17 18:44:13 +0000581 APFloat apf = APFloat(GV.IntVal);
582 uint64_t v;
Dale Johannesen6e547b42008-10-09 23:00:39 +0000583 bool ignored;
Dale Johannesenc560da62007-09-17 18:44:13 +0000584 (void)apf.convertToInteger(&v, BitWidth,
585 CE->getOpcode()==Instruction::FPToSI,
Dale Johannesen6e547b42008-10-09 23:00:39 +0000586 APFloat::rmTowardZero, &ignored);
Dale Johannesenc560da62007-09-17 18:44:13 +0000587 GV.IntVal = v; // endian?
588 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 return GV;
590 }
591 case Instruction::PtrToInt: {
592 GenericValue GV = getConstantValue(Op0);
593 uint32_t PtrWidth = TD->getPointerSizeInBits();
594 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal));
595 return GV;
596 }
597 case Instruction::IntToPtr: {
598 GenericValue GV = getConstantValue(Op0);
599 uint32_t PtrWidth = TD->getPointerSizeInBits();
600 if (PtrWidth != GV.IntVal.getBitWidth())
601 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth);
602 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width");
603 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue()));
604 return GV;
605 }
606 case Instruction::BitCast: {
607 GenericValue GV = getConstantValue(Op0);
608 const Type* DestTy = CE->getType();
609 switch (Op0->getType()->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000610 default: llvm_unreachable("Invalid bitcast operand");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 case Type::IntegerTyID:
612 assert(DestTy->isFloatingPoint() && "invalid bitcast");
Chris Lattner82cdc062009-10-05 05:54:46 +0000613 if (DestTy->isFloatTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614 GV.FloatVal = GV.IntVal.bitsToFloat();
Chris Lattner82cdc062009-10-05 05:54:46 +0000615 else if (DestTy->isDoubleTy())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 GV.DoubleVal = GV.IntVal.bitsToDouble();
617 break;
618 case Type::FloatTyID:
Owen Anderson35b47072009-08-13 21:58:54 +0000619 assert(DestTy == Type::getInt32Ty(DestTy->getContext()) &&
620 "Invalid bitcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 GV.IntVal.floatToBits(GV.FloatVal);
622 break;
623 case Type::DoubleTyID:
Owen Anderson35b47072009-08-13 21:58:54 +0000624 assert(DestTy == Type::getInt64Ty(DestTy->getContext()) &&
625 "Invalid bitcast");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 GV.IntVal.doubleToBits(GV.DoubleVal);
627 break;
628 case Type::PointerTyID:
629 assert(isa<PointerType>(DestTy) && "Invalid bitcast");
630 break; // getConstantValue(Op0) above already converted it
631 }
632 return GV;
633 }
634 case Instruction::Add:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000635 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 case Instruction::Sub:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000637 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638 case Instruction::Mul:
Dan Gohman7ce405e2009-06-04 22:49:04 +0000639 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 case Instruction::UDiv:
641 case Instruction::SDiv:
642 case Instruction::URem:
643 case Instruction::SRem:
644 case Instruction::And:
645 case Instruction::Or:
646 case Instruction::Xor: {
647 GenericValue LHS = getConstantValue(Op0);
648 GenericValue RHS = getConstantValue(CE->getOperand(1));
649 GenericValue GV;
650 switch (CE->getOperand(0)->getType()->getTypeID()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000651 default: llvm_unreachable("Bad add type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 case Type::IntegerTyID:
653 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000654 default: llvm_unreachable("Invalid integer opcode");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break;
656 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break;
657 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break;
658 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break;
659 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break;
660 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break;
661 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break;
662 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break;
663 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break;
664 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break;
665 }
666 break;
667 case Type::FloatTyID:
668 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000669 default: llvm_unreachable("Invalid float opcode");
Dan Gohman7ce405e2009-06-04 22:49:04 +0000670 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000672 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000674 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000675 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break;
676 case Instruction::FDiv:
677 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break;
678 case Instruction::FRem:
679 GV.FloatVal = ::fmodf(LHS.FloatVal,RHS.FloatVal); break;
680 }
681 break;
682 case Type::DoubleTyID:
683 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000684 default: llvm_unreachable("Invalid double opcode");
Dan Gohman7ce405e2009-06-04 22:49:04 +0000685 case Instruction::FAdd:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000687 case Instruction::FSub:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000689 case Instruction::FMul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break;
691 case Instruction::FDiv:
692 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break;
693 case Instruction::FRem:
694 GV.DoubleVal = ::fmod(LHS.DoubleVal,RHS.DoubleVal); break;
695 }
696 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000697 case Type::X86_FP80TyID:
698 case Type::PPC_FP128TyID:
699 case Type::FP128TyID: {
700 APFloat apfLHS = APFloat(LHS.IntVal);
701 switch (CE->getOpcode()) {
Edwin Törökbd448e32009-07-14 16:55:14 +0000702 default: llvm_unreachable("Invalid long double opcode");llvm_unreachable(0);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000703 case Instruction::FAdd:
Dale Johannesenc560da62007-09-17 18:44:13 +0000704 apfLHS.add(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000705 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000706 break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000707 case Instruction::FSub:
Dale Johannesenc560da62007-09-17 18:44:13 +0000708 apfLHS.subtract(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000709 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000710 break;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000711 case Instruction::FMul:
Dale Johannesenc560da62007-09-17 18:44:13 +0000712 apfLHS.multiply(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000713 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000714 break;
715 case Instruction::FDiv:
716 apfLHS.divide(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000717 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000718 break;
719 case Instruction::FRem:
720 apfLHS.mod(APFloat(RHS.IntVal), APFloat::rmNearestTiesToEven);
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000721 GV.IntVal = apfLHS.bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000722 break;
723 }
724 }
725 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 }
727 return GV;
728 }
729 default:
730 break;
731 }
Edwin Törökced9ff82009-07-11 13:10:19 +0000732 std::string msg;
733 raw_string_ostream Msg(msg);
734 Msg << "ConstantExpr not handled: " << *CE;
735 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 }
737
738 GenericValue Result;
739 switch (C->getType()->getTypeID()) {
740 case Type::FloatTyID:
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000741 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 break;
743 case Type::DoubleTyID:
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000744 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000745 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000746 case Type::X86_FP80TyID:
747 case Type::FP128TyID:
748 case Type::PPC_FP128TyID:
Dale Johannesen49cc7ce2008-10-09 18:53:47 +0000749 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt();
Dale Johannesenc560da62007-09-17 18:44:13 +0000750 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 case Type::IntegerTyID:
752 Result.IntVal = cast<ConstantInt>(C)->getValue();
753 break;
754 case Type::PointerTyID:
755 if (isa<ConstantPointerNull>(C))
756 Result.PointerVal = 0;
757 else if (const Function *F = dyn_cast<Function>(C))
758 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
759 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
760 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
761 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000762 llvm_unreachable("Unknown constant pointer type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 break;
764 default:
Edwin Törökced9ff82009-07-11 13:10:19 +0000765 std::string msg;
766 raw_string_ostream Msg(msg);
767 Msg << "ERROR: Constant unimplemented for type: " << *C->getType();
768 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 }
770 return Result;
771}
772
Duncan Sandse0a2b302007-12-14 19:38:31 +0000773/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
774/// with the integer held in IntVal.
775static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst,
776 unsigned StoreBytes) {
777 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!");
778 uint8_t *Src = (uint8_t *)IntVal.getRawData();
779
Chris Lattnerfcaa7f82009-01-22 19:53:00 +0000780 if (sys::isLittleEndianHost())
Duncan Sandse0a2b302007-12-14 19:38:31 +0000781 // Little-endian host - the source is ordered from LSB to MSB. Order the
782 // destination from LSB to MSB: Do a straight copy.
783 memcpy(Dst, Src, StoreBytes);
784 else {
785 // Big-endian host - the source is an array of 64 bit words ordered from
786 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination
787 // from MSB to LSB: Reverse the word order, but not the bytes in a word.
788 while (StoreBytes > sizeof(uint64_t)) {
789 StoreBytes -= sizeof(uint64_t);
790 // May not be aligned so use memcpy.
791 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t));
792 Src += sizeof(uint64_t);
793 }
794
795 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes);
796 }
797}
798
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799/// StoreValueToMemory - Stores the data in Val of type Ty at address Ptr. Ptr
800/// is the address of the memory at which to store Val, cast to GenericValue *.
801/// It is not a pointer to a GenericValue containing the address at which to
802/// store Val.
Evan Chengd0e5e982008-11-04 06:10:31 +0000803void ExecutionEngine::StoreValueToMemory(const GenericValue &Val,
804 GenericValue *Ptr, const Type *Ty) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000805 const unsigned StoreBytes = getTargetData()->getTypeStoreSize(Ty);
806
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 switch (Ty->getTypeID()) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000808 case Type::IntegerTyID:
809 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 case Type::FloatTyID:
812 *((float*)Ptr) = Val.FloatVal;
813 break;
814 case Type::DoubleTyID:
815 *((double*)Ptr) = Val.DoubleVal;
816 break;
Dale Johannesen2f294562009-03-24 18:16:17 +0000817 case Type::X86_FP80TyID:
818 memcpy(Ptr, Val.IntVal.getRawData(), 10);
819 break;
Duncan Sandse0a2b302007-12-14 19:38:31 +0000820 case Type::PointerTyID:
821 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts.
822 if (StoreBytes != sizeof(PointerTy))
823 memset(Ptr, 0, StoreBytes);
824
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 *((PointerTy*)Ptr) = Val.PointerVal;
826 break;
827 default:
Chris Lattnerb0659d42009-08-23 04:52:46 +0000828 errs() << "Cannot store value of type " << *Ty << "!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829 }
Duncan Sandse0a2b302007-12-14 19:38:31 +0000830
Chris Lattnerfcaa7f82009-01-22 19:53:00 +0000831 if (sys::isLittleEndianHost() != getTargetData()->isLittleEndian())
Duncan Sandse0a2b302007-12-14 19:38:31 +0000832 // Host and target are different endian - reverse the stored bytes.
833 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr);
834}
835
836/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
837/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
838static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) {
839 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!");
840 uint8_t *Dst = (uint8_t *)IntVal.getRawData();
841
Chris Lattnerfcaa7f82009-01-22 19:53:00 +0000842 if (sys::isLittleEndianHost())
Duncan Sandse0a2b302007-12-14 19:38:31 +0000843 // Little-endian host - the destination must be ordered from LSB to MSB.
844 // The source is ordered from LSB to MSB: Do a straight copy.
845 memcpy(Dst, Src, LoadBytes);
846 else {
847 // Big-endian - the destination is an array of 64 bit words ordered from
848 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is
849 // ordered from MSB to LSB: Reverse the word order, but not the bytes in
850 // a word.
851 while (LoadBytes > sizeof(uint64_t)) {
852 LoadBytes -= sizeof(uint64_t);
853 // May not be aligned so use memcpy.
854 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t));
855 Dst += sizeof(uint64_t);
856 }
857
858 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes);
859 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860}
861
862/// FIXME: document
863///
Duncan Sandse0a2b302007-12-14 19:38:31 +0000864void ExecutionEngine::LoadValueFromMemory(GenericValue &Result,
Duncan Sandsf06c7a62008-03-10 16:38:37 +0000865 GenericValue *Ptr,
866 const Type *Ty) {
Duncan Sandse0a2b302007-12-14 19:38:31 +0000867 const unsigned LoadBytes = getTargetData()->getTypeStoreSize(Ty);
Duncan Sands7feee8f2007-12-10 17:43:13 +0000868
Duncan Sandse0a2b302007-12-14 19:38:31 +0000869 switch (Ty->getTypeID()) {
870 case Type::IntegerTyID:
871 // An APInt with all words initially zero.
872 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0);
873 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes);
874 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 case Type::FloatTyID:
876 Result.FloatVal = *((float*)Ptr);
877 break;
878 case Type::DoubleTyID:
Duncan Sandse0a2b302007-12-14 19:38:31 +0000879 Result.DoubleVal = *((double*)Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 break;
Duncan Sandse0a2b302007-12-14 19:38:31 +0000881 case Type::PointerTyID:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882 Result.PointerVal = *((PointerTy*)Ptr);
883 break;
Dale Johannesenc560da62007-09-17 18:44:13 +0000884 case Type::X86_FP80TyID: {
885 // This is endian dependent, but it will only work on x86 anyway.
Duncan Sands1d641aa2007-12-15 17:37:40 +0000886 // FIXME: Will not trap if loading a signaling NaN.
Dale Johannesen2f294562009-03-24 18:16:17 +0000887 uint64_t y[2];
888 memcpy(y, Ptr, 10);
Duncan Sands8d00dd02007-11-28 10:36:19 +0000889 Result.IntVal = APInt(80, 2, y);
Dale Johannesenc560da62007-09-17 18:44:13 +0000890 break;
891 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000892 default:
Edwin Törökced9ff82009-07-11 13:10:19 +0000893 std::string msg;
894 raw_string_ostream Msg(msg);
895 Msg << "Cannot load value of type " << *Ty << "!";
896 llvm_report_error(Msg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 }
898}
899
900// InitializeMemory - Recursive function to apply a Constant value into the
901// specified memory location...
902//
903void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
Chris Lattner2b40c562009-08-23 06:35:02 +0000904 DEBUG(errs() << "JIT: Initializing " << Addr << " ");
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000905 DEBUG(Init->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 if (isa<UndefValue>(Init)) {
907 return;
908 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) {
909 unsigned ElementSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000910 getTargetData()->getTypeAllocSize(CP->getType()->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
912 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
913 return;
Chris Lattnerbfd482d2008-02-15 00:57:28 +0000914 } else if (isa<ConstantAggregateZero>(Init)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000915 memset(Addr, 0, (size_t)getTargetData()->getTypeAllocSize(Init->getType()));
Chris Lattnerbfd482d2008-02-15 00:57:28 +0000916 return;
Dan Gohman61dbdbd2008-05-20 03:20:09 +0000917 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) {
918 unsigned ElementSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000919 getTargetData()->getTypeAllocSize(CPA->getType()->getElementType());
Dan Gohman61dbdbd2008-05-20 03:20:09 +0000920 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
921 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
922 return;
923 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) {
924 const StructLayout *SL =
925 getTargetData()->getStructLayout(cast<StructType>(CPS->getType()));
926 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
927 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i));
928 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 } else if (Init->getType()->isFirstClassType()) {
930 GenericValue Val = getConstantValue(Init);
931 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
932 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000933 }
934
Chris Lattnerb0659d42009-08-23 04:52:46 +0000935 errs() << "Bad Type: " << *Init->getType() << "\n";
Edwin Törökbd448e32009-07-14 16:55:14 +0000936 llvm_unreachable("Unknown constant type to initialize memory with!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937}
938
939/// EmitGlobals - Emit all of the global variables to memory, storing their
940/// addresses into GlobalAddress. This must make sure to copy the contents of
941/// their initializers into the memory.
942///
943void ExecutionEngine::emitGlobals() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944
945 // Loop over all of the global variables in the program, allocating the memory
946 // to hold them. If there is more than one module, do a prepass over globals
947 // to figure out how the different modules should link together.
948 //
949 std::map<std::pair<std::string, const Type*>,
950 const GlobalValue*> LinkedGlobalsMap;
951
952 if (Modules.size() != 1) {
953 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
954 Module &M = *Modules[m]->getModule();
955 for (Module::const_global_iterator I = M.global_begin(),
956 E = M.global_end(); I != E; ++I) {
957 const GlobalValue *GV = I;
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000958 if (GV->hasLocalLinkage() || GV->isDeclaration() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 GV->hasAppendingLinkage() || !GV->hasName())
960 continue;// Ignore external globals and globals with internal linkage.
961
962 const GlobalValue *&GVEntry =
963 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
964
965 // If this is the first time we've seen this global, it is the canonical
966 // version.
967 if (!GVEntry) {
968 GVEntry = GV;
969 continue;
970 }
971
972 // If the existing global is strong, never replace it.
973 if (GVEntry->hasExternalLinkage() ||
974 GVEntry->hasDLLImportLinkage() ||
975 GVEntry->hasDLLExportLinkage())
976 continue;
977
978 // Otherwise, we know it's linkonce/weak, replace it if this is a strong
Dale Johannesen49c44122008-05-14 20:12:51 +0000979 // symbol. FIXME is this right for common?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 if (GV->hasExternalLinkage() || GVEntry->hasExternalWeakLinkage())
981 GVEntry = GV;
982 }
983 }
984 }
985
986 std::vector<const GlobalValue*> NonCanonicalGlobals;
987 for (unsigned m = 0, e = Modules.size(); m != e; ++m) {
988 Module &M = *Modules[m]->getModule();
989 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
990 I != E; ++I) {
991 // In the multi-module case, see what this global maps to.
992 if (!LinkedGlobalsMap.empty()) {
993 if (const GlobalValue *GVEntry =
994 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())]) {
995 // If something else is the canonical global, ignore this one.
996 if (GVEntry != &*I) {
997 NonCanonicalGlobals.push_back(I);
998 continue;
999 }
1000 }
1001 }
1002
1003 if (!I->isDeclaration()) {
Nicolas Geoffray46fa1532008-10-25 15:41:43 +00001004 addGlobalMapping(I, getMemoryForGV(I));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 } else {
1006 // External variable reference. Try to use the dynamic loader to
1007 // get a pointer to it.
1008 if (void *SymAddr =
Daniel Dunbar9198e932009-07-21 08:54:24 +00001009 sys::DynamicLibrary::SearchForAddressOfSymbol(I->getName()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 addGlobalMapping(I, SymAddr);
1011 else {
Edwin Törökf7cbfea2009-07-07 17:32:34 +00001012 llvm_report_error("Could not resolve external global address: "
1013 +I->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 }
1015 }
1016 }
1017
1018 // If there are multiple modules, map the non-canonical globals to their
1019 // canonical location.
1020 if (!NonCanonicalGlobals.empty()) {
1021 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) {
1022 const GlobalValue *GV = NonCanonicalGlobals[i];
1023 const GlobalValue *CGV =
1024 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())];
1025 void *Ptr = getPointerToGlobalIfAvailable(CGV);
1026 assert(Ptr && "Canonical global wasn't codegen'd!");
Nuno Lopesec8dccb2008-10-14 10:04:52 +00001027 addGlobalMapping(GV, Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001028 }
1029 }
1030
1031 // Now that all of the globals are set up in memory, loop through them all
1032 // and initialize their contents.
1033 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1034 I != E; ++I) {
1035 if (!I->isDeclaration()) {
1036 if (!LinkedGlobalsMap.empty()) {
1037 if (const GlobalValue *GVEntry =
1038 LinkedGlobalsMap[std::make_pair(I->getName(), I->getType())])
1039 if (GVEntry != &*I) // Not the canonical variable.
1040 continue;
1041 }
1042 EmitGlobalVariable(I);
1043 }
1044 }
1045 }
1046}
1047
1048// EmitGlobalVariable - This method emits the specified global variable to the
1049// address specified in GlobalAddresses, or allocates new memory if it's not
1050// already in the map.
1051void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
1052 void *GA = getPointerToGlobalIfAvailable(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 if (GA == 0) {
1055 // If it's not already specified, allocate memory for the global.
Nicolas Geoffray46fa1532008-10-25 15:41:43 +00001056 GA = getMemoryForGV(GV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 addGlobalMapping(GV, GA);
1058 }
Nicolas Geoffray46fa1532008-10-25 15:41:43 +00001059
1060 // Don't initialize if it's thread local, let the client do it.
1061 if (!GV->isThreadLocal())
1062 InitializeMemory(GV->getInitializer(), GA);
1063
1064 const Type *ElTy = GV->getType()->getElementType();
Duncan Sandsec4f97d2009-05-09 07:06:46 +00001065 size_t GVSize = (size_t)getTargetData()->getTypeAllocSize(ElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 NumInitBytes += (unsigned)GVSize;
1067 ++NumGlobals;
1068}