1 //===-- ExecutionEngine.cpp - Common Implementation shared by EEs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // 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 #include "llvm/ExecutionEngine/ExecutionEngine.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/ExecutionEngine/GenericValue.h" 19 #include "llvm/ExecutionEngine/JITMemoryManager.h" 20 #include "llvm/ExecutionEngine/ObjectCache.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DataLayout.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/IR/Operator.h" 26 #include "llvm/IR/ValueHandle.h" 27 #include "llvm/Object/ObjectFile.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/DynamicLibrary.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/Host.h" 32 #include "llvm/Support/MutexGuard.h" 33 #include "llvm/Support/TargetRegistry.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include <cmath> 37 #include <cstring> 38 using namespace llvm; 39 40 #define DEBUG_TYPE "jit" 41 42 STATISTIC(NumInitBytes, "Number of bytes of global vars initialized"); 43 STATISTIC(NumGlobals , "Number of global vars initialized"); 44 45 // Pin the vtable to this file. 46 void ObjectCache::anchor() {} 47 void ObjectBuffer::anchor() {} 48 void ObjectBufferStream::anchor() {} 49 50 ExecutionEngine *(*ExecutionEngine::JITCtor)( 51 Module *M, 52 std::string *ErrorStr, 53 JITMemoryManager *JMM, 54 bool GVsWithCode, 55 TargetMachine *TM) = nullptr; 56 ExecutionEngine *(*ExecutionEngine::MCJITCtor)( 57 Module *M, 58 std::string *ErrorStr, 59 RTDyldMemoryManager *MCJMM, 60 bool GVsWithCode, 61 TargetMachine *TM) = nullptr; 62 ExecutionEngine *(*ExecutionEngine::InterpCtor)(Module *M, 63 std::string *ErrorStr) =nullptr; 64 65 ExecutionEngine::ExecutionEngine(Module *M) 66 : EEState(*this), 67 LazyFunctionCreator(nullptr) { 68 CompilingLazily = false; 69 GVCompilationDisabled = false; 70 SymbolSearchingDisabled = false; 71 72 // IR module verification is enabled by default in debug builds, and disabled 73 // by default in release builds. 74 #ifndef NDEBUG 75 VerifyModules = true; 76 #else 77 VerifyModules = false; 78 #endif 79 80 Modules.push_back(M); 81 assert(M && "Module is null?"); 82 } 83 84 ExecutionEngine::~ExecutionEngine() { 85 clearAllGlobalMappings(); 86 for (unsigned i = 0, e = Modules.size(); i != e; ++i) 87 delete Modules[i]; 88 } 89 90 namespace { 91 /// \brief Helper class which uses a value handler to automatically deletes the 92 /// memory block when the GlobalVariable is destroyed. 93 class GVMemoryBlock : public CallbackVH { 94 GVMemoryBlock(const GlobalVariable *GV) 95 : CallbackVH(const_cast<GlobalVariable*>(GV)) {} 96 97 public: 98 /// \brief Returns the address the GlobalVariable should be written into. The 99 /// GVMemoryBlock object prefixes that. 100 static char *Create(const GlobalVariable *GV, const DataLayout& TD) { 101 Type *ElTy = GV->getType()->getElementType(); 102 size_t GVSize = (size_t)TD.getTypeAllocSize(ElTy); 103 void *RawMemory = ::operator new( 104 DataLayout::RoundUpAlignment(sizeof(GVMemoryBlock), 105 TD.getPreferredAlignment(GV)) 106 + GVSize); 107 new(RawMemory) GVMemoryBlock(GV); 108 return static_cast<char*>(RawMemory) + sizeof(GVMemoryBlock); 109 } 110 111 void deleted() override { 112 // We allocated with operator new and with some extra memory hanging off the 113 // end, so don't just delete this. I'm not sure if this is actually 114 // required. 115 this->~GVMemoryBlock(); 116 ::operator delete(this); 117 } 118 }; 119 } // anonymous namespace 120 121 char *ExecutionEngine::getMemoryForGV(const GlobalVariable *GV) { 122 return GVMemoryBlock::Create(GV, *getDataLayout()); 123 } 124 125 void ExecutionEngine::addObjectFile(std::unique_ptr<object::ObjectFile> O) { 126 llvm_unreachable("ExecutionEngine subclass doesn't implement addObjectFile."); 127 } 128 129 bool ExecutionEngine::removeModule(Module *M) { 130 for(SmallVectorImpl<Module *>::iterator I = Modules.begin(), 131 E = Modules.end(); I != E; ++I) { 132 Module *Found = *I; 133 if (Found == M) { 134 Modules.erase(I); 135 clearGlobalMappingsFromModule(M); 136 return true; 137 } 138 } 139 return false; 140 } 141 142 Function *ExecutionEngine::FindFunctionNamed(const char *FnName) { 143 for (unsigned i = 0, e = Modules.size(); i != e; ++i) { 144 if (Function *F = Modules[i]->getFunction(FnName)) 145 return F; 146 } 147 return nullptr; 148 } 149 150 151 void *ExecutionEngineState::RemoveMapping(const GlobalValue *ToUnmap) { 152 GlobalAddressMapTy::iterator I = GlobalAddressMap.find(ToUnmap); 153 void *OldVal; 154 155 // FIXME: This is silly, we shouldn't end up with a mapping -> 0 in the 156 // GlobalAddressMap. 157 if (I == GlobalAddressMap.end()) 158 OldVal = nullptr; 159 else { 160 OldVal = I->second; 161 GlobalAddressMap.erase(I); 162 } 163 164 GlobalAddressReverseMap.erase(OldVal); 165 return OldVal; 166 } 167 168 void ExecutionEngine::addGlobalMapping(const GlobalValue *GV, void *Addr) { 169 std::lock_guard<std::recursive_mutex> locked(lock); 170 171 DEBUG(dbgs() << "JIT: Map \'" << GV->getName() 172 << "\' to [" << Addr << "]\n";); 173 void *&CurVal = EEState.getGlobalAddressMap()[GV]; 174 assert((!CurVal || !Addr) && "GlobalMapping already established!"); 175 CurVal = Addr; 176 177 // If we are using the reverse mapping, add it too. 178 if (!EEState.getGlobalAddressReverseMap().empty()) { 179 AssertingVH<const GlobalValue> &V = 180 EEState.getGlobalAddressReverseMap()[Addr]; 181 assert((!V || !GV) && "GlobalMapping already established!"); 182 V = GV; 183 } 184 } 185 186 void ExecutionEngine::clearAllGlobalMappings() { 187 std::lock_guard<std::recursive_mutex> locked(lock); 188 189 EEState.getGlobalAddressMap().clear(); 190 EEState.getGlobalAddressReverseMap().clear(); 191 } 192 193 void ExecutionEngine::clearGlobalMappingsFromModule(Module *M) { 194 std::lock_guard<std::recursive_mutex> locked(lock); 195 196 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) 197 EEState.RemoveMapping(FI); 198 for (Module::global_iterator GI = M->global_begin(), GE = M->global_end(); 199 GI != GE; ++GI) 200 EEState.RemoveMapping(GI); 201 } 202 203 void *ExecutionEngine::updateGlobalMapping(const GlobalValue *GV, void *Addr) { 204 std::lock_guard<std::recursive_mutex> locked(lock); 205 206 ExecutionEngineState::GlobalAddressMapTy &Map = 207 EEState.getGlobalAddressMap(); 208 209 // Deleting from the mapping? 210 if (!Addr) 211 return EEState.RemoveMapping(GV); 212 213 void *&CurVal = Map[GV]; 214 void *OldVal = CurVal; 215 216 if (CurVal && !EEState.getGlobalAddressReverseMap().empty()) 217 EEState.getGlobalAddressReverseMap().erase(CurVal); 218 CurVal = Addr; 219 220 // If we are using the reverse mapping, add it too. 221 if (!EEState.getGlobalAddressReverseMap().empty()) { 222 AssertingVH<const GlobalValue> &V = 223 EEState.getGlobalAddressReverseMap()[Addr]; 224 assert((!V || !GV) && "GlobalMapping already established!"); 225 V = GV; 226 } 227 return OldVal; 228 } 229 230 void *ExecutionEngine::getPointerToGlobalIfAvailable(const GlobalValue *GV) { 231 std::lock_guard<std::recursive_mutex> locked(lock); 232 233 ExecutionEngineState::GlobalAddressMapTy::iterator I = 234 EEState.getGlobalAddressMap().find(GV); 235 return I != EEState.getGlobalAddressMap().end() ? I->second : nullptr; 236 } 237 238 const GlobalValue *ExecutionEngine::getGlobalValueAtAddress(void *Addr) { 239 std::lock_guard<std::recursive_mutex> locked(lock); 240 241 // If we haven't computed the reverse mapping yet, do so first. 242 if (EEState.getGlobalAddressReverseMap().empty()) { 243 for (ExecutionEngineState::GlobalAddressMapTy::iterator 244 I = EEState.getGlobalAddressMap().begin(), 245 E = EEState.getGlobalAddressMap().end(); I != E; ++I) 246 EEState.getGlobalAddressReverseMap().insert(std::make_pair( 247 I->second, I->first)); 248 } 249 250 std::map<void *, AssertingVH<const GlobalValue> >::iterator I = 251 EEState.getGlobalAddressReverseMap().find(Addr); 252 return I != EEState.getGlobalAddressReverseMap().end() ? I->second : nullptr; 253 } 254 255 namespace { 256 class ArgvArray { 257 char *Array; 258 std::vector<char*> Values; 259 public: 260 ArgvArray() : Array(nullptr) {} 261 ~ArgvArray() { clear(); } 262 void clear() { 263 delete[] Array; 264 Array = nullptr; 265 for (size_t I = 0, E = Values.size(); I != E; ++I) { 266 delete[] Values[I]; 267 } 268 Values.clear(); 269 } 270 /// Turn a vector of strings into a nice argv style array of pointers to null 271 /// terminated strings. 272 void *reset(LLVMContext &C, ExecutionEngine *EE, 273 const std::vector<std::string> &InputArgv); 274 }; 275 } // anonymous namespace 276 void *ArgvArray::reset(LLVMContext &C, ExecutionEngine *EE, 277 const std::vector<std::string> &InputArgv) { 278 clear(); // Free the old contents. 279 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 280 Array = new char[(InputArgv.size()+1)*PtrSize]; 281 282 DEBUG(dbgs() << "JIT: ARGV = " << (void*)Array << "\n"); 283 Type *SBytePtr = Type::getInt8PtrTy(C); 284 285 for (unsigned i = 0; i != InputArgv.size(); ++i) { 286 unsigned Size = InputArgv[i].size()+1; 287 char *Dest = new char[Size]; 288 Values.push_back(Dest); 289 DEBUG(dbgs() << "JIT: ARGV[" << i << "] = " << (void*)Dest << "\n"); 290 291 std::copy(InputArgv[i].begin(), InputArgv[i].end(), Dest); 292 Dest[Size-1] = 0; 293 294 // Endian safe: Array[i] = (PointerTy)Dest; 295 EE->StoreValueToMemory(PTOGV(Dest), (GenericValue*)(Array+i*PtrSize), 296 SBytePtr); 297 } 298 299 // Null terminate it 300 EE->StoreValueToMemory(PTOGV(nullptr), 301 (GenericValue*)(Array+InputArgv.size()*PtrSize), 302 SBytePtr); 303 return Array; 304 } 305 306 void ExecutionEngine::runStaticConstructorsDestructors(Module *module, 307 bool isDtors) { 308 const char *Name = isDtors ? "llvm.global_dtors" : "llvm.global_ctors"; 309 GlobalVariable *GV = module->getNamedGlobal(Name); 310 311 // If this global has internal linkage, or if it has a use, then it must be 312 // an old-style (llvmgcc3) static ctor with __main linked in and in use. If 313 // this is the case, don't execute any of the global ctors, __main will do 314 // it. 315 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage()) return; 316 317 // Should be an array of '{ i32, void ()* }' structs. The first value is 318 // the init priority, which we ignore. 319 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 320 if (!InitList) 321 return; 322 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 323 ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i)); 324 if (!CS) continue; 325 326 Constant *FP = CS->getOperand(1); 327 if (FP->isNullValue()) 328 continue; // Found a sentinal value, ignore. 329 330 // Strip off constant expression casts. 331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 332 if (CE->isCast()) 333 FP = CE->getOperand(0); 334 335 // Execute the ctor/dtor function! 336 if (Function *F = dyn_cast<Function>(FP)) 337 runFunction(F, std::vector<GenericValue>()); 338 339 // FIXME: It is marginally lame that we just do nothing here if we see an 340 // entry we don't recognize. It might not be unreasonable for the verifier 341 // to not even allow this and just assert here. 342 } 343 } 344 345 void ExecutionEngine::runStaticConstructorsDestructors(bool isDtors) { 346 // Execute global ctors/dtors for each module in the program. 347 for (unsigned i = 0, e = Modules.size(); i != e; ++i) 348 runStaticConstructorsDestructors(Modules[i], isDtors); 349 } 350 351 #ifndef NDEBUG 352 /// isTargetNullPtr - Return whether the target pointer stored at Loc is null. 353 static bool isTargetNullPtr(ExecutionEngine *EE, void *Loc) { 354 unsigned PtrSize = EE->getDataLayout()->getPointerSize(); 355 for (unsigned i = 0; i < PtrSize; ++i) 356 if (*(i + (uint8_t*)Loc)) 357 return false; 358 return true; 359 } 360 #endif 361 362 int ExecutionEngine::runFunctionAsMain(Function *Fn, 363 const std::vector<std::string> &argv, 364 const char * const * envp) { 365 std::vector<GenericValue> GVArgs; 366 GenericValue GVArgc; 367 GVArgc.IntVal = APInt(32, argv.size()); 368 369 // Check main() type 370 unsigned NumArgs = Fn->getFunctionType()->getNumParams(); 371 FunctionType *FTy = Fn->getFunctionType(); 372 Type* PPInt8Ty = Type::getInt8PtrTy(Fn->getContext())->getPointerTo(); 373 374 // Check the argument types. 375 if (NumArgs > 3) 376 report_fatal_error("Invalid number of arguments of main() supplied"); 377 if (NumArgs >= 3 && FTy->getParamType(2) != PPInt8Ty) 378 report_fatal_error("Invalid type for third argument of main() supplied"); 379 if (NumArgs >= 2 && FTy->getParamType(1) != PPInt8Ty) 380 report_fatal_error("Invalid type for second argument of main() supplied"); 381 if (NumArgs >= 1 && !FTy->getParamType(0)->isIntegerTy(32)) 382 report_fatal_error("Invalid type for first argument of main() supplied"); 383 if (!FTy->getReturnType()->isIntegerTy() && 384 !FTy->getReturnType()->isVoidTy()) 385 report_fatal_error("Invalid return type of main() supplied"); 386 387 ArgvArray CArgv; 388 ArgvArray CEnv; 389 if (NumArgs) { 390 GVArgs.push_back(GVArgc); // Arg #0 = argc. 391 if (NumArgs > 1) { 392 // Arg #1 = argv. 393 GVArgs.push_back(PTOGV(CArgv.reset(Fn->getContext(), this, argv))); 394 assert(!isTargetNullPtr(this, GVTOP(GVArgs[1])) && 395 "argv[0] was null after CreateArgv"); 396 if (NumArgs > 2) { 397 std::vector<std::string> EnvVars; 398 for (unsigned i = 0; envp[i]; ++i) 399 EnvVars.push_back(envp[i]); 400 // Arg #2 = envp. 401 GVArgs.push_back(PTOGV(CEnv.reset(Fn->getContext(), this, EnvVars))); 402 } 403 } 404 } 405 406 return runFunction(Fn, GVArgs).IntVal.getZExtValue(); 407 } 408 409 ExecutionEngine *ExecutionEngine::create(Module *M, 410 bool ForceInterpreter, 411 std::string *ErrorStr, 412 CodeGenOpt::Level OptLevel, 413 bool GVsWithCode) { 414 EngineBuilder EB = EngineBuilder(M) 415 .setEngineKind(ForceInterpreter 416 ? EngineKind::Interpreter 417 : EngineKind::JIT) 418 .setErrorStr(ErrorStr) 419 .setOptLevel(OptLevel) 420 .setAllocateGVsWithCode(GVsWithCode); 421 422 return EB.create(); 423 } 424 425 /// createJIT - This is the factory method for creating a JIT for the current 426 /// machine, it does not fall back to the interpreter. This takes ownership 427 /// of the module. 428 ExecutionEngine *ExecutionEngine::createJIT(Module *M, 429 std::string *ErrorStr, 430 JITMemoryManager *JMM, 431 CodeGenOpt::Level OL, 432 bool GVsWithCode, 433 Reloc::Model RM, 434 CodeModel::Model CMM) { 435 if (!ExecutionEngine::JITCtor) { 436 if (ErrorStr) 437 *ErrorStr = "JIT has not been linked in."; 438 return nullptr; 439 } 440 441 // Use the defaults for extra parameters. Users can use EngineBuilder to 442 // set them. 443 EngineBuilder EB(M); 444 EB.setEngineKind(EngineKind::JIT); 445 EB.setErrorStr(ErrorStr); 446 EB.setRelocationModel(RM); 447 EB.setCodeModel(CMM); 448 EB.setAllocateGVsWithCode(GVsWithCode); 449 EB.setOptLevel(OL); 450 EB.setJITMemoryManager(JMM); 451 452 // TODO: permit custom TargetOptions here 453 TargetMachine *TM = EB.selectTarget(); 454 if (!TM || (ErrorStr && ErrorStr->length() > 0)) return nullptr; 455 456 return ExecutionEngine::JITCtor(M, ErrorStr, JMM, GVsWithCode, TM); 457 } 458 459 void EngineBuilder::InitEngine() { 460 WhichEngine = EngineKind::Either; 461 ErrorStr = nullptr; 462 OptLevel = CodeGenOpt::Default; 463 MCJMM = nullptr; 464 JMM = nullptr; 465 Options = TargetOptions(); 466 AllocateGVsWithCode = false; 467 RelocModel = Reloc::Default; 468 CMModel = CodeModel::JITDefault; 469 UseMCJIT = false; 470 471 // IR module verification is enabled by default in debug builds, and disabled 472 // by default in release builds. 473 #ifndef NDEBUG 474 VerifyModules = true; 475 #else 476 VerifyModules = false; 477 #endif 478 } 479 480 ExecutionEngine *EngineBuilder::create(TargetMachine *TM) { 481 std::unique_ptr<TargetMachine> TheTM(TM); // Take ownership. 482 483 // Make sure we can resolve symbols in the program as well. The zero arg 484 // to the function tells DynamicLibrary to load the program, not a library. 485 if (sys::DynamicLibrary::LoadLibraryPermanently(nullptr, ErrorStr)) 486 return nullptr; 487 488 assert(!(JMM && MCJMM)); 489 490 // If the user specified a memory manager but didn't specify which engine to 491 // create, we assume they only want the JIT, and we fail if they only want 492 // the interpreter. 493 if (JMM || MCJMM) { 494 if (WhichEngine & EngineKind::JIT) 495 WhichEngine = EngineKind::JIT; 496 else { 497 if (ErrorStr) 498 *ErrorStr = "Cannot create an interpreter with a memory manager."; 499 return nullptr; 500 } 501 } 502 503 if (MCJMM && ! UseMCJIT) { 504 if (ErrorStr) 505 *ErrorStr = 506 "Cannot create a legacy JIT with a runtime dyld memory " 507 "manager."; 508 return nullptr; 509 } 510 511 // Unless the interpreter was explicitly selected or the JIT is not linked, 512 // try making a JIT. 513 if ((WhichEngine & EngineKind::JIT) && TheTM) { 514 Triple TT(M->getTargetTriple()); 515 if (!TM->getTarget().hasJIT()) { 516 errs() << "WARNING: This target JIT is not designed for the host" 517 << " you are running. If bad things happen, please choose" 518 << " a different -march switch.\n"; 519 } 520 521 ExecutionEngine *EE = nullptr; 522 if (UseMCJIT && ExecutionEngine::MCJITCtor) 523 EE = ExecutionEngine::MCJITCtor(M, ErrorStr, MCJMM ? MCJMM : JMM, 524 AllocateGVsWithCode, TheTM.release()); 525 else if (ExecutionEngine::JITCtor) 526 EE = ExecutionEngine::JITCtor(M, ErrorStr, JMM, 527 AllocateGVsWithCode, TheTM.release()); 528 529 if (EE) { 530 EE->setVerifyModules(VerifyModules); 531 return EE; 532 } 533 } 534 535 // If we can't make a JIT and we didn't request one specifically, try making 536 // an interpreter instead. 537 if (WhichEngine & EngineKind::Interpreter) { 538 if (ExecutionEngine::InterpCtor) 539 return ExecutionEngine::InterpCtor(M, ErrorStr); 540 if (ErrorStr) 541 *ErrorStr = "Interpreter has not been linked in."; 542 return nullptr; 543 } 544 545 if ((WhichEngine & EngineKind::JIT) && !ExecutionEngine::JITCtor && 546 !ExecutionEngine::MCJITCtor) { 547 if (ErrorStr) 548 *ErrorStr = "JIT has not been linked in."; 549 } 550 551 return nullptr; 552 } 553 554 void *ExecutionEngine::getPointerToGlobal(const GlobalValue *GV) { 555 if (Function *F = const_cast<Function*>(dyn_cast<Function>(GV))) 556 return getPointerToFunction(F); 557 558 std::lock_guard<std::recursive_mutex> locked(lock); 559 if (void *P = EEState.getGlobalAddressMap()[GV]) 560 return P; 561 562 // Global variable might have been added since interpreter started. 563 if (GlobalVariable *GVar = 564 const_cast<GlobalVariable *>(dyn_cast<GlobalVariable>(GV))) 565 EmitGlobalVariable(GVar); 566 else 567 llvm_unreachable("Global hasn't had an address allocated yet!"); 568 569 return EEState.getGlobalAddressMap()[GV]; 570 } 571 572 /// \brief Converts a Constant* into a GenericValue, including handling of 573 /// ConstantExpr values. 574 GenericValue ExecutionEngine::getConstantValue(const Constant *C) { 575 // If its undefined, return the garbage. 576 if (isa<UndefValue>(C)) { 577 GenericValue Result; 578 switch (C->getType()->getTypeID()) { 579 default: 580 break; 581 case Type::IntegerTyID: 582 case Type::X86_FP80TyID: 583 case Type::FP128TyID: 584 case Type::PPC_FP128TyID: 585 // Although the value is undefined, we still have to construct an APInt 586 // with the correct bit width. 587 Result.IntVal = APInt(C->getType()->getPrimitiveSizeInBits(), 0); 588 break; 589 case Type::StructTyID: { 590 // if the whole struct is 'undef' just reserve memory for the value. 591 if(StructType *STy = dyn_cast<StructType>(C->getType())) { 592 unsigned int elemNum = STy->getNumElements(); 593 Result.AggregateVal.resize(elemNum); 594 for (unsigned int i = 0; i < elemNum; ++i) { 595 Type *ElemTy = STy->getElementType(i); 596 if (ElemTy->isIntegerTy()) 597 Result.AggregateVal[i].IntVal = 598 APInt(ElemTy->getPrimitiveSizeInBits(), 0); 599 else if (ElemTy->isAggregateType()) { 600 const Constant *ElemUndef = UndefValue::get(ElemTy); 601 Result.AggregateVal[i] = getConstantValue(ElemUndef); 602 } 603 } 604 } 605 } 606 break; 607 case Type::VectorTyID: 608 // if the whole vector is 'undef' just reserve memory for the value. 609 const VectorType* VTy = dyn_cast<VectorType>(C->getType()); 610 const Type *ElemTy = VTy->getElementType(); 611 unsigned int elemNum = VTy->getNumElements(); 612 Result.AggregateVal.resize(elemNum); 613 if (ElemTy->isIntegerTy()) 614 for (unsigned int i = 0; i < elemNum; ++i) 615 Result.AggregateVal[i].IntVal = 616 APInt(ElemTy->getPrimitiveSizeInBits(), 0); 617 break; 618 } 619 return Result; 620 } 621 622 // Otherwise, if the value is a ConstantExpr... 623 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 624 Constant *Op0 = CE->getOperand(0); 625 switch (CE->getOpcode()) { 626 case Instruction::GetElementPtr: { 627 // Compute the index 628 GenericValue Result = getConstantValue(Op0); 629 APInt Offset(DL->getPointerSizeInBits(), 0); 630 cast<GEPOperator>(CE)->accumulateConstantOffset(*DL, Offset); 631 632 char* tmp = (char*) Result.PointerVal; 633 Result = PTOGV(tmp + Offset.getSExtValue()); 634 return Result; 635 } 636 case Instruction::Trunc: { 637 GenericValue GV = getConstantValue(Op0); 638 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 639 GV.IntVal = GV.IntVal.trunc(BitWidth); 640 return GV; 641 } 642 case Instruction::ZExt: { 643 GenericValue GV = getConstantValue(Op0); 644 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 645 GV.IntVal = GV.IntVal.zext(BitWidth); 646 return GV; 647 } 648 case Instruction::SExt: { 649 GenericValue GV = getConstantValue(Op0); 650 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 651 GV.IntVal = GV.IntVal.sext(BitWidth); 652 return GV; 653 } 654 case Instruction::FPTrunc: { 655 // FIXME long double 656 GenericValue GV = getConstantValue(Op0); 657 GV.FloatVal = float(GV.DoubleVal); 658 return GV; 659 } 660 case Instruction::FPExt:{ 661 // FIXME long double 662 GenericValue GV = getConstantValue(Op0); 663 GV.DoubleVal = double(GV.FloatVal); 664 return GV; 665 } 666 case Instruction::UIToFP: { 667 GenericValue GV = getConstantValue(Op0); 668 if (CE->getType()->isFloatTy()) 669 GV.FloatVal = float(GV.IntVal.roundToDouble()); 670 else if (CE->getType()->isDoubleTy()) 671 GV.DoubleVal = GV.IntVal.roundToDouble(); 672 else if (CE->getType()->isX86_FP80Ty()) { 673 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 674 (void)apf.convertFromAPInt(GV.IntVal, 675 false, 676 APFloat::rmNearestTiesToEven); 677 GV.IntVal = apf.bitcastToAPInt(); 678 } 679 return GV; 680 } 681 case Instruction::SIToFP: { 682 GenericValue GV = getConstantValue(Op0); 683 if (CE->getType()->isFloatTy()) 684 GV.FloatVal = float(GV.IntVal.signedRoundToDouble()); 685 else if (CE->getType()->isDoubleTy()) 686 GV.DoubleVal = GV.IntVal.signedRoundToDouble(); 687 else if (CE->getType()->isX86_FP80Ty()) { 688 APFloat apf = APFloat::getZero(APFloat::x87DoubleExtended); 689 (void)apf.convertFromAPInt(GV.IntVal, 690 true, 691 APFloat::rmNearestTiesToEven); 692 GV.IntVal = apf.bitcastToAPInt(); 693 } 694 return GV; 695 } 696 case Instruction::FPToUI: // double->APInt conversion handles sign 697 case Instruction::FPToSI: { 698 GenericValue GV = getConstantValue(Op0); 699 uint32_t BitWidth = cast<IntegerType>(CE->getType())->getBitWidth(); 700 if (Op0->getType()->isFloatTy()) 701 GV.IntVal = APIntOps::RoundFloatToAPInt(GV.FloatVal, BitWidth); 702 else if (Op0->getType()->isDoubleTy()) 703 GV.IntVal = APIntOps::RoundDoubleToAPInt(GV.DoubleVal, BitWidth); 704 else if (Op0->getType()->isX86_FP80Ty()) { 705 APFloat apf = APFloat(APFloat::x87DoubleExtended, GV.IntVal); 706 uint64_t v; 707 bool ignored; 708 (void)apf.convertToInteger(&v, BitWidth, 709 CE->getOpcode()==Instruction::FPToSI, 710 APFloat::rmTowardZero, &ignored); 711 GV.IntVal = v; // endian? 712 } 713 return GV; 714 } 715 case Instruction::PtrToInt: { 716 GenericValue GV = getConstantValue(Op0); 717 uint32_t PtrWidth = DL->getTypeSizeInBits(Op0->getType()); 718 assert(PtrWidth <= 64 && "Bad pointer width"); 719 GV.IntVal = APInt(PtrWidth, uintptr_t(GV.PointerVal)); 720 uint32_t IntWidth = DL->getTypeSizeInBits(CE->getType()); 721 GV.IntVal = GV.IntVal.zextOrTrunc(IntWidth); 722 return GV; 723 } 724 case Instruction::IntToPtr: { 725 GenericValue GV = getConstantValue(Op0); 726 uint32_t PtrWidth = DL->getTypeSizeInBits(CE->getType()); 727 GV.IntVal = GV.IntVal.zextOrTrunc(PtrWidth); 728 assert(GV.IntVal.getBitWidth() <= 64 && "Bad pointer width"); 729 GV.PointerVal = PointerTy(uintptr_t(GV.IntVal.getZExtValue())); 730 return GV; 731 } 732 case Instruction::BitCast: { 733 GenericValue GV = getConstantValue(Op0); 734 Type* DestTy = CE->getType(); 735 switch (Op0->getType()->getTypeID()) { 736 default: llvm_unreachable("Invalid bitcast operand"); 737 case Type::IntegerTyID: 738 assert(DestTy->isFloatingPointTy() && "invalid bitcast"); 739 if (DestTy->isFloatTy()) 740 GV.FloatVal = GV.IntVal.bitsToFloat(); 741 else if (DestTy->isDoubleTy()) 742 GV.DoubleVal = GV.IntVal.bitsToDouble(); 743 break; 744 case Type::FloatTyID: 745 assert(DestTy->isIntegerTy(32) && "Invalid bitcast"); 746 GV.IntVal = APInt::floatToBits(GV.FloatVal); 747 break; 748 case Type::DoubleTyID: 749 assert(DestTy->isIntegerTy(64) && "Invalid bitcast"); 750 GV.IntVal = APInt::doubleToBits(GV.DoubleVal); 751 break; 752 case Type::PointerTyID: 753 assert(DestTy->isPointerTy() && "Invalid bitcast"); 754 break; // getConstantValue(Op0) above already converted it 755 } 756 return GV; 757 } 758 case Instruction::Add: 759 case Instruction::FAdd: 760 case Instruction::Sub: 761 case Instruction::FSub: 762 case Instruction::Mul: 763 case Instruction::FMul: 764 case Instruction::UDiv: 765 case Instruction::SDiv: 766 case Instruction::URem: 767 case Instruction::SRem: 768 case Instruction::And: 769 case Instruction::Or: 770 case Instruction::Xor: { 771 GenericValue LHS = getConstantValue(Op0); 772 GenericValue RHS = getConstantValue(CE->getOperand(1)); 773 GenericValue GV; 774 switch (CE->getOperand(0)->getType()->getTypeID()) { 775 default: llvm_unreachable("Bad add type!"); 776 case Type::IntegerTyID: 777 switch (CE->getOpcode()) { 778 default: llvm_unreachable("Invalid integer opcode"); 779 case Instruction::Add: GV.IntVal = LHS.IntVal + RHS.IntVal; break; 780 case Instruction::Sub: GV.IntVal = LHS.IntVal - RHS.IntVal; break; 781 case Instruction::Mul: GV.IntVal = LHS.IntVal * RHS.IntVal; break; 782 case Instruction::UDiv:GV.IntVal = LHS.IntVal.udiv(RHS.IntVal); break; 783 case Instruction::SDiv:GV.IntVal = LHS.IntVal.sdiv(RHS.IntVal); break; 784 case Instruction::URem:GV.IntVal = LHS.IntVal.urem(RHS.IntVal); break; 785 case Instruction::SRem:GV.IntVal = LHS.IntVal.srem(RHS.IntVal); break; 786 case Instruction::And: GV.IntVal = LHS.IntVal & RHS.IntVal; break; 787 case Instruction::Or: GV.IntVal = LHS.IntVal | RHS.IntVal; break; 788 case Instruction::Xor: GV.IntVal = LHS.IntVal ^ RHS.IntVal; break; 789 } 790 break; 791 case Type::FloatTyID: 792 switch (CE->getOpcode()) { 793 default: llvm_unreachable("Invalid float opcode"); 794 case Instruction::FAdd: 795 GV.FloatVal = LHS.FloatVal + RHS.FloatVal; break; 796 case Instruction::FSub: 797 GV.FloatVal = LHS.FloatVal - RHS.FloatVal; break; 798 case Instruction::FMul: 799 GV.FloatVal = LHS.FloatVal * RHS.FloatVal; break; 800 case Instruction::FDiv: 801 GV.FloatVal = LHS.FloatVal / RHS.FloatVal; break; 802 case Instruction::FRem: 803 GV.FloatVal = std::fmod(LHS.FloatVal,RHS.FloatVal); break; 804 } 805 break; 806 case Type::DoubleTyID: 807 switch (CE->getOpcode()) { 808 default: llvm_unreachable("Invalid double opcode"); 809 case Instruction::FAdd: 810 GV.DoubleVal = LHS.DoubleVal + RHS.DoubleVal; break; 811 case Instruction::FSub: 812 GV.DoubleVal = LHS.DoubleVal - RHS.DoubleVal; break; 813 case Instruction::FMul: 814 GV.DoubleVal = LHS.DoubleVal * RHS.DoubleVal; break; 815 case Instruction::FDiv: 816 GV.DoubleVal = LHS.DoubleVal / RHS.DoubleVal; break; 817 case Instruction::FRem: 818 GV.DoubleVal = std::fmod(LHS.DoubleVal,RHS.DoubleVal); break; 819 } 820 break; 821 case Type::X86_FP80TyID: 822 case Type::PPC_FP128TyID: 823 case Type::FP128TyID: { 824 const fltSemantics &Sem = CE->getOperand(0)->getType()->getFltSemantics(); 825 APFloat apfLHS = APFloat(Sem, LHS.IntVal); 826 switch (CE->getOpcode()) { 827 default: llvm_unreachable("Invalid long double opcode"); 828 case Instruction::FAdd: 829 apfLHS.add(APFloat(Sem, RHS.IntVal), APFloat::rmNearestTiesToEven); 830 GV.IntVal = apfLHS.bitcastToAPInt(); 831 break; 832 case Instruction::FSub: 833 apfLHS.subtract(APFloat(Sem, RHS.IntVal), 834 APFloat::rmNearestTiesToEven); 835 GV.IntVal = apfLHS.bitcastToAPInt(); 836 break; 837 case Instruction::FMul: 838 apfLHS.multiply(APFloat(Sem, RHS.IntVal), 839 APFloat::rmNearestTiesToEven); 840 GV.IntVal = apfLHS.bitcastToAPInt(); 841 break; 842 case Instruction::FDiv: 843 apfLHS.divide(APFloat(Sem, RHS.IntVal), 844 APFloat::rmNearestTiesToEven); 845 GV.IntVal = apfLHS.bitcastToAPInt(); 846 break; 847 case Instruction::FRem: 848 apfLHS.mod(APFloat(Sem, RHS.IntVal), 849 APFloat::rmNearestTiesToEven); 850 GV.IntVal = apfLHS.bitcastToAPInt(); 851 break; 852 } 853 } 854 break; 855 } 856 return GV; 857 } 858 default: 859 break; 860 } 861 862 SmallString<256> Msg; 863 raw_svector_ostream OS(Msg); 864 OS << "ConstantExpr not handled: " << *CE; 865 report_fatal_error(OS.str()); 866 } 867 868 // Otherwise, we have a simple constant. 869 GenericValue Result; 870 switch (C->getType()->getTypeID()) { 871 case Type::FloatTyID: 872 Result.FloatVal = cast<ConstantFP>(C)->getValueAPF().convertToFloat(); 873 break; 874 case Type::DoubleTyID: 875 Result.DoubleVal = cast<ConstantFP>(C)->getValueAPF().convertToDouble(); 876 break; 877 case Type::X86_FP80TyID: 878 case Type::FP128TyID: 879 case Type::PPC_FP128TyID: 880 Result.IntVal = cast <ConstantFP>(C)->getValueAPF().bitcastToAPInt(); 881 break; 882 case Type::IntegerTyID: 883 Result.IntVal = cast<ConstantInt>(C)->getValue(); 884 break; 885 case Type::PointerTyID: 886 if (isa<ConstantPointerNull>(C)) 887 Result.PointerVal = nullptr; 888 else if (const Function *F = dyn_cast<Function>(C)) 889 Result = PTOGV(getPointerToFunctionOrStub(const_cast<Function*>(F))); 890 else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 891 Result = PTOGV(getOrEmitGlobalVariable(const_cast<GlobalVariable*>(GV))); 892 else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) 893 Result = PTOGV(getPointerToBasicBlock(const_cast<BasicBlock*>( 894 BA->getBasicBlock()))); 895 else 896 llvm_unreachable("Unknown constant pointer type!"); 897 break; 898 case Type::VectorTyID: { 899 unsigned elemNum; 900 Type* ElemTy; 901 const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C); 902 const ConstantVector *CV = dyn_cast<ConstantVector>(C); 903 const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(C); 904 905 if (CDV) { 906 elemNum = CDV->getNumElements(); 907 ElemTy = CDV->getElementType(); 908 } else if (CV || CAZ) { 909 VectorType* VTy = dyn_cast<VectorType>(C->getType()); 910 elemNum = VTy->getNumElements(); 911 ElemTy = VTy->getElementType(); 912 } else { 913 llvm_unreachable("Unknown constant vector type!"); 914 } 915 916 Result.AggregateVal.resize(elemNum); 917 // Check if vector holds floats. 918 if(ElemTy->isFloatTy()) { 919 if (CAZ) { 920 GenericValue floatZero; 921 floatZero.FloatVal = 0.f; 922 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 923 floatZero); 924 break; 925 } 926 if(CV) { 927 for (unsigned i = 0; i < elemNum; ++i) 928 if (!isa<UndefValue>(CV->getOperand(i))) 929 Result.AggregateVal[i].FloatVal = cast<ConstantFP>( 930 CV->getOperand(i))->getValueAPF().convertToFloat(); 931 break; 932 } 933 if(CDV) 934 for (unsigned i = 0; i < elemNum; ++i) 935 Result.AggregateVal[i].FloatVal = CDV->getElementAsFloat(i); 936 937 break; 938 } 939 // Check if vector holds doubles. 940 if (ElemTy->isDoubleTy()) { 941 if (CAZ) { 942 GenericValue doubleZero; 943 doubleZero.DoubleVal = 0.0; 944 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 945 doubleZero); 946 break; 947 } 948 if(CV) { 949 for (unsigned i = 0; i < elemNum; ++i) 950 if (!isa<UndefValue>(CV->getOperand(i))) 951 Result.AggregateVal[i].DoubleVal = cast<ConstantFP>( 952 CV->getOperand(i))->getValueAPF().convertToDouble(); 953 break; 954 } 955 if(CDV) 956 for (unsigned i = 0; i < elemNum; ++i) 957 Result.AggregateVal[i].DoubleVal = CDV->getElementAsDouble(i); 958 959 break; 960 } 961 // Check if vector holds integers. 962 if (ElemTy->isIntegerTy()) { 963 if (CAZ) { 964 GenericValue intZero; 965 intZero.IntVal = APInt(ElemTy->getScalarSizeInBits(), 0ull); 966 std::fill(Result.AggregateVal.begin(), Result.AggregateVal.end(), 967 intZero); 968 break; 969 } 970 if(CV) { 971 for (unsigned i = 0; i < elemNum; ++i) 972 if (!isa<UndefValue>(CV->getOperand(i))) 973 Result.AggregateVal[i].IntVal = cast<ConstantInt>( 974 CV->getOperand(i))->getValue(); 975 else { 976 Result.AggregateVal[i].IntVal = 977 APInt(CV->getOperand(i)->getType()->getPrimitiveSizeInBits(), 0); 978 } 979 break; 980 } 981 if(CDV) 982 for (unsigned i = 0; i < elemNum; ++i) 983 Result.AggregateVal[i].IntVal = APInt( 984 CDV->getElementType()->getPrimitiveSizeInBits(), 985 CDV->getElementAsInteger(i)); 986 987 break; 988 } 989 llvm_unreachable("Unknown constant pointer type!"); 990 } 991 break; 992 993 default: 994 SmallString<256> Msg; 995 raw_svector_ostream OS(Msg); 996 OS << "ERROR: Constant unimplemented for type: " << *C->getType(); 997 report_fatal_error(OS.str()); 998 } 999 1000 return Result; 1001 } 1002 1003 /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst 1004 /// with the integer held in IntVal. 1005 static void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, 1006 unsigned StoreBytes) { 1007 assert((IntVal.getBitWidth()+7)/8 >= StoreBytes && "Integer too small!"); 1008 const uint8_t *Src = (const uint8_t *)IntVal.getRawData(); 1009 1010 if (sys::IsLittleEndianHost) { 1011 // Little-endian host - the source is ordered from LSB to MSB. Order the 1012 // destination from LSB to MSB: Do a straight copy. 1013 memcpy(Dst, Src, StoreBytes); 1014 } else { 1015 // Big-endian host - the source is an array of 64 bit words ordered from 1016 // LSW to MSW. Each word is ordered from MSB to LSB. Order the destination 1017 // from MSB to LSB: Reverse the word order, but not the bytes in a word. 1018 while (StoreBytes > sizeof(uint64_t)) { 1019 StoreBytes -= sizeof(uint64_t); 1020 // May not be aligned so use memcpy. 1021 memcpy(Dst + StoreBytes, Src, sizeof(uint64_t)); 1022 Src += sizeof(uint64_t); 1023 } 1024 1025 memcpy(Dst, Src + sizeof(uint64_t) - StoreBytes, StoreBytes); 1026 } 1027 } 1028 1029 void ExecutionEngine::StoreValueToMemory(const GenericValue &Val, 1030 GenericValue *Ptr, Type *Ty) { 1031 const unsigned StoreBytes = getDataLayout()->getTypeStoreSize(Ty); 1032 1033 switch (Ty->getTypeID()) { 1034 default: 1035 dbgs() << "Cannot store value of type " << *Ty << "!\n"; 1036 break; 1037 case Type::IntegerTyID: 1038 StoreIntToMemory(Val.IntVal, (uint8_t*)Ptr, StoreBytes); 1039 break; 1040 case Type::FloatTyID: 1041 *((float*)Ptr) = Val.FloatVal; 1042 break; 1043 case Type::DoubleTyID: 1044 *((double*)Ptr) = Val.DoubleVal; 1045 break; 1046 case Type::X86_FP80TyID: 1047 memcpy(Ptr, Val.IntVal.getRawData(), 10); 1048 break; 1049 case Type::PointerTyID: 1050 // Ensure 64 bit target pointers are fully initialized on 32 bit hosts. 1051 if (StoreBytes != sizeof(PointerTy)) 1052 memset(&(Ptr->PointerVal), 0, StoreBytes); 1053 1054 *((PointerTy*)Ptr) = Val.PointerVal; 1055 break; 1056 case Type::VectorTyID: 1057 for (unsigned i = 0; i < Val.AggregateVal.size(); ++i) { 1058 if (cast<VectorType>(Ty)->getElementType()->isDoubleTy()) 1059 *(((double*)Ptr)+i) = Val.AggregateVal[i].DoubleVal; 1060 if (cast<VectorType>(Ty)->getElementType()->isFloatTy()) 1061 *(((float*)Ptr)+i) = Val.AggregateVal[i].FloatVal; 1062 if (cast<VectorType>(Ty)->getElementType()->isIntegerTy()) { 1063 unsigned numOfBytes =(Val.AggregateVal[i].IntVal.getBitWidth()+7)/8; 1064 StoreIntToMemory(Val.AggregateVal[i].IntVal, 1065 (uint8_t*)Ptr + numOfBytes*i, numOfBytes); 1066 } 1067 } 1068 break; 1069 } 1070 1071 if (sys::IsLittleEndianHost != getDataLayout()->isLittleEndian()) 1072 // Host and target are different endian - reverse the stored bytes. 1073 std::reverse((uint8_t*)Ptr, StoreBytes + (uint8_t*)Ptr); 1074 } 1075 1076 /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting 1077 /// from Src into IntVal, which is assumed to be wide enough and to hold zero. 1078 static void LoadIntFromMemory(APInt &IntVal, uint8_t *Src, unsigned LoadBytes) { 1079 assert((IntVal.getBitWidth()+7)/8 >= LoadBytes && "Integer too small!"); 1080 uint8_t *Dst = reinterpret_cast<uint8_t *>( 1081 const_cast<uint64_t *>(IntVal.getRawData())); 1082 1083 if (sys::IsLittleEndianHost) 1084 // Little-endian host - the destination must be ordered from LSB to MSB. 1085 // The source is ordered from LSB to MSB: Do a straight copy. 1086 memcpy(Dst, Src, LoadBytes); 1087 else { 1088 // Big-endian - the destination is an array of 64 bit words ordered from 1089 // LSW to MSW. Each word must be ordered from MSB to LSB. The source is 1090 // ordered from MSB to LSB: Reverse the word order, but not the bytes in 1091 // a word. 1092 while (LoadBytes > sizeof(uint64_t)) { 1093 LoadBytes -= sizeof(uint64_t); 1094 // May not be aligned so use memcpy. 1095 memcpy(Dst, Src + LoadBytes, sizeof(uint64_t)); 1096 Dst += sizeof(uint64_t); 1097 } 1098 1099 memcpy(Dst + sizeof(uint64_t) - LoadBytes, Src, LoadBytes); 1100 } 1101 } 1102 1103 /// FIXME: document 1104 /// 1105 void ExecutionEngine::LoadValueFromMemory(GenericValue &Result, 1106 GenericValue *Ptr, 1107 Type *Ty) { 1108 const unsigned LoadBytes = getDataLayout()->getTypeStoreSize(Ty); 1109 1110 switch (Ty->getTypeID()) { 1111 case Type::IntegerTyID: 1112 // An APInt with all words initially zero. 1113 Result.IntVal = APInt(cast<IntegerType>(Ty)->getBitWidth(), 0); 1114 LoadIntFromMemory(Result.IntVal, (uint8_t*)Ptr, LoadBytes); 1115 break; 1116 case Type::FloatTyID: 1117 Result.FloatVal = *((float*)Ptr); 1118 break; 1119 case Type::DoubleTyID: 1120 Result.DoubleVal = *((double*)Ptr); 1121 break; 1122 case Type::PointerTyID: 1123 Result.PointerVal = *((PointerTy*)Ptr); 1124 break; 1125 case Type::X86_FP80TyID: { 1126 // This is endian dependent, but it will only work on x86 anyway. 1127 // FIXME: Will not trap if loading a signaling NaN. 1128 uint64_t y[2]; 1129 memcpy(y, Ptr, 10); 1130 Result.IntVal = APInt(80, y); 1131 break; 1132 } 1133 case Type::VectorTyID: { 1134 const VectorType *VT = cast<VectorType>(Ty); 1135 const Type *ElemT = VT->getElementType(); 1136 const unsigned numElems = VT->getNumElements(); 1137 if (ElemT->isFloatTy()) { 1138 Result.AggregateVal.resize(numElems); 1139 for (unsigned i = 0; i < numElems; ++i) 1140 Result.AggregateVal[i].FloatVal = *((float*)Ptr+i); 1141 } 1142 if (ElemT->isDoubleTy()) { 1143 Result.AggregateVal.resize(numElems); 1144 for (unsigned i = 0; i < numElems; ++i) 1145 Result.AggregateVal[i].DoubleVal = *((double*)Ptr+i); 1146 } 1147 if (ElemT->isIntegerTy()) { 1148 GenericValue intZero; 1149 const unsigned elemBitWidth = cast<IntegerType>(ElemT)->getBitWidth(); 1150 intZero.IntVal = APInt(elemBitWidth, 0); 1151 Result.AggregateVal.resize(numElems, intZero); 1152 for (unsigned i = 0; i < numElems; ++i) 1153 LoadIntFromMemory(Result.AggregateVal[i].IntVal, 1154 (uint8_t*)Ptr+((elemBitWidth+7)/8)*i, (elemBitWidth+7)/8); 1155 } 1156 break; 1157 } 1158 default: 1159 SmallString<256> Msg; 1160 raw_svector_ostream OS(Msg); 1161 OS << "Cannot load value of type " << *Ty << "!"; 1162 report_fatal_error(OS.str()); 1163 } 1164 } 1165 1166 void ExecutionEngine::InitializeMemory(const Constant *Init, void *Addr) { 1167 DEBUG(dbgs() << "JIT: Initializing " << Addr << " "); 1168 DEBUG(Init->dump()); 1169 if (isa<UndefValue>(Init)) 1170 return; 1171 1172 if (const ConstantVector *CP = dyn_cast<ConstantVector>(Init)) { 1173 unsigned ElementSize = 1174 getDataLayout()->getTypeAllocSize(CP->getType()->getElementType()); 1175 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 1176 InitializeMemory(CP->getOperand(i), (char*)Addr+i*ElementSize); 1177 return; 1178 } 1179 1180 if (isa<ConstantAggregateZero>(Init)) { 1181 memset(Addr, 0, (size_t)getDataLayout()->getTypeAllocSize(Init->getType())); 1182 return; 1183 } 1184 1185 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(Init)) { 1186 unsigned ElementSize = 1187 getDataLayout()->getTypeAllocSize(CPA->getType()->getElementType()); 1188 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i) 1189 InitializeMemory(CPA->getOperand(i), (char*)Addr+i*ElementSize); 1190 return; 1191 } 1192 1193 if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(Init)) { 1194 const StructLayout *SL = 1195 getDataLayout()->getStructLayout(cast<StructType>(CPS->getType())); 1196 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i) 1197 InitializeMemory(CPS->getOperand(i), (char*)Addr+SL->getElementOffset(i)); 1198 return; 1199 } 1200 1201 if (const ConstantDataSequential *CDS = 1202 dyn_cast<ConstantDataSequential>(Init)) { 1203 // CDS is already laid out in host memory order. 1204 StringRef Data = CDS->getRawDataValues(); 1205 memcpy(Addr, Data.data(), Data.size()); 1206 return; 1207 } 1208 1209 if (Init->getType()->isFirstClassType()) { 1210 GenericValue Val = getConstantValue(Init); 1211 StoreValueToMemory(Val, (GenericValue*)Addr, Init->getType()); 1212 return; 1213 } 1214 1215 DEBUG(dbgs() << "Bad Type: " << *Init->getType() << "\n"); 1216 llvm_unreachable("Unknown constant type to initialize memory with!"); 1217 } 1218 1219 /// EmitGlobals - Emit all of the global variables to memory, storing their 1220 /// addresses into GlobalAddress. This must make sure to copy the contents of 1221 /// their initializers into the memory. 1222 void ExecutionEngine::emitGlobals() { 1223 // Loop over all of the global variables in the program, allocating the memory 1224 // to hold them. If there is more than one module, do a prepass over globals 1225 // to figure out how the different modules should link together. 1226 std::map<std::pair<std::string, Type*>, 1227 const GlobalValue*> LinkedGlobalsMap; 1228 1229 if (Modules.size() != 1) { 1230 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1231 Module &M = *Modules[m]; 1232 for (const auto &GV : M.globals()) { 1233 if (GV.hasLocalLinkage() || GV.isDeclaration() || 1234 GV.hasAppendingLinkage() || !GV.hasName()) 1235 continue;// Ignore external globals and globals with internal linkage. 1236 1237 const GlobalValue *&GVEntry = 1238 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]; 1239 1240 // If this is the first time we've seen this global, it is the canonical 1241 // version. 1242 if (!GVEntry) { 1243 GVEntry = &GV; 1244 continue; 1245 } 1246 1247 // If the existing global is strong, never replace it. 1248 if (GVEntry->hasExternalLinkage()) 1249 continue; 1250 1251 // Otherwise, we know it's linkonce/weak, replace it if this is a strong 1252 // symbol. FIXME is this right for common? 1253 if (GV.hasExternalLinkage() || GVEntry->hasExternalWeakLinkage()) 1254 GVEntry = &GV; 1255 } 1256 } 1257 } 1258 1259 std::vector<const GlobalValue*> NonCanonicalGlobals; 1260 for (unsigned m = 0, e = Modules.size(); m != e; ++m) { 1261 Module &M = *Modules[m]; 1262 for (const auto &GV : M.globals()) { 1263 // In the multi-module case, see what this global maps to. 1264 if (!LinkedGlobalsMap.empty()) { 1265 if (const GlobalValue *GVEntry = 1266 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) { 1267 // If something else is the canonical global, ignore this one. 1268 if (GVEntry != &GV) { 1269 NonCanonicalGlobals.push_back(&GV); 1270 continue; 1271 } 1272 } 1273 } 1274 1275 if (!GV.isDeclaration()) { 1276 addGlobalMapping(&GV, getMemoryForGV(&GV)); 1277 } else { 1278 // External variable reference. Try to use the dynamic loader to 1279 // get a pointer to it. 1280 if (void *SymAddr = 1281 sys::DynamicLibrary::SearchForAddressOfSymbol(GV.getName())) 1282 addGlobalMapping(&GV, SymAddr); 1283 else { 1284 report_fatal_error("Could not resolve external global address: " 1285 +GV.getName()); 1286 } 1287 } 1288 } 1289 1290 // If there are multiple modules, map the non-canonical globals to their 1291 // canonical location. 1292 if (!NonCanonicalGlobals.empty()) { 1293 for (unsigned i = 0, e = NonCanonicalGlobals.size(); i != e; ++i) { 1294 const GlobalValue *GV = NonCanonicalGlobals[i]; 1295 const GlobalValue *CGV = 1296 LinkedGlobalsMap[std::make_pair(GV->getName(), GV->getType())]; 1297 void *Ptr = getPointerToGlobalIfAvailable(CGV); 1298 assert(Ptr && "Canonical global wasn't codegen'd!"); 1299 addGlobalMapping(GV, Ptr); 1300 } 1301 } 1302 1303 // Now that all of the globals are set up in memory, loop through them all 1304 // and initialize their contents. 1305 for (const auto &GV : M.globals()) { 1306 if (!GV.isDeclaration()) { 1307 if (!LinkedGlobalsMap.empty()) { 1308 if (const GlobalValue *GVEntry = 1309 LinkedGlobalsMap[std::make_pair(GV.getName(), GV.getType())]) 1310 if (GVEntry != &GV) // Not the canonical variable. 1311 continue; 1312 } 1313 EmitGlobalVariable(&GV); 1314 } 1315 } 1316 } 1317 } 1318 1319 // EmitGlobalVariable - This method emits the specified global variable to the 1320 // address specified in GlobalAddresses, or allocates new memory if it's not 1321 // already in the map. 1322 void ExecutionEngine::EmitGlobalVariable(const GlobalVariable *GV) { 1323 void *GA = getPointerToGlobalIfAvailable(GV); 1324 1325 if (!GA) { 1326 // If it's not already specified, allocate memory for the global. 1327 GA = getMemoryForGV(GV); 1328 1329 // If we failed to allocate memory for this global, return. 1330 if (!GA) return; 1331 1332 addGlobalMapping(GV, GA); 1333 } 1334 1335 // Don't initialize if it's thread local, let the client do it. 1336 if (!GV->isThreadLocal()) 1337 InitializeMemory(GV->getInitializer(), GA); 1338 1339 Type *ElTy = GV->getType()->getElementType(); 1340 size_t GVSize = (size_t)getDataLayout()->getTypeAllocSize(ElTy); 1341 NumInitBytes += (unsigned)GVSize; 1342 ++NumGlobals; 1343 } 1344 1345 ExecutionEngineState::ExecutionEngineState(ExecutionEngine &EE) 1346 : EE(EE), GlobalAddressMap(this) { 1347 } 1348 1349 std::recursive_mutex * 1350 ExecutionEngineState::AddressMapConfig::getMutex(ExecutionEngineState *EES) { 1351 return &EES->EE.lock; 1352 } 1353 1354 void ExecutionEngineState::AddressMapConfig::onDelete(ExecutionEngineState *EES, 1355 const GlobalValue *Old) { 1356 void *OldVal = EES->GlobalAddressMap.lookup(Old); 1357 EES->GlobalAddressReverseMap.erase(OldVal); 1358 } 1359 1360 void ExecutionEngineState::AddressMapConfig::onRAUW(ExecutionEngineState *, 1361 const GlobalValue *, 1362 const GlobalValue *) { 1363 llvm_unreachable("The ExecutionEngine doesn't know how to handle a" 1364 " RAUW on a value it has a global mapping for."); 1365 } 1366