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