ExecutionEngine.cpp revision df5a37efc997288da520ff4889443e3560d95387
1//===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 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" 16#include "Interpreter/Interpreter.h" 17#include "JIT/JIT.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" 29using namespace llvm; 30 31namespace { 32 Statistic<> NumInitBytes("lli", "Number of bytes of global vars initialized"); 33 Statistic<> NumGlobals ("lli", "Number of global vars initialized"); 34} 35 36ExecutionEngine::ExecutionEngine(ModuleProvider *P) : 37 CurMod(*P->getModule()), MP(P) { 38 assert(P && "ModuleProvider is null?"); 39} 40 41ExecutionEngine::ExecutionEngine(Module *M) : CurMod(*M), MP(0) { 42 assert(M && "Module is null?"); 43} 44 45ExecutionEngine::~ExecutionEngine() { 46 delete MP; 47} 48 49/// getGlobalValueAtAddress - Return the LLVM global value object that starts 50/// at the specified address. 51/// 52const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 53 // If we haven't computed the reverse mapping yet, do so first. 54 if (GlobalAddressReverseMap.empty()) { 55 for (std::map<const GlobalValue*, void *>::iterator I = 56 GlobalAddressMap.begin(), E = GlobalAddressMap.end(); I != E; ++I) 57 GlobalAddressReverseMap.insert(std::make_pair(I->second, I->first)); 58 } 59 60 std::map<void *, const GlobalValue*>::iterator I = 61 GlobalAddressReverseMap.find(Addr); 62 return I != GlobalAddressReverseMap.end() ? I->second : 0; 63} 64 65// CreateArgv - Turn a vector of strings into a nice argv style array of 66// pointers to null terminated strings. 67// 68static void *CreateArgv(ExecutionEngine *EE, 69 const std::vector<std::string> &InputArgv) { 70 unsigned PtrSize = EE->getTargetData().getPointerSize(); 71 char *Result = new char[(InputArgv.size()+1)*PtrSize]; 72 73 DEBUG(std::cerr << "ARGV = " << (void*)Result << "\n"); 74 const Type *SBytePtr = PointerType::get(Type::SByteTy); 75 76 for (unsigned i = 0; i != InputArgv.size(); ++i) { 77 unsigned Size = InputArgv[i].size()+1; 78 char *Dest = new char[Size]; 79 DEBUG(std::cerr << "ARGV[" << i << "] = " << (void*)Dest << "\n"); 80 81 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 82 Dest[Size-1] = 0; 83 84 // Endian safe: Result[i] = (PointerTy)Dest; 85 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Result+i*PtrSize), 86 SBytePtr); 87 } 88 89 // Null terminate it 90 EE->StoreValueToMemory(PTOGV(0), 91 (GenericValue*)(Result+InputArgv.size()*PtrSize), 92 SBytePtr); 93 return Result; 94} 95 96/// runFunctionAsMain - This is a helper function which wraps runFunction to 97/// handle the common task of starting up main with the specified argc, argv, 98/// and envp parameters. 99int ExecutionEngine::runFunctionAsMain(Function *Fn, 100 const std::vector<std::string> &argv, 101 const char * const * envp) { 102 std::vector<GenericValue> GVArgs; 103 GenericValue GVArgc; 104 GVArgc.IntVal = argv.size(); 105 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 106 if (NumArgs) { 107 GVArgs.push_back(GVArgc); // Arg #0 = argc. 108 if (NumArgs > 1) { 109 GVArgs.push_back(PTOGV(CreateArgv(this, argv))); // Arg #1 = argv. 110 assert(((char **)GVTOP(GVArgs[1]))[0] && 111 "argv[0] was null after CreateArgv"); 112 if (NumArgs > 2) { 113 std::vector<std::string> EnvVars; 114 for (unsigned i = 0; envp[i]; ++i) 115 EnvVars.push_back(envp[i]); 116 GVArgs.push_back(PTOGV(CreateArgv(this, EnvVars))); // Arg #2 = envp. 117 } 118 } 119 } 120 return runFunction(Fn, GVArgs).IntVal; 121} 122 123 124 125/// If possible, create a JIT, unless the caller specifically requests an 126/// Interpreter or there's an error. If even an Interpreter cannot be created, 127/// NULL is returned. 128/// 129ExecutionEngine *ExecutionEngine::create(ModuleProvider *MP, 130 bool ForceInterpreter, 131 IntrinsicLowering *IL) { 132 ExecutionEngine *EE = 0; 133 134 // Unless the interpreter was explicitly selected, try making a JIT. 135 if (!ForceInterpreter) 136 EE = JIT::create(MP, IL); 137 138 // If we can't make a JIT, make an interpreter instead. 139 if (EE == 0) { 140 try { 141 Module *M = MP->materializeModule(); 142 try { 143 EE = Interpreter::create(M, IL); 144 } catch (...) { 145 std::cerr << "Error creating the interpreter!\n"; 146 } 147 } catch (std::string& errmsg) { 148 std::cerr << "Error reading the bytecode file: " << errmsg << "\n"; 149 } catch (...) { 150 std::cerr << "Error reading the bytecode file!\n"; 151 } 152 } 153 154 if (EE == 0) 155 delete IL; 156 else 157 // Make sure we can resolve symbols in the program as well. The zero arg 158 // to the function tells DynamicLibrary to load the program, not a library. 159 sys::DynamicLibrary::LoadLibraryPermanently(0); 160 161 return EE; 162} 163 164/// getPointerToGlobal - This returns the address of the specified global 165/// value. This may involve code generation if it's a function. 166/// 167void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 168 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 169 return getPointerToFunction(F); 170 171 assert(GlobalAddressMap[GV] && "Global hasn't had an address allocated yet?"); 172 return GlobalAddressMap[GV]; 173} 174 175/// FIXME: document 176/// 177GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 178 GenericValue Result; 179 if (isa<UndefValue>(C)) return Result; 180 181 if (ConstantExpr *CE = const_cast<ConstantExpr*>(dyn_cast<ConstantExpr>(C))) { 182 switch (CE->getOpcode()) { 183 case Instruction::GetElementPtr: { 184 Result = getConstantValue(CE->getOperand(0)); 185 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end()); 186 uint64_t Offset = 187 TD->getIndexedOffset(CE->getOperand(0)->getType(), Indexes); 188 189 Result.LongVal += Offset; 190 return Result; 191 } 192 case Instruction::Cast: { 193 // We only need to handle a few cases here. Almost all casts will 194 // automatically fold, just the ones involving pointers won't. 195 // 196 Constant *Op = CE->getOperand(0); 197 GenericValue GV = getConstantValue(Op); 198 199 // Handle cast of pointer to pointer... 200 if (Op->getType()->getTypeID() == C->getType()->getTypeID()) 201 return GV; 202 203 // Handle a cast of pointer to any integral type... 204 if (isa<PointerType>(Op->getType()) && C->getType()->isIntegral()) 205 return GV; 206 207 // Handle cast of integer to a pointer... 208 if (isa<PointerType>(C->getType()) && Op->getType()->isIntegral()) 209 switch (Op->getType()->getTypeID()) { 210 case Type::BoolTyID: return PTOGV((void*)(uintptr_t)GV.BoolVal); 211 case Type::SByteTyID: return PTOGV((void*)( intptr_t)GV.SByteVal); 212 case Type::UByteTyID: return PTOGV((void*)(uintptr_t)GV.UByteVal); 213 case Type::ShortTyID: return PTOGV((void*)( intptr_t)GV.ShortVal); 214 case Type::UShortTyID: return PTOGV((void*)(uintptr_t)GV.UShortVal); 215 case Type::IntTyID: return PTOGV((void*)( intptr_t)GV.IntVal); 216 case Type::UIntTyID: return PTOGV((void*)(uintptr_t)GV.UIntVal); 217 case Type::LongTyID: return PTOGV((void*)( intptr_t)GV.LongVal); 218 case Type::ULongTyID: return PTOGV((void*)(uintptr_t)GV.ULongVal); 219 default: assert(0 && "Unknown integral type!"); 220 } 221 break; 222 } 223 224 case Instruction::Add: 225 switch (CE->getOperand(0)->getType()->getTypeID()) { 226 default: assert(0 && "Bad add type!"); abort(); 227 case Type::LongTyID: 228 case Type::ULongTyID: 229 Result.LongVal = getConstantValue(CE->getOperand(0)).LongVal + 230 getConstantValue(CE->getOperand(1)).LongVal; 231 break; 232 case Type::IntTyID: 233 case Type::UIntTyID: 234 Result.IntVal = getConstantValue(CE->getOperand(0)).IntVal + 235 getConstantValue(CE->getOperand(1)).IntVal; 236 break; 237 case Type::ShortTyID: 238 case Type::UShortTyID: 239 Result.ShortVal = getConstantValue(CE->getOperand(0)).ShortVal + 240 getConstantValue(CE->getOperand(1)).ShortVal; 241 break; 242 case Type::SByteTyID: 243 case Type::UByteTyID: 244 Result.SByteVal = getConstantValue(CE->getOperand(0)).SByteVal + 245 getConstantValue(CE->getOperand(1)).SByteVal; 246 break; 247 case Type::FloatTyID: 248 Result.FloatVal = getConstantValue(CE->getOperand(0)).FloatVal + 249 getConstantValue(CE->getOperand(1)).FloatVal; 250 break; 251 case Type::DoubleTyID: 252 Result.DoubleVal = getConstantValue(CE->getOperand(0)).DoubleVal + 253 getConstantValue(CE->getOperand(1)).DoubleVal; 254 break; 255 } 256 return Result; 257 default: 258 break; 259 } 260 std::cerr << "ConstantExpr not handled as global var init: " << *CE << "\n"; 261 abort(); 262 } 263 264 switch (C->getType()->getTypeID()) { 265#define GET_CONST_VAL(TY, CLASS) \ 266 case Type::TY##TyID: Result.TY##Val = cast<CLASS>(C)->getValue(); break 267 GET_CONST_VAL(Bool , ConstantBool); 268 GET_CONST_VAL(UByte , ConstantUInt); 269 GET_CONST_VAL(SByte , ConstantSInt); 270 GET_CONST_VAL(UShort , ConstantUInt); 271 GET_CONST_VAL(Short , ConstantSInt); 272 GET_CONST_VAL(UInt , ConstantUInt); 273 GET_CONST_VAL(Int , ConstantSInt); 274 GET_CONST_VAL(ULong , ConstantUInt); 275 GET_CONST_VAL(Long , ConstantSInt); 276 GET_CONST_VAL(Float , ConstantFP); 277 GET_CONST_VAL(Double , ConstantFP); 278#undef GET_CONST_VAL 279 case Type::PointerTyID: 280 if (isa<ConstantPointerNull>(C)) 281 Result.PointerVal = 0; 282 else if (const Function *F = dyn_cast<Function>(C)) 283 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 284 else if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C)) 285 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 286 else 287 assert(0 && "Unknown constant pointer type!"); 288 break; 289 default: 290 std::cout << "ERROR: Constant unimp for type: " << *C->getType() << "\n"; 291 abort(); 292 } 293 return Result; 294} 295 296/// FIXME: document 297/// 298void ExecutionEngine::StoreValueToMemory(GenericValue Val, GenericValue *Ptr, 299 const Type *Ty) { 300 if (getTargetData().isLittleEndian()) { 301 switch (Ty->getTypeID()) { 302 case Type::BoolTyID: 303 case Type::UByteTyID: 304 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break; 305 case Type::UShortTyID: 306 case Type::ShortTyID: Ptr->Untyped[0] = Val.UShortVal & 255; 307 Ptr->Untyped[1] = (Val.UShortVal >> 8) & 255; 308 break; 309 Store4BytesLittleEndian: 310 case Type::FloatTyID: 311 case Type::UIntTyID: 312 case Type::IntTyID: Ptr->Untyped[0] = Val.UIntVal & 255; 313 Ptr->Untyped[1] = (Val.UIntVal >> 8) & 255; 314 Ptr->Untyped[2] = (Val.UIntVal >> 16) & 255; 315 Ptr->Untyped[3] = (Val.UIntVal >> 24) & 255; 316 break; 317 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4) 318 goto Store4BytesLittleEndian; 319 case Type::DoubleTyID: 320 case Type::ULongTyID: 321 case Type::LongTyID: Ptr->Untyped[0] = Val.ULongVal & 255; 322 Ptr->Untyped[1] = (Val.ULongVal >> 8) & 255; 323 Ptr->Untyped[2] = (Val.ULongVal >> 16) & 255; 324 Ptr->Untyped[3] = (Val.ULongVal >> 24) & 255; 325 Ptr->Untyped[4] = (Val.ULongVal >> 32) & 255; 326 Ptr->Untyped[5] = (Val.ULongVal >> 40) & 255; 327 Ptr->Untyped[6] = (Val.ULongVal >> 48) & 255; 328 Ptr->Untyped[7] = (Val.ULongVal >> 56) & 255; 329 break; 330 default: 331 std::cout << "Cannot store value of type " << *Ty << "!\n"; 332 } 333 } else { 334 switch (Ty->getTypeID()) { 335 case Type::BoolTyID: 336 case Type::UByteTyID: 337 case Type::SByteTyID: Ptr->Untyped[0] = Val.UByteVal; break; 338 case Type::UShortTyID: 339 case Type::ShortTyID: Ptr->Untyped[1] = Val.UShortVal & 255; 340 Ptr->Untyped[0] = (Val.UShortVal >> 8) & 255; 341 break; 342 Store4BytesBigEndian: 343 case Type::FloatTyID: 344 case Type::UIntTyID: 345 case Type::IntTyID: Ptr->Untyped[3] = Val.UIntVal & 255; 346 Ptr->Untyped[2] = (Val.UIntVal >> 8) & 255; 347 Ptr->Untyped[1] = (Val.UIntVal >> 16) & 255; 348 Ptr->Untyped[0] = (Val.UIntVal >> 24) & 255; 349 break; 350 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4) 351 goto Store4BytesBigEndian; 352 case Type::DoubleTyID: 353 case Type::ULongTyID: 354 case Type::LongTyID: Ptr->Untyped[7] = Val.ULongVal & 255; 355 Ptr->Untyped[6] = (Val.ULongVal >> 8) & 255; 356 Ptr->Untyped[5] = (Val.ULongVal >> 16) & 255; 357 Ptr->Untyped[4] = (Val.ULongVal >> 24) & 255; 358 Ptr->Untyped[3] = (Val.ULongVal >> 32) & 255; 359 Ptr->Untyped[2] = (Val.ULongVal >> 40) & 255; 360 Ptr->Untyped[1] = (Val.ULongVal >> 48) & 255; 361 Ptr->Untyped[0] = (Val.ULongVal >> 56) & 255; 362 break; 363 default: 364 std::cout << "Cannot store value of type " << *Ty << "!\n"; 365 } 366 } 367} 368 369/// FIXME: document 370/// 371GenericValue ExecutionEngine::LoadValueFromMemory(GenericValue *Ptr, 372 const Type *Ty) { 373 GenericValue Result; 374 if (getTargetData().isLittleEndian()) { 375 switch (Ty->getTypeID()) { 376 case Type::BoolTyID: 377 case Type::UByteTyID: 378 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break; 379 case Type::UShortTyID: 380 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[0] | 381 ((unsigned)Ptr->Untyped[1] << 8); 382 break; 383 Load4BytesLittleEndian: 384 case Type::FloatTyID: 385 case Type::UIntTyID: 386 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[0] | 387 ((unsigned)Ptr->Untyped[1] << 8) | 388 ((unsigned)Ptr->Untyped[2] << 16) | 389 ((unsigned)Ptr->Untyped[3] << 24); 390 break; 391 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4) 392 goto Load4BytesLittleEndian; 393 case Type::DoubleTyID: 394 case Type::ULongTyID: 395 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[0] | 396 ((uint64_t)Ptr->Untyped[1] << 8) | 397 ((uint64_t)Ptr->Untyped[2] << 16) | 398 ((uint64_t)Ptr->Untyped[3] << 24) | 399 ((uint64_t)Ptr->Untyped[4] << 32) | 400 ((uint64_t)Ptr->Untyped[5] << 40) | 401 ((uint64_t)Ptr->Untyped[6] << 48) | 402 ((uint64_t)Ptr->Untyped[7] << 56); 403 break; 404 default: 405 std::cout << "Cannot load value of type " << *Ty << "!\n"; 406 abort(); 407 } 408 } else { 409 switch (Ty->getTypeID()) { 410 case Type::BoolTyID: 411 case Type::UByteTyID: 412 case Type::SByteTyID: Result.UByteVal = Ptr->Untyped[0]; break; 413 case Type::UShortTyID: 414 case Type::ShortTyID: Result.UShortVal = (unsigned)Ptr->Untyped[1] | 415 ((unsigned)Ptr->Untyped[0] << 8); 416 break; 417 Load4BytesBigEndian: 418 case Type::FloatTyID: 419 case Type::UIntTyID: 420 case Type::IntTyID: Result.UIntVal = (unsigned)Ptr->Untyped[3] | 421 ((unsigned)Ptr->Untyped[2] << 8) | 422 ((unsigned)Ptr->Untyped[1] << 16) | 423 ((unsigned)Ptr->Untyped[0] << 24); 424 break; 425 case Type::PointerTyID: if (getTargetData().getPointerSize() == 4) 426 goto Load4BytesBigEndian; 427 case Type::DoubleTyID: 428 case Type::ULongTyID: 429 case Type::LongTyID: Result.ULongVal = (uint64_t)Ptr->Untyped[7] | 430 ((uint64_t)Ptr->Untyped[6] << 8) | 431 ((uint64_t)Ptr->Untyped[5] << 16) | 432 ((uint64_t)Ptr->Untyped[4] << 24) | 433 ((uint64_t)Ptr->Untyped[3] << 32) | 434 ((uint64_t)Ptr->Untyped[2] << 40) | 435 ((uint64_t)Ptr->Untyped[1] << 48) | 436 ((uint64_t)Ptr->Untyped[0] << 56); 437 break; 438 default: 439 std::cout << "Cannot load value of type " << *Ty << "!\n"; 440 abort(); 441 } 442 } 443 return Result; 444} 445 446// InitializeMemory - Recursive function to apply a Constant value into the 447// specified memory location... 448// 449void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 450 if (isa<UndefValue>(Init)) { 451 // FIXME: THIS SHOULD NOT BE NEEDED. 452 unsigned Size = getTargetData().getTypeSize(Init->getType()); 453 memset(Addr, 0, Size); 454 return; 455 } else if (Init->getType()->isFirstClassType()) { 456 GenericValue Val = getConstantValue(Init); 457 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 458 return; 459 } else if (isa<ConstantAggregateZero>(Init)) { 460 unsigned Size = getTargetData().getTypeSize(Init->getType()); 461 memset(Addr, 0, Size); 462 return; 463 } 464 465 switch (Init->getType()->getTypeID()) { 466 case Type::ArrayTyID: { 467 const ConstantArray *CPA = cast<ConstantArray>(Init); 468 unsigned ElementSize = 469 getTargetData().getTypeSize(cast<ArrayType>(CPA->getType())->getElementType()); 470 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 471 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 472 return; 473 } 474 475 case Type::StructTyID: { 476 const ConstantStruct *CPS = cast<ConstantStruct>(Init); 477 const StructLayout *SL = 478 getTargetData().getStructLayout(cast<StructType>(CPS->getType())); 479 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 480 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->MemberOffsets[i]); 481 return; 482 } 483 484 default: 485 std::cerr << "Bad Type: " << *Init->getType() << "\n"; 486 assert(0 && "Unknown constant type to initialize memory with!"); 487 } 488} 489 490/// EmitGlobals - Emit all of the global variables to memory, storing their 491/// addresses into GlobalAddress. This must make sure to copy the contents of 492/// their initializers into the memory. 493/// 494void ExecutionEngine::emitGlobals() { 495 const TargetData &TD = getTargetData(); 496 497 // Loop over all of the global variables in the program, allocating the memory 498 // to hold them. 499 for (Module::giterator I = getModule().gbegin(), E = getModule().gend(); 500 I != E; ++I) 501 if (!I->isExternal()) { 502 // Get the type of the global... 503 const Type *Ty = I->getType()->getElementType(); 504 505 // Allocate some memory for it! 506 unsigned Size = TD.getTypeSize(Ty); 507 addGlobalMapping(I, new char[Size]); 508 } else { 509 // External variable reference. Try to use the dynamic loader to 510 // get a pointer to it. 511 if (void *SymAddr = sys::DynamicLibrary::SearchForAddressOfSymbol( 512 I->getName().c_str())) 513 addGlobalMapping(I, SymAddr); 514 else { 515 std::cerr << "Could not resolve external global address: " 516 << I->getName() << "\n"; 517 abort(); 518 } 519 } 520 521 // Now that all of the globals are set up in memory, loop through them all and 522 // initialize their contents. 523 for (Module::giterator I = getModule().gbegin(), E = getModule().gend(); 524 I != E; ++I) 525 if (!I->isExternal()) 526 EmitGlobalVariable(I); 527} 528 529// EmitGlobalVariable - This method emits the specified global variable to the 530// address specified in GlobalAddresses, or allocates new memory if it's not 531// already in the map. 532void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 533 void *GA = getPointerToGlobalIfAvailable(GV); 534 DEBUG(std::cerr << "Global '" << GV->getName() << "' -> " << GA << "\n"); 535 536 const Type *ElTy = GV->getType()->getElementType(); 537 unsigned GVSize = getTargetData().getTypeSize(ElTy); 538 if (GA == 0) { 539 // If it's not already specified, allocate memory for the global. 540 GA = new char[GVSize]; 541 addGlobalMapping(GV, GA); 542 } 543 544 InitializeMemory(GV->getInitializer(), GA); 545 NumInitBytes += GVSize; 546 ++NumGlobals; 547} 548