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