1 //===- MachineFunction.cpp ------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Collect native machine code information for a function. This allows 10 // target-specific information about the generated code to be stored with each 11 // function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/ConstantFolding.h" 25 #include "llvm/Analysis/EHPersonalities.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineConstantPool.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineModuleInfo.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/PseudoSourceValue.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetInstrInfo.h" 37 #include "llvm/CodeGen/TargetLowering.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/CodeGen/WasmEHFuncInfo.h" 41 #include "llvm/CodeGen/WinEHFuncInfo.h" 42 #include "llvm/Config/llvm-config.h" 43 #include "llvm/IR/Attributes.h" 44 #include "llvm/IR/BasicBlock.h" 45 #include "llvm/IR/Constant.h" 46 #include "llvm/IR/DataLayout.h" 47 #include "llvm/IR/DebugInfoMetadata.h" 48 #include "llvm/IR/DerivedTypes.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalValue.h" 51 #include "llvm/IR/Instruction.h" 52 #include "llvm/IR/Instructions.h" 53 #include "llvm/IR/Metadata.h" 54 #include "llvm/IR/Module.h" 55 #include "llvm/IR/ModuleSlotTracker.h" 56 #include "llvm/IR/Value.h" 57 #include "llvm/MC/MCContext.h" 58 #include "llvm/MC/MCSymbol.h" 59 #include "llvm/MC/SectionKind.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/DOTGraphTraits.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/GraphWriter.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetMachine.h" 69 #include <algorithm> 70 #include <cassert> 71 #include <cstddef> 72 #include <cstdint> 73 #include <iterator> 74 #include <string> 75 #include <type_traits> 76 #include <utility> 77 #include <vector> 78 79 using namespace llvm; 80 81 #define DEBUG_TYPE "codegen" 82 83 static cl::opt<unsigned> AlignAllFunctions( 84 "align-all-functions", 85 cl::desc("Force the alignment of all functions in log2 format (e.g. 4 " 86 "means align on 16B boundaries)."), 87 cl::init(0), cl::Hidden); 88 89 static const char *getPropertyName(MachineFunctionProperties::Property Prop) { 90 using P = MachineFunctionProperties::Property; 91 92 // clang-format off 93 switch(Prop) { 94 case P::FailedISel: return "FailedISel"; 95 case P::IsSSA: return "IsSSA"; 96 case P::Legalized: return "Legalized"; 97 case P::NoPHIs: return "NoPHIs"; 98 case P::NoVRegs: return "NoVRegs"; 99 case P::RegBankSelected: return "RegBankSelected"; 100 case P::Selected: return "Selected"; 101 case P::TracksLiveness: return "TracksLiveness"; 102 case P::TiedOpsRewritten: return "TiedOpsRewritten"; 103 case P::FailsVerification: return "FailsVerification"; 104 case P::TracksDebugUserValues: return "TracksDebugUserValues"; 105 } 106 // clang-format on 107 llvm_unreachable("Invalid machine function property"); 108 } 109 110 // Pin the vtable to this file. 111 void MachineFunction::Delegate::anchor() {} 112 113 void MachineFunctionProperties::print(raw_ostream &OS) const { 114 const char *Separator = ""; 115 for (BitVector::size_type I = 0; I < Properties.size(); ++I) { 116 if (!Properties[I]) 117 continue; 118 OS << Separator << getPropertyName(static_cast<Property>(I)); 119 Separator = ", "; 120 } 121 } 122 123 //===----------------------------------------------------------------------===// 124 // MachineFunction implementation 125 //===----------------------------------------------------------------------===// 126 127 // Out-of-line virtual method. 128 MachineFunctionInfo::~MachineFunctionInfo() = default; 129 130 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 131 MBB->getParent()->deleteMachineBasicBlock(MBB); 132 } 133 134 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 135 const Function &F) { 136 if (auto MA = F.getFnStackAlign()) 137 return MA->value(); 138 return STI->getFrameLowering()->getStackAlign().value(); 139 } 140 141 MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target, 142 const TargetSubtargetInfo &STI, 143 unsigned FunctionNum, MachineModuleInfo &mmi) 144 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) { 145 FunctionNumber = FunctionNum; 146 init(); 147 } 148 149 void MachineFunction::handleInsertion(MachineInstr &MI) { 150 if (TheDelegate) 151 TheDelegate->MF_HandleInsertion(MI); 152 } 153 154 void MachineFunction::handleRemoval(MachineInstr &MI) { 155 if (TheDelegate) 156 TheDelegate->MF_HandleRemoval(MI); 157 } 158 159 void MachineFunction::init() { 160 // Assume the function starts in SSA form with correct liveness. 161 Properties.set(MachineFunctionProperties::Property::IsSSA); 162 Properties.set(MachineFunctionProperties::Property::TracksLiveness); 163 if (STI->getRegisterInfo()) 164 RegInfo = new (Allocator) MachineRegisterInfo(this); 165 else 166 RegInfo = nullptr; 167 168 MFInfo = nullptr; 169 // We can realign the stack if the target supports it and the user hasn't 170 // explicitly asked us not to. 171 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && 172 !F.hasFnAttribute("no-realign-stack"); 173 FrameInfo = new (Allocator) MachineFrameInfo( 174 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP, 175 /*ForcedRealign=*/CanRealignSP && 176 F.hasFnAttribute(Attribute::StackAlignment)); 177 178 if (F.hasFnAttribute(Attribute::StackAlignment)) 179 FrameInfo->ensureMaxAlignment(*F.getFnStackAlign()); 180 181 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 182 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 183 184 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F. 185 // FIXME: Use Function::hasOptSize(). 186 if (!F.hasFnAttribute(Attribute::OptimizeForSize)) 187 Alignment = std::max(Alignment, 188 STI->getTargetLowering()->getPrefFunctionAlignment()); 189 190 if (AlignAllFunctions) 191 Alignment = Align(1ULL << AlignAllFunctions); 192 193 JumpTableInfo = nullptr; 194 195 if (isFuncletEHPersonality(classifyEHPersonality( 196 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 197 WinEHInfo = new (Allocator) WinEHFuncInfo(); 198 } 199 200 if (isScopedEHPersonality(classifyEHPersonality( 201 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 202 WasmEHInfo = new (Allocator) WasmEHFuncInfo(); 203 } 204 205 assert(Target.isCompatibleDataLayout(getDataLayout()) && 206 "Can't create a MachineFunction using a Module with a " 207 "Target-incompatible DataLayout attached\n"); 208 209 PSVManager = 210 std::make_unique<PseudoSourceValueManager>(*(getSubtarget(). 211 getInstrInfo())); 212 } 213 214 MachineFunction::~MachineFunction() { 215 clear(); 216 } 217 218 void MachineFunction::clear() { 219 Properties.reset(); 220 // Don't call destructors on MachineInstr and MachineOperand. All of their 221 // memory comes from the BumpPtrAllocator which is about to be purged. 222 // 223 // Do call MachineBasicBlock destructors, it contains std::vectors. 224 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 225 I->Insts.clearAndLeakNodesUnsafely(); 226 MBBNumbering.clear(); 227 228 InstructionRecycler.clear(Allocator); 229 OperandRecycler.clear(Allocator); 230 BasicBlockRecycler.clear(Allocator); 231 CodeViewAnnotations.clear(); 232 VariableDbgInfos.clear(); 233 if (RegInfo) { 234 RegInfo->~MachineRegisterInfo(); 235 Allocator.Deallocate(RegInfo); 236 } 237 if (MFInfo) { 238 MFInfo->~MachineFunctionInfo(); 239 Allocator.Deallocate(MFInfo); 240 } 241 242 FrameInfo->~MachineFrameInfo(); 243 Allocator.Deallocate(FrameInfo); 244 245 ConstantPool->~MachineConstantPool(); 246 Allocator.Deallocate(ConstantPool); 247 248 if (JumpTableInfo) { 249 JumpTableInfo->~MachineJumpTableInfo(); 250 Allocator.Deallocate(JumpTableInfo); 251 } 252 253 if (WinEHInfo) { 254 WinEHInfo->~WinEHFuncInfo(); 255 Allocator.Deallocate(WinEHInfo); 256 } 257 258 if (WasmEHInfo) { 259 WasmEHInfo->~WasmEHFuncInfo(); 260 Allocator.Deallocate(WasmEHInfo); 261 } 262 } 263 264 const DataLayout &MachineFunction::getDataLayout() const { 265 return F.getParent()->getDataLayout(); 266 } 267 268 /// Get the JumpTableInfo for this function. 269 /// If it does not already exist, allocate one. 270 MachineJumpTableInfo *MachineFunction:: 271 getOrCreateJumpTableInfo(unsigned EntryKind) { 272 if (JumpTableInfo) return JumpTableInfo; 273 274 JumpTableInfo = new (Allocator) 275 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 276 return JumpTableInfo; 277 } 278 279 DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const { 280 return F.getDenormalMode(FPType); 281 } 282 283 /// Should we be emitting segmented stack stuff for the function 284 bool MachineFunction::shouldSplitStack() const { 285 return getFunction().hasFnAttribute("split-stack"); 286 } 287 288 LLVM_NODISCARD unsigned 289 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) { 290 FrameInstructions.push_back(Inst); 291 return FrameInstructions.size() - 1; 292 } 293 294 /// This discards all of the MachineBasicBlock numbers and recomputes them. 295 /// This guarantees that the MBB numbers are sequential, dense, and match the 296 /// ordering of the blocks within the function. If a specific MachineBasicBlock 297 /// is specified, only that block and those after it are renumbered. 298 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 299 if (empty()) { MBBNumbering.clear(); return; } 300 MachineFunction::iterator MBBI, E = end(); 301 if (MBB == nullptr) 302 MBBI = begin(); 303 else 304 MBBI = MBB->getIterator(); 305 306 // Figure out the block number this should have. 307 unsigned BlockNo = 0; 308 if (MBBI != begin()) 309 BlockNo = std::prev(MBBI)->getNumber() + 1; 310 311 for (; MBBI != E; ++MBBI, ++BlockNo) { 312 if (MBBI->getNumber() != (int)BlockNo) { 313 // Remove use of the old number. 314 if (MBBI->getNumber() != -1) { 315 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 316 "MBB number mismatch!"); 317 MBBNumbering[MBBI->getNumber()] = nullptr; 318 } 319 320 // If BlockNo is already taken, set that block's number to -1. 321 if (MBBNumbering[BlockNo]) 322 MBBNumbering[BlockNo]->setNumber(-1); 323 324 MBBNumbering[BlockNo] = &*MBBI; 325 MBBI->setNumber(BlockNo); 326 } 327 } 328 329 // Okay, all the blocks are renumbered. If we have compactified the block 330 // numbering, shrink MBBNumbering now. 331 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 332 MBBNumbering.resize(BlockNo); 333 } 334 335 /// This method iterates over the basic blocks and assigns their IsBeginSection 336 /// and IsEndSection fields. This must be called after MBB layout is finalized 337 /// and the SectionID's are assigned to MBBs. 338 void MachineFunction::assignBeginEndSections() { 339 front().setIsBeginSection(); 340 auto CurrentSectionID = front().getSectionID(); 341 for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) { 342 if (MBBI->getSectionID() == CurrentSectionID) 343 continue; 344 MBBI->setIsBeginSection(); 345 std::prev(MBBI)->setIsEndSection(); 346 CurrentSectionID = MBBI->getSectionID(); 347 } 348 back().setIsEndSection(); 349 } 350 351 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 352 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 353 DebugLoc DL, 354 bool NoImplicit) { 355 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 356 MachineInstr(*this, MCID, std::move(DL), NoImplicit); 357 } 358 359 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 360 /// identical in all ways except the instruction has no parent, prev, or next. 361 MachineInstr * 362 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 363 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 364 MachineInstr(*this, *Orig); 365 } 366 367 MachineInstr &MachineFunction::cloneMachineInstrBundle( 368 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, 369 const MachineInstr &Orig) { 370 MachineInstr *FirstClone = nullptr; 371 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 372 while (true) { 373 MachineInstr *Cloned = CloneMachineInstr(&*I); 374 MBB.insert(InsertBefore, Cloned); 375 if (FirstClone == nullptr) { 376 FirstClone = Cloned; 377 } else { 378 Cloned->bundleWithPred(); 379 } 380 381 if (!I->isBundledWithSucc()) 382 break; 383 ++I; 384 } 385 // Copy over call site info to the cloned instruction if needed. If Orig is in 386 // a bundle, copyCallSiteInfo takes care of finding the call instruction in 387 // the bundle. 388 if (Orig.shouldUpdateCallSiteInfo()) 389 copyCallSiteInfo(&Orig, FirstClone); 390 return *FirstClone; 391 } 392 393 /// Delete the given MachineInstr. 394 /// 395 /// This function also serves as the MachineInstr destructor - the real 396 /// ~MachineInstr() destructor must be empty. 397 void MachineFunction::deleteMachineInstr(MachineInstr *MI) { 398 // Verify that a call site info is at valid state. This assertion should 399 // be triggered during the implementation of support for the 400 // call site info of a new architecture. If the assertion is triggered, 401 // back trace will tell where to insert a call to updateCallSiteInfo(). 402 assert((!MI->isCandidateForCallSiteEntry() || 403 CallSitesInfo.find(MI) == CallSitesInfo.end()) && 404 "Call site info was not updated!"); 405 // Strip it for parts. The operand array and the MI object itself are 406 // independently recyclable. 407 if (MI->Operands) 408 deallocateOperandArray(MI->CapOperands, MI->Operands); 409 // Don't call ~MachineInstr() which must be trivial anyway because 410 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 411 // destructors. 412 InstructionRecycler.Deallocate(Allocator, MI); 413 } 414 415 /// Allocate a new MachineBasicBlock. Use this instead of 416 /// `new MachineBasicBlock'. 417 MachineBasicBlock * 418 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 419 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 420 MachineBasicBlock(*this, bb); 421 } 422 423 /// Delete the given MachineBasicBlock. 424 void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) { 425 assert(MBB->getParent() == this && "MBB parent mismatch!"); 426 // Clean up any references to MBB in jump tables before deleting it. 427 if (JumpTableInfo) 428 JumpTableInfo->RemoveMBBFromJumpTables(MBB); 429 MBB->~MachineBasicBlock(); 430 BasicBlockRecycler.Deallocate(Allocator, MBB); 431 } 432 433 MachineMemOperand *MachineFunction::getMachineMemOperand( 434 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 435 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 436 SyncScope::ID SSID, AtomicOrdering Ordering, 437 AtomicOrdering FailureOrdering) { 438 return new (Allocator) 439 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 440 SSID, Ordering, FailureOrdering); 441 } 442 443 MachineMemOperand *MachineFunction::getMachineMemOperand( 444 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, 445 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 446 SyncScope::ID SSID, AtomicOrdering Ordering, 447 AtomicOrdering FailureOrdering) { 448 return new (Allocator) 449 MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID, 450 Ordering, FailureOrdering); 451 } 452 453 MachineMemOperand *MachineFunction::getMachineMemOperand( 454 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) { 455 return new (Allocator) 456 MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(), 457 AAMDNodes(), nullptr, MMO->getSyncScopeID(), 458 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 459 } 460 461 MachineMemOperand *MachineFunction::getMachineMemOperand( 462 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) { 463 return new (Allocator) 464 MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(), 465 AAMDNodes(), nullptr, MMO->getSyncScopeID(), 466 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 467 } 468 469 MachineMemOperand * 470 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 471 int64_t Offset, LLT Ty) { 472 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 473 474 // If there is no pointer value, the offset isn't tracked so we need to adjust 475 // the base alignment. 476 Align Alignment = PtrInfo.V.isNull() 477 ? commonAlignment(MMO->getBaseAlign(), Offset) 478 : MMO->getBaseAlign(); 479 480 // Do not preserve ranges, since we don't necessarily know what the high bits 481 // are anymore. 482 return new (Allocator) MachineMemOperand( 483 PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment, 484 MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(), 485 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 486 } 487 488 MachineMemOperand * 489 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 490 const AAMDNodes &AAInfo) { 491 MachinePointerInfo MPI = MMO->getValue() ? 492 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 493 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 494 495 return new (Allocator) MachineMemOperand( 496 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo, 497 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(), 498 MMO->getFailureOrdering()); 499 } 500 501 MachineMemOperand * 502 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 503 MachineMemOperand::Flags Flags) { 504 return new (Allocator) MachineMemOperand( 505 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(), 506 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(), 507 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 508 } 509 510 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo( 511 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol, 512 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) { 513 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 514 PostInstrSymbol, HeapAllocMarker); 515 } 516 517 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 518 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 519 llvm::copy(Name, Dest); 520 Dest[Name.size()] = 0; 521 return Dest; 522 } 523 524 uint32_t *MachineFunction::allocateRegMask() { 525 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 526 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 527 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 528 memset(Mask, 0, Size * sizeof(Mask[0])); 529 return Mask; 530 } 531 532 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) { 533 int* AllocMask = Allocator.Allocate<int>(Mask.size()); 534 copy(Mask, AllocMask); 535 return {AllocMask, Mask.size()}; 536 } 537 538 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 539 LLVM_DUMP_METHOD void MachineFunction::dump() const { 540 print(dbgs()); 541 } 542 #endif 543 544 StringRef MachineFunction::getName() const { 545 return getFunction().getName(); 546 } 547 548 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 549 OS << "# Machine code for function " << getName() << ": "; 550 getProperties().print(OS); 551 OS << '\n'; 552 553 // Print Frame Information 554 FrameInfo->print(*this, OS); 555 556 // Print JumpTable Information 557 if (JumpTableInfo) 558 JumpTableInfo->print(OS); 559 560 // Print Constant Pool 561 ConstantPool->print(OS); 562 563 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 564 565 if (RegInfo && !RegInfo->livein_empty()) { 566 OS << "Function Live Ins: "; 567 for (MachineRegisterInfo::livein_iterator 568 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 569 OS << printReg(I->first, TRI); 570 if (I->second) 571 OS << " in " << printReg(I->second, TRI); 572 if (std::next(I) != E) 573 OS << ", "; 574 } 575 OS << '\n'; 576 } 577 578 ModuleSlotTracker MST(getFunction().getParent()); 579 MST.incorporateFunction(getFunction()); 580 for (const auto &BB : *this) { 581 OS << '\n'; 582 // If we print the whole function, print it at its most verbose level. 583 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 584 } 585 586 OS << "\n# End machine code for function " << getName() << ".\n\n"; 587 } 588 589 /// True if this function needs frame moves for debug or exceptions. 590 bool MachineFunction::needsFrameMoves() const { 591 return getMMI().hasDebugInfo() || 592 getTarget().Options.ForceDwarfFrameSection || 593 F.needsUnwindTableEntry(); 594 } 595 596 namespace llvm { 597 598 template<> 599 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 600 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 601 602 static std::string getGraphName(const MachineFunction *F) { 603 return ("CFG for '" + F->getName() + "' function").str(); 604 } 605 606 std::string getNodeLabel(const MachineBasicBlock *Node, 607 const MachineFunction *Graph) { 608 std::string OutStr; 609 { 610 raw_string_ostream OSS(OutStr); 611 612 if (isSimple()) { 613 OSS << printMBBReference(*Node); 614 if (const BasicBlock *BB = Node->getBasicBlock()) 615 OSS << ": " << BB->getName(); 616 } else 617 Node->print(OSS); 618 } 619 620 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 621 622 // Process string output to make it nicer... 623 for (unsigned i = 0; i != OutStr.length(); ++i) 624 if (OutStr[i] == '\n') { // Left justify 625 OutStr[i] = '\\'; 626 OutStr.insert(OutStr.begin()+i+1, 'l'); 627 } 628 return OutStr; 629 } 630 }; 631 632 } // end namespace llvm 633 634 void MachineFunction::viewCFG() const 635 { 636 #ifndef NDEBUG 637 ViewGraph(this, "mf" + getName()); 638 #else 639 errs() << "MachineFunction::viewCFG is only available in debug builds on " 640 << "systems with Graphviz or gv!\n"; 641 #endif // NDEBUG 642 } 643 644 void MachineFunction::viewCFGOnly() const 645 { 646 #ifndef NDEBUG 647 ViewGraph(this, "mf" + getName(), true); 648 #else 649 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 650 << "systems with Graphviz or gv!\n"; 651 #endif // NDEBUG 652 } 653 654 /// Add the specified physical register as a live-in value and 655 /// create a corresponding virtual register for it. 656 Register MachineFunction::addLiveIn(MCRegister PReg, 657 const TargetRegisterClass *RC) { 658 MachineRegisterInfo &MRI = getRegInfo(); 659 Register VReg = MRI.getLiveInVirtReg(PReg); 660 if (VReg) { 661 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 662 (void)VRegRC; 663 // A physical register can be added several times. 664 // Between two calls, the register class of the related virtual register 665 // may have been constrained to match some operation constraints. 666 // In that case, check that the current register class includes the 667 // physical register and is a sub class of the specified RC. 668 assert((VRegRC == RC || (VRegRC->contains(PReg) && 669 RC->hasSubClassEq(VRegRC))) && 670 "Register class mismatch!"); 671 return VReg; 672 } 673 VReg = MRI.createVirtualRegister(RC); 674 MRI.addLiveIn(PReg, VReg); 675 return VReg; 676 } 677 678 /// Return the MCSymbol for the specified non-empty jump table. 679 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 680 /// normal 'L' label is returned. 681 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 682 bool isLinkerPrivate) const { 683 const DataLayout &DL = getDataLayout(); 684 assert(JumpTableInfo && "No jump tables"); 685 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 686 687 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 688 : DL.getPrivateGlobalPrefix(); 689 SmallString<60> Name; 690 raw_svector_ostream(Name) 691 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 692 return Ctx.getOrCreateSymbol(Name); 693 } 694 695 /// Return a function-local symbol to represent the PIC base. 696 MCSymbol *MachineFunction::getPICBaseSymbol() const { 697 const DataLayout &DL = getDataLayout(); 698 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 699 Twine(getFunctionNumber()) + "$pb"); 700 } 701 702 /// \name Exception Handling 703 /// \{ 704 705 LandingPadInfo & 706 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 707 unsigned N = LandingPads.size(); 708 for (unsigned i = 0; i < N; ++i) { 709 LandingPadInfo &LP = LandingPads[i]; 710 if (LP.LandingPadBlock == LandingPad) 711 return LP; 712 } 713 714 LandingPads.push_back(LandingPadInfo(LandingPad)); 715 return LandingPads[N]; 716 } 717 718 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 719 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 720 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 721 LP.BeginLabels.push_back(BeginLabel); 722 LP.EndLabels.push_back(EndLabel); 723 } 724 725 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 726 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 727 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 728 LP.LandingPadLabel = LandingPadLabel; 729 730 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 731 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 732 if (const auto *PF = 733 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 734 getMMI().addPersonality(PF); 735 736 if (LPI->isCleanup()) 737 addCleanup(LandingPad); 738 739 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 740 // correct, but we need to do it this way because of how the DWARF EH 741 // emitter processes the clauses. 742 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 743 Value *Val = LPI->getClause(I - 1); 744 if (LPI->isCatch(I - 1)) { 745 addCatchTypeInfo(LandingPad, 746 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 747 } else { 748 // Add filters in a list. 749 auto *CVal = cast<Constant>(Val); 750 SmallVector<const GlobalValue *, 4> FilterList; 751 for (const Use &U : CVal->operands()) 752 FilterList.push_back(cast<GlobalValue>(U->stripPointerCasts())); 753 754 addFilterTypeInfo(LandingPad, FilterList); 755 } 756 } 757 758 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 759 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) { 760 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts(); 761 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo)); 762 } 763 764 } else { 765 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 766 } 767 768 return LandingPadLabel; 769 } 770 771 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 772 ArrayRef<const GlobalValue *> TyInfo) { 773 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 774 for (const GlobalValue *GV : llvm::reverse(TyInfo)) 775 LP.TypeIds.push_back(getTypeIDFor(GV)); 776 } 777 778 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 779 ArrayRef<const GlobalValue *> TyInfo) { 780 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 781 std::vector<unsigned> IdsInFilter(TyInfo.size()); 782 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 783 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 784 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 785 } 786 787 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap, 788 bool TidyIfNoBeginLabels) { 789 for (unsigned i = 0; i != LandingPads.size(); ) { 790 LandingPadInfo &LandingPad = LandingPads[i]; 791 if (LandingPad.LandingPadLabel && 792 !LandingPad.LandingPadLabel->isDefined() && 793 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 794 LandingPad.LandingPadLabel = nullptr; 795 796 // Special case: we *should* emit LPs with null LP MBB. This indicates 797 // "nounwind" case. 798 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 799 LandingPads.erase(LandingPads.begin() + i); 800 continue; 801 } 802 803 if (TidyIfNoBeginLabels) { 804 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 805 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 806 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 807 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) && 808 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0))) 809 continue; 810 811 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 812 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 813 --j; 814 --e; 815 } 816 817 // Remove landing pads with no try-ranges. 818 if (LandingPads[i].BeginLabels.empty()) { 819 LandingPads.erase(LandingPads.begin() + i); 820 continue; 821 } 822 } 823 824 // If there is no landing pad, ensure that the list of typeids is empty. 825 // If the only typeid is a cleanup, this is the same as having no typeids. 826 if (!LandingPad.LandingPadBlock || 827 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 828 LandingPad.TypeIds.clear(); 829 ++i; 830 } 831 } 832 833 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 834 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 835 LP.TypeIds.push_back(0); 836 } 837 838 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 839 const Function *Filter, 840 const BlockAddress *RecoverBA) { 841 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 842 SEHHandler Handler; 843 Handler.FilterOrFinally = Filter; 844 Handler.RecoverBA = RecoverBA; 845 LP.SEHHandlers.push_back(Handler); 846 } 847 848 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 849 const Function *Cleanup) { 850 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 851 SEHHandler Handler; 852 Handler.FilterOrFinally = Cleanup; 853 Handler.RecoverBA = nullptr; 854 LP.SEHHandlers.push_back(Handler); 855 } 856 857 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 858 ArrayRef<unsigned> Sites) { 859 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 860 } 861 862 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 863 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 864 if (TypeInfos[i] == TI) return i + 1; 865 866 TypeInfos.push_back(TI); 867 return TypeInfos.size(); 868 } 869 870 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 871 // If the new filter coincides with the tail of an existing filter, then 872 // re-use the existing filter. Folding filters more than this requires 873 // re-ordering filters and/or their elements - probably not worth it. 874 for (unsigned i : FilterEnds) { 875 unsigned j = TyIds.size(); 876 877 while (i && j) 878 if (FilterIds[--i] != TyIds[--j]) 879 goto try_next; 880 881 if (!j) 882 // The new filter coincides with range [i, end) of the existing filter. 883 return -(1 + i); 884 885 try_next:; 886 } 887 888 // Add the new filter. 889 int FilterID = -(1 + FilterIds.size()); 890 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 891 llvm::append_range(FilterIds, TyIds); 892 FilterEnds.push_back(FilterIds.size()); 893 FilterIds.push_back(0); // terminator 894 return FilterID; 895 } 896 897 MachineFunction::CallSiteInfoMap::iterator 898 MachineFunction::getCallSiteInfo(const MachineInstr *MI) { 899 assert(MI->isCandidateForCallSiteEntry() && 900 "Call site info refers only to call (MI) candidates"); 901 902 if (!Target.Options.EmitCallSiteInfo) 903 return CallSitesInfo.end(); 904 return CallSitesInfo.find(MI); 905 } 906 907 /// Return the call machine instruction or find a call within bundle. 908 static const MachineInstr *getCallInstr(const MachineInstr *MI) { 909 if (!MI->isBundle()) 910 return MI; 911 912 for (auto &BMI : make_range(getBundleStart(MI->getIterator()), 913 getBundleEnd(MI->getIterator()))) 914 if (BMI.isCandidateForCallSiteEntry()) 915 return &BMI; 916 917 llvm_unreachable("Unexpected bundle without a call site candidate"); 918 } 919 920 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) { 921 assert(MI->shouldUpdateCallSiteInfo() && 922 "Call site info refers only to call (MI) candidates or " 923 "candidates inside bundles"); 924 925 const MachineInstr *CallMI = getCallInstr(MI); 926 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI); 927 if (CSIt == CallSitesInfo.end()) 928 return; 929 CallSitesInfo.erase(CSIt); 930 } 931 932 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old, 933 const MachineInstr *New) { 934 assert(Old->shouldUpdateCallSiteInfo() && 935 "Call site info refers only to call (MI) candidates or " 936 "candidates inside bundles"); 937 938 if (!New->isCandidateForCallSiteEntry()) 939 return eraseCallSiteInfo(Old); 940 941 const MachineInstr *OldCallMI = getCallInstr(Old); 942 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 943 if (CSIt == CallSitesInfo.end()) 944 return; 945 946 CallSiteInfo CSInfo = CSIt->second; 947 CallSitesInfo[New] = CSInfo; 948 } 949 950 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old, 951 const MachineInstr *New) { 952 assert(Old->shouldUpdateCallSiteInfo() && 953 "Call site info refers only to call (MI) candidates or " 954 "candidates inside bundles"); 955 956 if (!New->isCandidateForCallSiteEntry()) 957 return eraseCallSiteInfo(Old); 958 959 const MachineInstr *OldCallMI = getCallInstr(Old); 960 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 961 if (CSIt == CallSitesInfo.end()) 962 return; 963 964 CallSiteInfo CSInfo = std::move(CSIt->second); 965 CallSitesInfo.erase(CSIt); 966 CallSitesInfo[New] = CSInfo; 967 } 968 969 void MachineFunction::setDebugInstrNumberingCount(unsigned Num) { 970 DebugInstrNumberingCount = Num; 971 } 972 973 void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A, 974 DebugInstrOperandPair B, 975 unsigned Subreg) { 976 // Catch any accidental self-loops. 977 assert(A.first != B.first); 978 // Don't allow any substitutions _from_ the memory operand number. 979 assert(A.second != DebugOperandMemNumber); 980 981 DebugValueSubstitutions.push_back({A, B, Subreg}); 982 } 983 984 void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old, 985 MachineInstr &New, 986 unsigned MaxOperand) { 987 // If the Old instruction wasn't tracked at all, there is no work to do. 988 unsigned OldInstrNum = Old.peekDebugInstrNum(); 989 if (!OldInstrNum) 990 return; 991 992 // Iterate over all operands looking for defs to create substitutions for. 993 // Avoid creating new instr numbers unless we create a new substitution. 994 // While this has no functional effect, it risks confusing someone reading 995 // MIR output. 996 // Examine all the operands, or the first N specified by the caller. 997 MaxOperand = std::min(MaxOperand, Old.getNumOperands()); 998 for (unsigned int I = 0; I < MaxOperand; ++I) { 999 const auto &OldMO = Old.getOperand(I); 1000 auto &NewMO = New.getOperand(I); 1001 (void)NewMO; 1002 1003 if (!OldMO.isReg() || !OldMO.isDef()) 1004 continue; 1005 assert(NewMO.isDef()); 1006 1007 unsigned NewInstrNum = New.getDebugInstrNum(); 1008 makeDebugValueSubstitution(std::make_pair(OldInstrNum, I), 1009 std::make_pair(NewInstrNum, I)); 1010 } 1011 } 1012 1013 auto MachineFunction::salvageCopySSA(MachineInstr &MI) 1014 -> DebugInstrOperandPair { 1015 MachineRegisterInfo &MRI = getRegInfo(); 1016 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 1017 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo(); 1018 1019 // Chase the value read by a copy-like instruction back to the instruction 1020 // that ultimately _defines_ that value. This may pass: 1021 // * Through multiple intermediate copies, including subregister moves / 1022 // copies, 1023 // * Copies from physical registers that must then be traced back to the 1024 // defining instruction, 1025 // * Or, physical registers may be live-in to (only) the entry block, which 1026 // requires a DBG_PHI to be created. 1027 // We can pursue this problem in that order: trace back through copies, 1028 // optionally through a physical register, to a defining instruction. We 1029 // should never move from physreg to vreg. As we're still in SSA form, no need 1030 // to worry about partial definitions of registers. 1031 1032 // Helper lambda to interpret a copy-like instruction. Takes instruction, 1033 // returns the register read and any subregister identifying which part is 1034 // read. 1035 auto GetRegAndSubreg = 1036 [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> { 1037 Register NewReg, OldReg; 1038 unsigned SubReg; 1039 if (Cpy.isCopy()) { 1040 OldReg = Cpy.getOperand(0).getReg(); 1041 NewReg = Cpy.getOperand(1).getReg(); 1042 SubReg = Cpy.getOperand(1).getSubReg(); 1043 } else if (Cpy.isSubregToReg()) { 1044 OldReg = Cpy.getOperand(0).getReg(); 1045 NewReg = Cpy.getOperand(2).getReg(); 1046 SubReg = Cpy.getOperand(3).getImm(); 1047 } else { 1048 auto CopyDetails = *TII.isCopyInstr(Cpy); 1049 const MachineOperand &Src = *CopyDetails.Source; 1050 const MachineOperand &Dest = *CopyDetails.Destination; 1051 OldReg = Dest.getReg(); 1052 NewReg = Src.getReg(); 1053 SubReg = Src.getSubReg(); 1054 } 1055 1056 return {NewReg, SubReg}; 1057 }; 1058 1059 // First seek either the defining instruction, or a copy from a physreg. 1060 // During search, the current state is the current copy instruction, and which 1061 // register we've read. Accumulate qualifying subregisters into SubregsSeen; 1062 // deal with those later. 1063 auto State = GetRegAndSubreg(MI); 1064 auto CurInst = MI.getIterator(); 1065 SmallVector<unsigned, 4> SubregsSeen; 1066 while (true) { 1067 // If we've found a copy from a physreg, first portion of search is over. 1068 if (!State.first.isVirtual()) 1069 break; 1070 1071 // Record any subregister qualifier. 1072 if (State.second) 1073 SubregsSeen.push_back(State.second); 1074 1075 assert(MRI.hasOneDef(State.first)); 1076 MachineInstr &Inst = *MRI.def_begin(State.first)->getParent(); 1077 CurInst = Inst.getIterator(); 1078 1079 // Any non-copy instruction is the defining instruction we're seeking. 1080 if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst)) 1081 break; 1082 State = GetRegAndSubreg(Inst); 1083 }; 1084 1085 // Helper lambda to apply additional subregister substitutions to a known 1086 // instruction/operand pair. Adds new (fake) substitutions so that we can 1087 // record the subregister. FIXME: this isn't very space efficient if multiple 1088 // values are tracked back through the same copies; cache something later. 1089 auto ApplySubregisters = 1090 [&](DebugInstrOperandPair P) -> DebugInstrOperandPair { 1091 for (unsigned Subreg : reverse(SubregsSeen)) { 1092 // Fetch a new instruction number, not attached to an actual instruction. 1093 unsigned NewInstrNumber = getNewDebugInstrNum(); 1094 // Add a substitution from the "new" number to the known one, with a 1095 // qualifying subreg. 1096 makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg); 1097 // Return the new number; to find the underlying value, consumers need to 1098 // deal with the qualifying subreg. 1099 P = {NewInstrNumber, 0}; 1100 } 1101 return P; 1102 }; 1103 1104 // If we managed to find the defining instruction after COPYs, return an 1105 // instruction / operand pair after adding subregister qualifiers. 1106 if (State.first.isVirtual()) { 1107 // Virtual register def -- we can just look up where this happens. 1108 MachineInstr *Inst = MRI.def_begin(State.first)->getParent(); 1109 for (auto &MO : Inst->operands()) { 1110 if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first) 1111 continue; 1112 return ApplySubregisters( 1113 {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)}); 1114 } 1115 1116 llvm_unreachable("Vreg def with no corresponding operand?"); 1117 } 1118 1119 // Our search ended in a copy from a physreg: walk back up the function 1120 // looking for whatever defines the physreg. 1121 assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst)); 1122 State = GetRegAndSubreg(*CurInst); 1123 Register RegToSeek = State.first; 1124 1125 auto RMII = CurInst->getReverseIterator(); 1126 auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend()); 1127 for (auto &ToExamine : PrevInstrs) { 1128 for (auto &MO : ToExamine.operands()) { 1129 // Test for operand that defines something aliasing RegToSeek. 1130 if (!MO.isReg() || !MO.isDef() || 1131 !TRI.regsOverlap(RegToSeek, MO.getReg())) 1132 continue; 1133 1134 return ApplySubregisters( 1135 {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)}); 1136 } 1137 } 1138 1139 MachineBasicBlock &InsertBB = *CurInst->getParent(); 1140 1141 // We reached the start of the block before finding a defining instruction. 1142 // It could be from a constant register, otherwise it must be an argument. 1143 if (TRI.isConstantPhysReg(State.first)) { 1144 // We can produce a DBG_PHI that identifies the constant physreg. Doesn't 1145 // matter where we put it, as it's constant valued. 1146 assert(CurInst->isCopy()); 1147 } else if (State.first == TRI.getFrameRegister(*this)) { 1148 // LLVM IR is allowed to read the framepointer by calling a 1149 // llvm.frameaddress.* intrinsic. We can support this by emitting a 1150 // DBG_PHI $fp. This isn't ideal, because it extends the behaviours / 1151 // position that DBG_PHIs appear at, limiting what can be done later. 1152 // TODO: see if there's a better way of expressing these variable 1153 // locations. 1154 ; 1155 } else { 1156 // Assert that this is the entry block, or an EH pad. If it isn't, then 1157 // there is some code construct we don't recognise that deals with physregs 1158 // across blocks. 1159 assert(!State.first.isVirtual()); 1160 assert(&*InsertBB.getParent()->begin() == &InsertBB || InsertBB.isEHPad()); 1161 } 1162 1163 // Create DBG_PHI for specified physreg. 1164 auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(), 1165 TII.get(TargetOpcode::DBG_PHI)); 1166 Builder.addReg(State.first); 1167 unsigned NewNum = getNewDebugInstrNum(); 1168 Builder.addImm(NewNum); 1169 return ApplySubregisters({NewNum, 0u}); 1170 } 1171 1172 void MachineFunction::finalizeDebugInstrRefs() { 1173 auto *TII = getSubtarget().getInstrInfo(); 1174 1175 auto MakeUndefDbgValue = [&](MachineInstr &MI) { 1176 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE); 1177 MI.setDesc(RefII); 1178 MI.getOperand(0).setReg(0); 1179 MI.getOperand(1).ChangeToRegister(0, false); 1180 }; 1181 1182 if (!useDebugInstrRef()) 1183 return; 1184 1185 for (auto &MBB : *this) { 1186 for (auto &MI : MBB) { 1187 if (!MI.isDebugRef() || !MI.getOperand(0).isReg()) 1188 continue; 1189 1190 Register Reg = MI.getOperand(0).getReg(); 1191 1192 // Some vregs can be deleted as redundant in the meantime. Mark those 1193 // as DBG_VALUE $noreg. Additionally, some normal instructions are 1194 // quickly deleted, leaving dangling references to vregs with no def. 1195 if (Reg == 0 || !RegInfo->hasOneDef(Reg)) { 1196 MakeUndefDbgValue(MI); 1197 continue; 1198 } 1199 1200 assert(Reg.isVirtual()); 1201 MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg); 1202 1203 // If we've found a copy-like instruction, follow it back to the 1204 // instruction that defines the source value, see salvageCopySSA docs 1205 // for why this is important. 1206 if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) { 1207 auto Result = salvageCopySSA(DefMI); 1208 MI.getOperand(0).ChangeToImmediate(Result.first); 1209 MI.getOperand(1).setImm(Result.second); 1210 } else { 1211 // Otherwise, identify the operand number that the VReg refers to. 1212 unsigned OperandIdx = 0; 1213 for (const auto &MO : DefMI.operands()) { 1214 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg) 1215 break; 1216 ++OperandIdx; 1217 } 1218 assert(OperandIdx < DefMI.getNumOperands()); 1219 1220 // Morph this instr ref to point at the given instruction and operand. 1221 unsigned ID = DefMI.getDebugInstrNum(); 1222 MI.getOperand(0).ChangeToImmediate(ID); 1223 MI.getOperand(1).setImm(OperandIdx); 1224 } 1225 } 1226 } 1227 } 1228 1229 bool MachineFunction::useDebugInstrRef() const { 1230 // Disable instr-ref at -O0: it's very slow (in compile time). We can still 1231 // have optimized code inlined into this unoptimized code, however with 1232 // fewer and less aggressive optimizations happening, coverage and accuracy 1233 // should not suffer. 1234 if (getTarget().getOptLevel() == CodeGenOpt::None) 1235 return false; 1236 1237 // Don't use instr-ref if this function is marked optnone. 1238 if (F.hasFnAttribute(Attribute::OptimizeNone)) 1239 return false; 1240 1241 if (getTarget().Options.ValueTrackingVariableLocations) 1242 return true; 1243 1244 return false; 1245 } 1246 1247 // Use one million as a high / reserved number. 1248 const unsigned MachineFunction::DebugOperandMemNumber = 1000000; 1249 1250 /// \} 1251 1252 //===----------------------------------------------------------------------===// 1253 // MachineJumpTableInfo implementation 1254 //===----------------------------------------------------------------------===// 1255 1256 /// Return the size of each entry in the jump table. 1257 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 1258 // The size of a jump table entry is 4 bytes unless the entry is just the 1259 // address of a block, in which case it is the pointer size. 1260 switch (getEntryKind()) { 1261 case MachineJumpTableInfo::EK_BlockAddress: 1262 return TD.getPointerSize(); 1263 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1264 return 8; 1265 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1266 case MachineJumpTableInfo::EK_LabelDifference32: 1267 case MachineJumpTableInfo::EK_Custom32: 1268 return 4; 1269 case MachineJumpTableInfo::EK_Inline: 1270 return 0; 1271 } 1272 llvm_unreachable("Unknown jump table encoding!"); 1273 } 1274 1275 /// Return the alignment of each entry in the jump table. 1276 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 1277 // The alignment of a jump table entry is the alignment of int32 unless the 1278 // entry is just the address of a block, in which case it is the pointer 1279 // alignment. 1280 switch (getEntryKind()) { 1281 case MachineJumpTableInfo::EK_BlockAddress: 1282 return TD.getPointerABIAlignment(0).value(); 1283 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1284 return TD.getABIIntegerTypeAlignment(64).value(); 1285 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1286 case MachineJumpTableInfo::EK_LabelDifference32: 1287 case MachineJumpTableInfo::EK_Custom32: 1288 return TD.getABIIntegerTypeAlignment(32).value(); 1289 case MachineJumpTableInfo::EK_Inline: 1290 return 1; 1291 } 1292 llvm_unreachable("Unknown jump table encoding!"); 1293 } 1294 1295 /// Create a new jump table entry in the jump table info. 1296 unsigned MachineJumpTableInfo::createJumpTableIndex( 1297 const std::vector<MachineBasicBlock*> &DestBBs) { 1298 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 1299 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 1300 return JumpTables.size()-1; 1301 } 1302 1303 /// If Old is the target of any jump tables, update the jump tables to branch 1304 /// to New instead. 1305 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 1306 MachineBasicBlock *New) { 1307 assert(Old != New && "Not making a change?"); 1308 bool MadeChange = false; 1309 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 1310 ReplaceMBBInJumpTable(i, Old, New); 1311 return MadeChange; 1312 } 1313 1314 /// If MBB is present in any jump tables, remove it. 1315 bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) { 1316 bool MadeChange = false; 1317 for (MachineJumpTableEntry &JTE : JumpTables) { 1318 auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB); 1319 MadeChange |= (removeBeginItr != JTE.MBBs.end()); 1320 JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end()); 1321 } 1322 return MadeChange; 1323 } 1324 1325 /// If Old is a target of the jump tables, update the jump table to branch to 1326 /// New instead. 1327 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 1328 MachineBasicBlock *Old, 1329 MachineBasicBlock *New) { 1330 assert(Old != New && "Not making a change?"); 1331 bool MadeChange = false; 1332 MachineJumpTableEntry &JTE = JumpTables[Idx]; 1333 for (MachineBasicBlock *&MBB : JTE.MBBs) 1334 if (MBB == Old) { 1335 MBB = New; 1336 MadeChange = true; 1337 } 1338 return MadeChange; 1339 } 1340 1341 void MachineJumpTableInfo::print(raw_ostream &OS) const { 1342 if (JumpTables.empty()) return; 1343 1344 OS << "Jump Tables:\n"; 1345 1346 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 1347 OS << printJumpTableEntryReference(i) << ':'; 1348 for (const MachineBasicBlock *MBB : JumpTables[i].MBBs) 1349 OS << ' ' << printMBBReference(*MBB); 1350 if (i != e) 1351 OS << '\n'; 1352 } 1353 1354 OS << '\n'; 1355 } 1356 1357 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1358 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 1359 #endif 1360 1361 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 1362 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 1363 } 1364 1365 //===----------------------------------------------------------------------===// 1366 // MachineConstantPool implementation 1367 //===----------------------------------------------------------------------===// 1368 1369 void MachineConstantPoolValue::anchor() {} 1370 1371 unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const { 1372 return DL.getTypeAllocSize(Ty); 1373 } 1374 1375 unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const { 1376 if (isMachineConstantPoolEntry()) 1377 return Val.MachineCPVal->getSizeInBytes(DL); 1378 return DL.getTypeAllocSize(Val.ConstVal->getType()); 1379 } 1380 1381 bool MachineConstantPoolEntry::needsRelocation() const { 1382 if (isMachineConstantPoolEntry()) 1383 return true; 1384 return Val.ConstVal->needsDynamicRelocation(); 1385 } 1386 1387 SectionKind 1388 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 1389 if (needsRelocation()) 1390 return SectionKind::getReadOnlyWithRel(); 1391 switch (getSizeInBytes(*DL)) { 1392 case 4: 1393 return SectionKind::getMergeableConst4(); 1394 case 8: 1395 return SectionKind::getMergeableConst8(); 1396 case 16: 1397 return SectionKind::getMergeableConst16(); 1398 case 32: 1399 return SectionKind::getMergeableConst32(); 1400 default: 1401 return SectionKind::getReadOnly(); 1402 } 1403 } 1404 1405 MachineConstantPool::~MachineConstantPool() { 1406 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 1407 // so keep track of which we've deleted to avoid double deletions. 1408 DenseSet<MachineConstantPoolValue*> Deleted; 1409 for (const MachineConstantPoolEntry &C : Constants) 1410 if (C.isMachineConstantPoolEntry()) { 1411 Deleted.insert(C.Val.MachineCPVal); 1412 delete C.Val.MachineCPVal; 1413 } 1414 for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) { 1415 if (Deleted.count(CPV) == 0) 1416 delete CPV; 1417 } 1418 } 1419 1420 /// Test whether the given two constants can be allocated the same constant pool 1421 /// entry. 1422 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 1423 const DataLayout &DL) { 1424 // Handle the trivial case quickly. 1425 if (A == B) return true; 1426 1427 // If they have the same type but weren't the same constant, quickly 1428 // reject them. 1429 if (A->getType() == B->getType()) return false; 1430 1431 // We can't handle structs or arrays. 1432 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 1433 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 1434 return false; 1435 1436 // For now, only support constants with the same size. 1437 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 1438 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 1439 return false; 1440 1441 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1442 1443 // Try constant folding a bitcast of both instructions to an integer. If we 1444 // get two identical ConstantInt's, then we are good to share them. We use 1445 // the constant folding APIs to do this so that we get the benefit of 1446 // DataLayout. 1447 if (isa<PointerType>(A->getType())) 1448 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1449 const_cast<Constant *>(A), IntTy, DL); 1450 else if (A->getType() != IntTy) 1451 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1452 IntTy, DL); 1453 if (isa<PointerType>(B->getType())) 1454 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1455 const_cast<Constant *>(B), IntTy, DL); 1456 else if (B->getType() != IntTy) 1457 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1458 IntTy, DL); 1459 1460 return A == B; 1461 } 1462 1463 /// Create a new entry in the constant pool or return an existing one. 1464 /// User must specify the log2 of the minimum required alignment for the object. 1465 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1466 Align Alignment) { 1467 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1468 1469 // Check to see if we already have this constant. 1470 // 1471 // FIXME, this could be made much more efficient for large constant pools. 1472 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1473 if (!Constants[i].isMachineConstantPoolEntry() && 1474 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1475 if (Constants[i].getAlign() < Alignment) 1476 Constants[i].Alignment = Alignment; 1477 return i; 1478 } 1479 1480 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1481 return Constants.size()-1; 1482 } 1483 1484 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1485 Align Alignment) { 1486 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1487 1488 // Check to see if we already have this constant. 1489 // 1490 // FIXME, this could be made much more efficient for large constant pools. 1491 int Idx = V->getExistingMachineCPValue(this, Alignment); 1492 if (Idx != -1) { 1493 MachineCPVsSharingEntries.insert(V); 1494 return (unsigned)Idx; 1495 } 1496 1497 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1498 return Constants.size()-1; 1499 } 1500 1501 void MachineConstantPool::print(raw_ostream &OS) const { 1502 if (Constants.empty()) return; 1503 1504 OS << "Constant Pool:\n"; 1505 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1506 OS << " cp#" << i << ": "; 1507 if (Constants[i].isMachineConstantPoolEntry()) 1508 Constants[i].Val.MachineCPVal->print(OS); 1509 else 1510 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1511 OS << ", align=" << Constants[i].getAlign().value(); 1512 OS << "\n"; 1513 } 1514 } 1515 1516 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1517 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1518 #endif 1519