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