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