1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the common interface used by the various execution engine
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
16 #include "Interpreter/Interpreter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/ModuleProvider.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/IntrinsicLowering.h"
24 #include "llvm/ExecutionEngine/ExecutionEngine.h"
25 #include "llvm/ExecutionEngine/GenericValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/System/DynamicLibrary.h"
28 #include "llvm/Target/TargetData.h"
32 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized");
33 Statistic<> NumGlobals ("lli", "Number of global vars initialized");
36 ExecutionEngine::ExecutionEngine(ModuleProvider *P) :
37 CurMod(*P->getModule()), MP(P) {
38 assert(P && "ModuleProvider is null?");
41 ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) {
42 assert(M && "Module is null?");
45 ExecutionEngine::~ExecutionEngine() {
49 /// getGlobalValueAtAddress - Return the LLVM global value object that starts
50 /// at the specified address.
52 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) {
53 MutexGuard locked(lock);
55 // If we haven't computed the reverse mapping yet, do so first.
56 if (state.getGlobalAddressReverseMap(locked).empty()) {
57 for (std::map<const GlobalValue*, void *>::iterator I =
58 state.getGlobalAddressMap(locked).begin(), E = state.getGlobalAddressMap(locked).end(); I != E; ++I)
59 state.getGlobalAddressReverseMap(locked).insert(std::make_pair(I->second, I->first));
62 std::map<void *, const GlobalValue*>::iterator I =
63 state.getGlobalAddressReverseMap(locked).find(Addr);
64 return I != state.getGlobalAddressReverseMap(locked).end() ? I->second : 0;
67 // CreateArgv - Turn a vector of strings into a nice argv style array of
68 // pointers to null terminated strings.
70 static void *CreateArgv(ExecutionEngine *EE,
71 const std::vector<std::string> &InputArgv) {
72 unsigned PtrSize = EE->getTargetData().getPointerSize();
73 char *Result = new char[(InputArgv.size()+1)*PtrSize];
75 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n");
76 const Type *SBytePtr = PointerType::get(Type::SByteTy);
78 for (unsigned i = 0; i != InputArgv.size(); ++i) {
79 unsigned Size = InputArgv[i].size()+1;
80 char *Dest = new char[Size];
81 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n");
83 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest);
86 // Endian safe: Result[i] = (PointerTy)Dest;
87 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize),
92 EE->StoreValueToMemory(PTOGV(0),
93 (GenericValue*)(Result+InputArgv.size()*PtrSize),
98 /// runFunctionAsMain - This is a helper function which wraps runFunction to
99 /// handle the common task of starting up main with the specified argc, argv,
100 /// and envp parameters.
101 int ExecutionEngine::runFunctionAsMain(Function *Fn,
102 const std::vector<std::string> &argv,
103 const char * const * envp) {
104 std::vector<GenericValue> GVArgs;
106 GVArgc.IntVal = argv.size();
107 unsigned NumArgs = Fn->getFunctionType()->getNumParams();
109 GVArgs.push_back(GVArgc); // Arg #0 = argc.
111 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv.
112 assert(((char **)GVTOP(GVArgs[1]))[0] &&
113 "argv[0] was null after CreateArgv");
115 std::vector<std::string> EnvVars;
116 for (unsigned i = 0; envp[i]; ++i)
117 EnvVars.push_back(envp[i]);
118 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp.
122 return runFunction(Fn, GVArgs).IntVal;
127 /// If possible, create a JIT, unless the caller specifically requests an
128 /// Interpreter or there's an error. If even an Interpreter cannot be created,
129 /// NULL is returned.
131 ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP,
132 bool ForceInterpreter,
133 IntrinsicLowering *IL) {
134 ExecutionEngine *EE = 0;
136 // Unless the interpreter was explicitly selected, try making a JIT.
137 if (!ForceInterpreter)
138 EE = JIT::create(MP, IL);
140 // If we can't make a JIT, make an interpreter instead.
143 Module *M = MP->materializeModule();
145 EE = Interpreter::create(M, IL);
147 std::cerr << "Error creating the interpreter!\n";
149 } catch (std::string& errmsg) {
150 std::cerr << "Error reading the bytecode file: " << errmsg << "\n";
152 std::cerr << "Error reading the bytecode file!\n";
159 // Make sure we can resolve symbols in the program as well. The zero arg
160 // to the function tells DynamicLibrary to load the program, not a library.
161 sys::DynamicLibrary::LoadLibraryPermanently(0);
166 /// getPointerToGlobal - This returns the address of the specified global
167 /// value. This may involve code generation if it's a function.
169 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) {
170 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV)))
171 return getPointerToFunction(F);
173 MutexGuard locked(lock);
174 assert(state.getGlobalAddressMap(locked)[GV] && "Global hasn't had an address allocated yet?");
175 return state.getGlobalAddressMap(locked)[GV];
180 GenericValue ExecutionEngine::getConstantValue(const Constant *C) {
182 if (isa<UndefValue>(C)) return Result;
184 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) {
185 switch (CE->getOpcode()) {
186 case Instruction::GetElementPtr: {
187 Result = getConstantValue(CE->getOperand(0));
188 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
190 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes);
192 if (getTargetData().getPointerSize() == 4)
193 Result.IntVal += Offset;
195 Result.LongVal += Offset;
198 case Instruction::Cast: {
199 // We only need to handle a few cases here. Almost all casts will
200 // automatically fold, just the ones involving pointers won't.
202 Constant *Op = CE->getOperand(0);
203 GenericValue GV = getConstantValue(Op);
205 // Handle cast of pointer to pointer...
206 if (Op->getType()->getTypeID() == C->getType()->getTypeID())
209 // Handle a cast of pointer to any integral type...
210 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral())
213 // Handle cast of integer to a pointer...
214 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral())
215 switch (Op->getType()->getTypeID()) {
216 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal);
217 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal);
218 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal);
219 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal);
220 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal);
221 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal);
222 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal);
223 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal);
224 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal);
225 default: assert(0 && "Unknown integral type!");
230 case Instruction::Add:
231 switch (CE->getOperand(0)->getType()->getTypeID()) {
232 default: assert(0 && "Bad add type!"); abort();
234 case Type::ULongTyID:
235 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal +
236 getConstantValue(CE->getOperand(1)).LongVal;
240 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal +
241 getConstantValue(CE->getOperand(1)).IntVal;
243 case Type::ShortTyID:
244 case Type::UShortTyID:
245 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal +
246 getConstantValue(CE->getOperand(1)).ShortVal;
248 case Type::SByteTyID:
249 case Type::UByteTyID:
250 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal +
251 getConstantValue(CE->getOperand(1)).SByteVal;
253 case Type::FloatTyID:
254 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal +
255 getConstantValue(CE->getOperand(1)).FloatVal;
257 case Type::DoubleTyID:
258 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal +
259 getConstantValue(CE->getOperand(1)).DoubleVal;
266 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
270 switch (C->getType()->getTypeID()) {
271 #define GET_CONST_VAL(TY, CTY, CLASS) \
272 case Type::TY##TyID: Result.TY##Val = (CTY)cast<CLASS>(C)->getValue(); break
273 GET_CONST_VAL(Bool , bool , ConstantBool);
274 GET_CONST_VAL(UByte , unsigned char , ConstantUInt);
275 GET_CONST_VAL(SByte , signed char , ConstantSInt);
276 GET_CONST_VAL(UShort , unsigned short, ConstantUInt);
277 GET_CONST_VAL(Short , signed short , ConstantSInt);
278 GET_CONST_VAL(UInt , unsigned int , ConstantUInt);
279 GET_CONST_VAL(Int , signed int , ConstantSInt);
280 GET_CONST_VAL(ULong , uint64_t , ConstantUInt);
281 GET_CONST_VAL(Long , int64_t , ConstantSInt);
282 GET_CONST_VAL(Float , float , ConstantFP);
283 GET_CONST_VAL(Double , double , ConstantFP);
285 case Type::PointerTyID:
286 if (isa<ConstantPointerNull>(C))
287 Result.PointerVal = 0;
288 else if (const Function *F = dyn_cast<Function>(C))
289 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F)));
290 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
291 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV)));
293 assert(0 && "Unknown constant pointer type!");
296 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n";
304 void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr,
306 if (getTargetData().isLittleEndian()) {
307 switch (Ty->getTypeID()) {
309 case Type::UByteTyID:
310 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
311 case Type::UShortTyID:
312 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255;
313 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255;
315 Store4BytesLittleEndian:
316 case Type::FloatTyID:
318 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255;
319 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255;
320 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255;
321 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255;
323 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
324 goto Store4BytesLittleEndian;
325 case Type::DoubleTyID:
326 case Type::ULongTyID:
328 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal );
329 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 8);
330 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 16);
331 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 24);
332 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 32);
333 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 40);
334 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 48);
335 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal >> 56);
338 std::cout << "Cannot store value of type " << *Ty << "!\n";
341 switch (Ty->getTypeID()) {
343 case Type::UByteTyID:
344 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break;
345 case Type::UShortTyID:
346 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255;
347 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255;
349 Store4BytesBigEndian:
350 case Type::FloatTyID:
352 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255;
353 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255;
354 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255;
355 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255;
357 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
358 goto Store4BytesBigEndian;
359 case Type::DoubleTyID:
360 case Type::ULongTyID:
362 Ptr->Untyped[7] = (unsigned char)(Val.ULongVal );
363 Ptr->Untyped[6] = (unsigned char)(Val.ULongVal >> 8);
364 Ptr->Untyped[5] = (unsigned char)(Val.ULongVal >> 16);
365 Ptr->Untyped[4] = (unsigned char)(Val.ULongVal >> 24);
366 Ptr->Untyped[3] = (unsigned char)(Val.ULongVal >> 32);
367 Ptr->Untyped[2] = (unsigned char)(Val.ULongVal >> 40);
368 Ptr->Untyped[1] = (unsigned char)(Val.ULongVal >> 48);
369 Ptr->Untyped[0] = (unsigned char)(Val.ULongVal >> 56);
372 std::cout << "Cannot store value of type " << *Ty << "!\n";
379 GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr,
382 if (getTargetData().isLittleEndian()) {
383 switch (Ty->getTypeID()) {
385 case Type::UByteTyID:
386 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
387 case Type::UShortTyID:
388 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] |
389 ((unsigned)Ptr->Untyped[1] << 8);
391 Load4BytesLittleEndian:
392 case Type::FloatTyID:
394 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] |
395 ((unsigned)Ptr->Untyped[1] << 8) |
396 ((unsigned)Ptr->Untyped[2] << 16) |
397 ((unsigned)Ptr->Untyped[3] << 24);
399 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
400 goto Load4BytesLittleEndian;
401 case Type::DoubleTyID:
402 case Type::ULongTyID:
403 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] |
404 ((uint64_t)Ptr->Untyped[1] << 8) |
405 ((uint64_t)Ptr->Untyped[2] << 16) |
406 ((uint64_t)Ptr->Untyped[3] << 24) |
407 ((uint64_t)Ptr->Untyped[4] << 32) |
408 ((uint64_t)Ptr->Untyped[5] << 40) |
409 ((uint64_t)Ptr->Untyped[6] << 48) |
410 ((uint64_t)Ptr->Untyped[7] << 56);
413 std::cout << "Cannot load value of type " << *Ty << "!\n";
417 switch (Ty->getTypeID()) {
419 case Type::UByteTyID:
420 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break;
421 case Type::UShortTyID:
422 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] |
423 ((unsigned)Ptr->Untyped[0] << 8);
426 case Type::FloatTyID:
428 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] |
429 ((unsigned)Ptr->Untyped[2] << 8) |
430 ((unsigned)Ptr->Untyped[1] << 16) |
431 ((unsigned)Ptr->Untyped[0] << 24);
433 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4)
434 goto Load4BytesBigEndian;
435 case Type::DoubleTyID:
436 case Type::ULongTyID:
437 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] |
438 ((uint64_t)Ptr->Untyped[6] << 8) |
439 ((uint64_t)Ptr->Untyped[5] << 16) |
440 ((uint64_t)Ptr->Untyped[4] << 24) |
441 ((uint64_t)Ptr->Untyped[3] << 32) |
442 ((uint64_t)Ptr->Untyped[2] << 40) |
443 ((uint64_t)Ptr->Untyped[1] << 48) |
444 ((uint64_t)Ptr->Untyped[0] << 56);
447 std::cout << "Cannot load value of type " << *Ty << "!\n";
454 // InitializeMemory - Recursive function to apply a Constant value into the
455 // specified memory location...
457 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) {
458 if (isa<UndefValue>(Init)) {
460 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(Init)) {
461 unsigned ElementSize =
462 getTargetData().getTypeSize(CP->getType()->getElementType());
463 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
464 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize);
466 } else if (Init->getType()->isFirstClassType()) {
467 GenericValue Val = getConstantValue(Init);
468 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType());
470 } else if (isa<ConstantAggregateZero>(Init)) {
471 memset(Addr, 0, (size_t)getTargetData().getTypeSize(Init->getType()));
475 switch (Init->getType()->getTypeID()) {
476 case Type::ArrayTyID: {
477 const ConstantArray *CPA = cast<ConstantArray>(Init);
478 unsigned ElementSize =
479 getTargetData().getTypeSize(CPA->getType()->getElementType());
480 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
481 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize);
485 case Type::StructTyID: {
486 const ConstantStruct *CPS = cast<ConstantStruct>(Init);
487 const StructLayout *SL =
488 getTargetData().getStructLayout(cast<StructType>(CPS->getType()));
489 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
490 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]);
495 std::cerr << "Bad Type: " << *Init->getType() << "\n";
496 assert(0 && "Unknown constant type to initialize memory with!");
500 /// EmitGlobals - Emit all of the global variables to memory, storing their
501 /// addresses into GlobalAddress. This must make sure to copy the contents of
502 /// their initializers into the memory.
504 void ExecutionEngine::emitGlobals() {
505 const TargetData &TD = getTargetData();
507 // Loop over all of the global variables in the program, allocating the memory
509 Module &M = getModule();
510 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
512 if (!I->isExternal()) {
513 // Get the type of the global...
514 const Type *Ty = I->getType()->getElementType();
516 // Allocate some memory for it!
517 unsigned Size = TD.getTypeSize(Ty);
518 addGlobalMapping(I, new char[Size]);
520 // External variable reference. Try to use the dynamic loader to
521 // get a pointer to it.
522 if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol(
523 I->getName().c_str()))
524 addGlobalMapping(I, SymAddr);
526 std::cerr << "Could not resolve external global address: "
527 << I->getName() << "\n";
532 // Now that all of the globals are set up in memory, loop through them all and
533 // initialize their contents.
534 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
536 if (!I->isExternal())
537 EmitGlobalVariable(I);
540 // EmitGlobalVariable - This method emits the specified global variable to the
541 // address specified in GlobalAddresses, or allocates new memory if it's not
542 // already in the map.
543 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) {
544 void *GA = getPointerToGlobalIfAvailable(GV);
545 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n");
547 const Type *ElTy = GV->getType()->getElementType();
548 size_t GVSize = (size_t)getTargetData().getTypeSize(ElTy);
550 // If it's not already specified, allocate memory for the global.
551 GA = new char[GVSize];
552 addGlobalMapping(GV, GA);
555 InitializeMemory(GV->getInitializer(), GA);
556 NumInitBytes += (unsigned)GVSize;