1 //===- MachineFunction.cpp ------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Collect native machine code information for a function. This allows 10 // target-specific information about the generated code to be stored with each 11 // function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/ConstantFolding.h" 25 #include "llvm/Analysis/EHPersonalities.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineConstantPool.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineModuleInfo.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/PseudoSourceValue.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetInstrInfo.h" 37 #include "llvm/CodeGen/TargetLowering.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/CodeGen/WasmEHFuncInfo.h" 41 #include "llvm/CodeGen/WinEHFuncInfo.h" 42 #include "llvm/Config/llvm-config.h" 43 #include "llvm/IR/Attributes.h" 44 #include "llvm/IR/BasicBlock.h" 45 #include "llvm/IR/Constant.h" 46 #include "llvm/IR/DataLayout.h" 47 #include "llvm/IR/DerivedTypes.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() || 431 CallSitesInfo.find(MI) == CallSitesInfo.end()) && 432 "Call site info was not updated!"); 433 // Strip it for parts. The operand array and the MI object itself are 434 // independently recyclable. 435 if (MI->Operands) 436 deallocateOperandArray(MI->CapOperands, MI->Operands); 437 // Don't call ~MachineInstr() which must be trivial anyway because 438 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 439 // destructors. 440 InstructionRecycler.Deallocate(Allocator, MI); 441 } 442 443 /// Allocate a new MachineBasicBlock. Use this instead of 444 /// `new MachineBasicBlock'. 445 MachineBasicBlock * 446 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 447 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 448 MachineBasicBlock(*this, bb); 449 } 450 451 /// Delete the given MachineBasicBlock. 452 void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) { 453 assert(MBB->getParent() == this && "MBB parent mismatch!"); 454 // Clean up any references to MBB in jump tables before deleting it. 455 if (JumpTableInfo) 456 JumpTableInfo->RemoveMBBFromJumpTables(MBB); 457 MBB->~MachineBasicBlock(); 458 BasicBlockRecycler.Deallocate(Allocator, MBB); 459 } 460 461 MachineMemOperand *MachineFunction::getMachineMemOperand( 462 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 463 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 464 SyncScope::ID SSID, AtomicOrdering Ordering, 465 AtomicOrdering FailureOrdering) { 466 return new (Allocator) 467 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 468 SSID, Ordering, FailureOrdering); 469 } 470 471 MachineMemOperand *MachineFunction::getMachineMemOperand( 472 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy, 473 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 474 SyncScope::ID SSID, AtomicOrdering Ordering, 475 AtomicOrdering FailureOrdering) { 476 return new (Allocator) 477 MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID, 478 Ordering, FailureOrdering); 479 } 480 481 MachineMemOperand *MachineFunction::getMachineMemOperand( 482 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) { 483 return new (Allocator) 484 MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(), 485 AAMDNodes(), nullptr, MMO->getSyncScopeID(), 486 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 487 } 488 489 MachineMemOperand *MachineFunction::getMachineMemOperand( 490 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) { 491 return new (Allocator) 492 MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(), 493 AAMDNodes(), nullptr, MMO->getSyncScopeID(), 494 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 495 } 496 497 MachineMemOperand * 498 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 499 int64_t Offset, LLT Ty) { 500 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 501 502 // If there is no pointer value, the offset isn't tracked so we need to adjust 503 // the base alignment. 504 Align Alignment = PtrInfo.V.isNull() 505 ? commonAlignment(MMO->getBaseAlign(), Offset) 506 : MMO->getBaseAlign(); 507 508 // Do not preserve ranges, since we don't necessarily know what the high bits 509 // are anymore. 510 return new (Allocator) MachineMemOperand( 511 PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment, 512 MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(), 513 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 514 } 515 516 MachineMemOperand * 517 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 518 const AAMDNodes &AAInfo) { 519 MachinePointerInfo MPI = MMO->getValue() ? 520 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 521 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 522 523 return new (Allocator) MachineMemOperand( 524 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo, 525 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(), 526 MMO->getFailureOrdering()); 527 } 528 529 MachineMemOperand * 530 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 531 MachineMemOperand::Flags Flags) { 532 return new (Allocator) MachineMemOperand( 533 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(), 534 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(), 535 MMO->getSuccessOrdering(), MMO->getFailureOrdering()); 536 } 537 538 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo( 539 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol, 540 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections, 541 uint32_t CFIType) { 542 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 543 PostInstrSymbol, HeapAllocMarker, 544 PCSections, CFIType); 545 } 546 547 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 548 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 549 llvm::copy(Name, Dest); 550 Dest[Name.size()] = 0; 551 return Dest; 552 } 553 554 uint32_t *MachineFunction::allocateRegMask() { 555 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 556 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 557 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 558 memset(Mask, 0, Size * sizeof(Mask[0])); 559 return Mask; 560 } 561 562 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) { 563 int* AllocMask = Allocator.Allocate<int>(Mask.size()); 564 copy(Mask, AllocMask); 565 return {AllocMask, Mask.size()}; 566 } 567 568 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 569 LLVM_DUMP_METHOD void MachineFunction::dump() const { 570 print(dbgs()); 571 } 572 #endif 573 574 StringRef MachineFunction::getName() const { 575 return getFunction().getName(); 576 } 577 578 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 579 OS << "# Machine code for function " << getName() << ": "; 580 getProperties().print(OS); 581 OS << '\n'; 582 583 // Print Frame Information 584 FrameInfo->print(*this, OS); 585 586 // Print JumpTable Information 587 if (JumpTableInfo) 588 JumpTableInfo->print(OS); 589 590 // Print Constant Pool 591 ConstantPool->print(OS); 592 593 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 594 595 if (RegInfo && !RegInfo->livein_empty()) { 596 OS << "Function Live Ins: "; 597 for (MachineRegisterInfo::livein_iterator 598 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 599 OS << printReg(I->first, TRI); 600 if (I->second) 601 OS << " in " << printReg(I->second, TRI); 602 if (std::next(I) != E) 603 OS << ", "; 604 } 605 OS << '\n'; 606 } 607 608 ModuleSlotTracker MST(getFunction().getParent()); 609 MST.incorporateFunction(getFunction()); 610 for (const auto &BB : *this) { 611 OS << '\n'; 612 // If we print the whole function, print it at its most verbose level. 613 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 614 } 615 616 OS << "\n# End machine code for function " << getName() << ".\n\n"; 617 } 618 619 /// True if this function needs frame moves for debug or exceptions. 620 bool MachineFunction::needsFrameMoves() const { 621 return getMMI().hasDebugInfo() || 622 getTarget().Options.ForceDwarfFrameSection || 623 F.needsUnwindTableEntry(); 624 } 625 626 namespace llvm { 627 628 template<> 629 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 630 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 631 632 static std::string getGraphName(const MachineFunction *F) { 633 return ("CFG for '" + F->getName() + "' function").str(); 634 } 635 636 std::string getNodeLabel(const MachineBasicBlock *Node, 637 const MachineFunction *Graph) { 638 std::string OutStr; 639 { 640 raw_string_ostream OSS(OutStr); 641 642 if (isSimple()) { 643 OSS << printMBBReference(*Node); 644 if (const BasicBlock *BB = Node->getBasicBlock()) 645 OSS << ": " << BB->getName(); 646 } else 647 Node->print(OSS); 648 } 649 650 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 651 652 // Process string output to make it nicer... 653 for (unsigned i = 0; i != OutStr.length(); ++i) 654 if (OutStr[i] == '\n') { // Left justify 655 OutStr[i] = '\\'; 656 OutStr.insert(OutStr.begin()+i+1, 'l'); 657 } 658 return OutStr; 659 } 660 }; 661 662 } // end namespace llvm 663 664 void MachineFunction::viewCFG() const 665 { 666 #ifndef NDEBUG 667 ViewGraph(this, "mf" + getName()); 668 #else 669 errs() << "MachineFunction::viewCFG is only available in debug builds on " 670 << "systems with Graphviz or gv!\n"; 671 #endif // NDEBUG 672 } 673 674 void MachineFunction::viewCFGOnly() const 675 { 676 #ifndef NDEBUG 677 ViewGraph(this, "mf" + getName(), true); 678 #else 679 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 680 << "systems with Graphviz or gv!\n"; 681 #endif // NDEBUG 682 } 683 684 /// Add the specified physical register as a live-in value and 685 /// create a corresponding virtual register for it. 686 Register MachineFunction::addLiveIn(MCRegister PReg, 687 const TargetRegisterClass *RC) { 688 MachineRegisterInfo &MRI = getRegInfo(); 689 Register VReg = MRI.getLiveInVirtReg(PReg); 690 if (VReg) { 691 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 692 (void)VRegRC; 693 // A physical register can be added several times. 694 // Between two calls, the register class of the related virtual register 695 // may have been constrained to match some operation constraints. 696 // In that case, check that the current register class includes the 697 // physical register and is a sub class of the specified RC. 698 assert((VRegRC == RC || (VRegRC->contains(PReg) && 699 RC->hasSubClassEq(VRegRC))) && 700 "Register class mismatch!"); 701 return VReg; 702 } 703 VReg = MRI.createVirtualRegister(RC); 704 MRI.addLiveIn(PReg, VReg); 705 return VReg; 706 } 707 708 /// Return the MCSymbol for the specified non-empty jump table. 709 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 710 /// normal 'L' label is returned. 711 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 712 bool isLinkerPrivate) const { 713 const DataLayout &DL = getDataLayout(); 714 assert(JumpTableInfo && "No jump tables"); 715 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 716 717 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 718 : DL.getPrivateGlobalPrefix(); 719 SmallString<60> Name; 720 raw_svector_ostream(Name) 721 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 722 return Ctx.getOrCreateSymbol(Name); 723 } 724 725 /// Return a function-local symbol to represent the PIC base. 726 MCSymbol *MachineFunction::getPICBaseSymbol() const { 727 const DataLayout &DL = getDataLayout(); 728 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 729 Twine(getFunctionNumber()) + "$pb"); 730 } 731 732 /// \name Exception Handling 733 /// \{ 734 735 LandingPadInfo & 736 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 737 unsigned N = LandingPads.size(); 738 for (unsigned i = 0; i < N; ++i) { 739 LandingPadInfo &LP = LandingPads[i]; 740 if (LP.LandingPadBlock == LandingPad) 741 return LP; 742 } 743 744 LandingPads.push_back(LandingPadInfo(LandingPad)); 745 return LandingPads[N]; 746 } 747 748 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 749 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 750 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 751 LP.BeginLabels.push_back(BeginLabel); 752 LP.EndLabels.push_back(EndLabel); 753 } 754 755 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 756 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 757 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 758 LP.LandingPadLabel = LandingPadLabel; 759 760 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 761 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 762 if (const auto *PF = 763 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 764 getMMI().addPersonality(PF); 765 766 // If there's no typeid list specified, then "cleanup" is implicit. 767 // Otherwise, id 0 is reserved for the cleanup action. 768 if (LPI->isCleanup() && LPI->getNumClauses() != 0) 769 LP.TypeIds.push_back(0); 770 771 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 772 // correct, but we need to do it this way because of how the DWARF EH 773 // emitter processes the clauses. 774 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 775 Value *Val = LPI->getClause(I - 1); 776 if (LPI->isCatch(I - 1)) { 777 LP.TypeIds.push_back( 778 getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts()))); 779 } else { 780 // Add filters in a list. 781 auto *CVal = cast<Constant>(Val); 782 SmallVector<unsigned, 4> FilterList; 783 for (const Use &U : CVal->operands()) 784 FilterList.push_back( 785 getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts()))); 786 787 LP.TypeIds.push_back(getFilterIDFor(FilterList)); 788 } 789 } 790 791 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 792 for (unsigned I = CPI->arg_size(); I != 0; --I) { 793 auto *TypeInfo = 794 dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts()); 795 LP.TypeIds.push_back(getTypeIDFor(TypeInfo)); 796 } 797 798 } else { 799 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 800 } 801 802 return LandingPadLabel; 803 } 804 805 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 806 ArrayRef<unsigned> Sites) { 807 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 808 } 809 810 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 811 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 812 if (TypeInfos[i] == TI) return i + 1; 813 814 TypeInfos.push_back(TI); 815 return TypeInfos.size(); 816 } 817 818 int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) { 819 // If the new filter coincides with the tail of an existing filter, then 820 // re-use the existing filter. Folding filters more than this requires 821 // re-ordering filters and/or their elements - probably not worth it. 822 for (unsigned i : FilterEnds) { 823 unsigned j = TyIds.size(); 824 825 while (i && j) 826 if (FilterIds[--i] != TyIds[--j]) 827 goto try_next; 828 829 if (!j) 830 // The new filter coincides with range [i, end) of the existing filter. 831 return -(1 + i); 832 833 try_next:; 834 } 835 836 // Add the new filter. 837 int FilterID = -(1 + FilterIds.size()); 838 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 839 llvm::append_range(FilterIds, TyIds); 840 FilterEnds.push_back(FilterIds.size()); 841 FilterIds.push_back(0); // terminator 842 return FilterID; 843 } 844 845 MachineFunction::CallSiteInfoMap::iterator 846 MachineFunction::getCallSiteInfo(const MachineInstr *MI) { 847 assert(MI->isCandidateForCallSiteEntry() && 848 "Call site info refers only to call (MI) candidates"); 849 850 if (!Target.Options.EmitCallSiteInfo) 851 return CallSitesInfo.end(); 852 return CallSitesInfo.find(MI); 853 } 854 855 /// Return the call machine instruction or find a call within bundle. 856 static const MachineInstr *getCallInstr(const MachineInstr *MI) { 857 if (!MI->isBundle()) 858 return MI; 859 860 for (const auto &BMI : make_range(getBundleStart(MI->getIterator()), 861 getBundleEnd(MI->getIterator()))) 862 if (BMI.isCandidateForCallSiteEntry()) 863 return &BMI; 864 865 llvm_unreachable("Unexpected bundle without a call site candidate"); 866 } 867 868 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) { 869 assert(MI->shouldUpdateCallSiteInfo() && 870 "Call site info refers only to call (MI) candidates or " 871 "candidates inside bundles"); 872 873 const MachineInstr *CallMI = getCallInstr(MI); 874 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI); 875 if (CSIt == CallSitesInfo.end()) 876 return; 877 CallSitesInfo.erase(CSIt); 878 } 879 880 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old, 881 const MachineInstr *New) { 882 assert(Old->shouldUpdateCallSiteInfo() && 883 "Call site info refers only to call (MI) candidates or " 884 "candidates inside bundles"); 885 886 if (!New->isCandidateForCallSiteEntry()) 887 return eraseCallSiteInfo(Old); 888 889 const MachineInstr *OldCallMI = getCallInstr(Old); 890 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 891 if (CSIt == CallSitesInfo.end()) 892 return; 893 894 CallSiteInfo CSInfo = CSIt->second; 895 CallSitesInfo[New] = CSInfo; 896 } 897 898 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old, 899 const MachineInstr *New) { 900 assert(Old->shouldUpdateCallSiteInfo() && 901 "Call site info refers only to call (MI) candidates or " 902 "candidates inside bundles"); 903 904 if (!New->isCandidateForCallSiteEntry()) 905 return eraseCallSiteInfo(Old); 906 907 const MachineInstr *OldCallMI = getCallInstr(Old); 908 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 909 if (CSIt == CallSitesInfo.end()) 910 return; 911 912 CallSiteInfo CSInfo = std::move(CSIt->second); 913 CallSitesInfo.erase(CSIt); 914 CallSitesInfo[New] = CSInfo; 915 } 916 917 void MachineFunction::setDebugInstrNumberingCount(unsigned Num) { 918 DebugInstrNumberingCount = Num; 919 } 920 921 void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A, 922 DebugInstrOperandPair B, 923 unsigned Subreg) { 924 // Catch any accidental self-loops. 925 assert(A.first != B.first); 926 // Don't allow any substitutions _from_ the memory operand number. 927 assert(A.second != DebugOperandMemNumber); 928 929 DebugValueSubstitutions.push_back({A, B, Subreg}); 930 } 931 932 void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old, 933 MachineInstr &New, 934 unsigned MaxOperand) { 935 // If the Old instruction wasn't tracked at all, there is no work to do. 936 unsigned OldInstrNum = Old.peekDebugInstrNum(); 937 if (!OldInstrNum) 938 return; 939 940 // Iterate over all operands looking for defs to create substitutions for. 941 // Avoid creating new instr numbers unless we create a new substitution. 942 // While this has no functional effect, it risks confusing someone reading 943 // MIR output. 944 // Examine all the operands, or the first N specified by the caller. 945 MaxOperand = std::min(MaxOperand, Old.getNumOperands()); 946 for (unsigned int I = 0; I < MaxOperand; ++I) { 947 const auto &OldMO = Old.getOperand(I); 948 auto &NewMO = New.getOperand(I); 949 (void)NewMO; 950 951 if (!OldMO.isReg() || !OldMO.isDef()) 952 continue; 953 assert(NewMO.isDef()); 954 955 unsigned NewInstrNum = New.getDebugInstrNum(); 956 makeDebugValueSubstitution(std::make_pair(OldInstrNum, I), 957 std::make_pair(NewInstrNum, I)); 958 } 959 } 960 961 auto MachineFunction::salvageCopySSA( 962 MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache) 963 -> DebugInstrOperandPair { 964 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo(); 965 966 // Check whether this copy-like instruction has already been salvaged into 967 // an operand pair. 968 Register Dest; 969 if (auto CopyDstSrc = TII.isCopyInstr(MI)) { 970 Dest = CopyDstSrc->Destination->getReg(); 971 } else { 972 assert(MI.isSubregToReg()); 973 Dest = MI.getOperand(0).getReg(); 974 } 975 976 auto CacheIt = DbgPHICache.find(Dest); 977 if (CacheIt != DbgPHICache.end()) 978 return CacheIt->second; 979 980 // Calculate the instruction number to use, or install a DBG_PHI. 981 auto OperandPair = salvageCopySSAImpl(MI); 982 DbgPHICache.insert({Dest, OperandPair}); 983 return OperandPair; 984 } 985 986 auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI) 987 -> DebugInstrOperandPair { 988 MachineRegisterInfo &MRI = getRegInfo(); 989 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 990 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo(); 991 992 // Chase the value read by a copy-like instruction back to the instruction 993 // that ultimately _defines_ that value. This may pass: 994 // * Through multiple intermediate copies, including subregister moves / 995 // copies, 996 // * Copies from physical registers that must then be traced back to the 997 // defining instruction, 998 // * Or, physical registers may be live-in to (only) the entry block, which 999 // requires a DBG_PHI to be created. 1000 // We can pursue this problem in that order: trace back through copies, 1001 // optionally through a physical register, to a defining instruction. We 1002 // should never move from physreg to vreg. As we're still in SSA form, no need 1003 // to worry about partial definitions of registers. 1004 1005 // Helper lambda to interpret a copy-like instruction. Takes instruction, 1006 // returns the register read and any subregister identifying which part is 1007 // read. 1008 auto GetRegAndSubreg = 1009 [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> { 1010 Register NewReg, OldReg; 1011 unsigned SubReg; 1012 if (Cpy.isCopy()) { 1013 OldReg = Cpy.getOperand(0).getReg(); 1014 NewReg = Cpy.getOperand(1).getReg(); 1015 SubReg = Cpy.getOperand(1).getSubReg(); 1016 } else if (Cpy.isSubregToReg()) { 1017 OldReg = Cpy.getOperand(0).getReg(); 1018 NewReg = Cpy.getOperand(2).getReg(); 1019 SubReg = Cpy.getOperand(3).getImm(); 1020 } else { 1021 auto CopyDetails = *TII.isCopyInstr(Cpy); 1022 const MachineOperand &Src = *CopyDetails.Source; 1023 const MachineOperand &Dest = *CopyDetails.Destination; 1024 OldReg = Dest.getReg(); 1025 NewReg = Src.getReg(); 1026 SubReg = Src.getSubReg(); 1027 } 1028 1029 return {NewReg, SubReg}; 1030 }; 1031 1032 // First seek either the defining instruction, or a copy from a physreg. 1033 // During search, the current state is the current copy instruction, and which 1034 // register we've read. Accumulate qualifying subregisters into SubregsSeen; 1035 // deal with those later. 1036 auto State = GetRegAndSubreg(MI); 1037 auto CurInst = MI.getIterator(); 1038 SmallVector<unsigned, 4> SubregsSeen; 1039 while (true) { 1040 // If we've found a copy from a physreg, first portion of search is over. 1041 if (!State.first.isVirtual()) 1042 break; 1043 1044 // Record any subregister qualifier. 1045 if (State.second) 1046 SubregsSeen.push_back(State.second); 1047 1048 assert(MRI.hasOneDef(State.first)); 1049 MachineInstr &Inst = *MRI.def_begin(State.first)->getParent(); 1050 CurInst = Inst.getIterator(); 1051 1052 // Any non-copy instruction is the defining instruction we're seeking. 1053 if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst)) 1054 break; 1055 State = GetRegAndSubreg(Inst); 1056 }; 1057 1058 // Helper lambda to apply additional subregister substitutions to a known 1059 // instruction/operand pair. Adds new (fake) substitutions so that we can 1060 // record the subregister. FIXME: this isn't very space efficient if multiple 1061 // values are tracked back through the same copies; cache something later. 1062 auto ApplySubregisters = 1063 [&](DebugInstrOperandPair P) -> DebugInstrOperandPair { 1064 for (unsigned Subreg : reverse(SubregsSeen)) { 1065 // Fetch a new instruction number, not attached to an actual instruction. 1066 unsigned NewInstrNumber = getNewDebugInstrNum(); 1067 // Add a substitution from the "new" number to the known one, with a 1068 // qualifying subreg. 1069 makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg); 1070 // Return the new number; to find the underlying value, consumers need to 1071 // deal with the qualifying subreg. 1072 P = {NewInstrNumber, 0}; 1073 } 1074 return P; 1075 }; 1076 1077 // If we managed to find the defining instruction after COPYs, return an 1078 // instruction / operand pair after adding subregister qualifiers. 1079 if (State.first.isVirtual()) { 1080 // Virtual register def -- we can just look up where this happens. 1081 MachineInstr *Inst = MRI.def_begin(State.first)->getParent(); 1082 for (auto &MO : Inst->operands()) { 1083 if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first) 1084 continue; 1085 return ApplySubregisters( 1086 {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)}); 1087 } 1088 1089 llvm_unreachable("Vreg def with no corresponding operand?"); 1090 } 1091 1092 // Our search ended in a copy from a physreg: walk back up the function 1093 // looking for whatever defines the physreg. 1094 assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst)); 1095 State = GetRegAndSubreg(*CurInst); 1096 Register RegToSeek = State.first; 1097 1098 auto RMII = CurInst->getReverseIterator(); 1099 auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend()); 1100 for (auto &ToExamine : PrevInstrs) { 1101 for (auto &MO : ToExamine.operands()) { 1102 // Test for operand that defines something aliasing RegToSeek. 1103 if (!MO.isReg() || !MO.isDef() || 1104 !TRI.regsOverlap(RegToSeek, MO.getReg())) 1105 continue; 1106 1107 return ApplySubregisters( 1108 {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)}); 1109 } 1110 } 1111 1112 MachineBasicBlock &InsertBB = *CurInst->getParent(); 1113 1114 // We reached the start of the block before finding a defining instruction. 1115 // There are numerous scenarios where this can happen: 1116 // * Constant physical registers, 1117 // * Several intrinsics that allow LLVM-IR to read arbitary registers, 1118 // * Arguments in the entry block, 1119 // * Exception handling landing pads. 1120 // Validating all of them is too difficult, so just insert a DBG_PHI reading 1121 // the variable value at this position, rather than checking it makes sense. 1122 1123 // Create DBG_PHI for specified physreg. 1124 auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(), 1125 TII.get(TargetOpcode::DBG_PHI)); 1126 Builder.addReg(State.first); 1127 unsigned NewNum = getNewDebugInstrNum(); 1128 Builder.addImm(NewNum); 1129 return ApplySubregisters({NewNum, 0u}); 1130 } 1131 1132 void MachineFunction::finalizeDebugInstrRefs() { 1133 auto *TII = getSubtarget().getInstrInfo(); 1134 1135 auto MakeUndefDbgValue = [&](MachineInstr &MI) { 1136 const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST); 1137 MI.setDesc(RefII); 1138 MI.setDebugValueUndef(); 1139 }; 1140 1141 DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs; 1142 for (auto &MBB : *this) { 1143 for (auto &MI : MBB) { 1144 if (!MI.isDebugRef()) 1145 continue; 1146 1147 bool IsValidRef = true; 1148 1149 for (MachineOperand &MO : MI.debug_operands()) { 1150 if (!MO.isReg()) 1151 continue; 1152 1153 Register Reg = MO.getReg(); 1154 1155 // Some vregs can be deleted as redundant in the meantime. Mark those 1156 // as DBG_VALUE $noreg. Additionally, some normal instructions are 1157 // quickly deleted, leaving dangling references to vregs with no def. 1158 if (Reg == 0 || !RegInfo->hasOneDef(Reg)) { 1159 IsValidRef = false; 1160 break; 1161 } 1162 1163 assert(Reg.isVirtual()); 1164 MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg); 1165 1166 // If we've found a copy-like instruction, follow it back to the 1167 // instruction that defines the source value, see salvageCopySSA docs 1168 // for why this is important. 1169 if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) { 1170 auto Result = salvageCopySSA(DefMI, ArgDbgPHIs); 1171 MO.ChangeToDbgInstrRef(Result.first, Result.second); 1172 } else { 1173 // Otherwise, identify the operand number that the VReg refers to. 1174 unsigned OperandIdx = 0; 1175 for (const auto &DefMO : DefMI.operands()) { 1176 if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg) 1177 break; 1178 ++OperandIdx; 1179 } 1180 assert(OperandIdx < DefMI.getNumOperands()); 1181 1182 // Morph this instr ref to point at the given instruction and operand. 1183 unsigned ID = DefMI.getDebugInstrNum(); 1184 MO.ChangeToDbgInstrRef(ID, OperandIdx); 1185 } 1186 } 1187 1188 if (!IsValidRef) 1189 MakeUndefDbgValue(MI); 1190 } 1191 } 1192 } 1193 1194 bool MachineFunction::useDebugInstrRef() const { 1195 // Disable instr-ref at -O0: it's very slow (in compile time). We can still 1196 // have optimized code inlined into this unoptimized code, however with 1197 // fewer and less aggressive optimizations happening, coverage and accuracy 1198 // should not suffer. 1199 if (getTarget().getOptLevel() == CodeGenOpt::None) 1200 return false; 1201 1202 // Don't use instr-ref if this function is marked optnone. 1203 if (F.hasFnAttribute(Attribute::OptimizeNone)) 1204 return false; 1205 1206 if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple())) 1207 return true; 1208 1209 return false; 1210 } 1211 1212 // Use one million as a high / reserved number. 1213 const unsigned MachineFunction::DebugOperandMemNumber = 1000000; 1214 1215 /// \} 1216 1217 //===----------------------------------------------------------------------===// 1218 // MachineJumpTableInfo implementation 1219 //===----------------------------------------------------------------------===// 1220 1221 /// Return the size of each entry in the jump table. 1222 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 1223 // The size of a jump table entry is 4 bytes unless the entry is just the 1224 // address of a block, in which case it is the pointer size. 1225 switch (getEntryKind()) { 1226 case MachineJumpTableInfo::EK_BlockAddress: 1227 return TD.getPointerSize(); 1228 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1229 return 8; 1230 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1231 case MachineJumpTableInfo::EK_LabelDifference32: 1232 case MachineJumpTableInfo::EK_Custom32: 1233 return 4; 1234 case MachineJumpTableInfo::EK_Inline: 1235 return 0; 1236 } 1237 llvm_unreachable("Unknown jump table encoding!"); 1238 } 1239 1240 /// Return the alignment of each entry in the jump table. 1241 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 1242 // The alignment of a jump table entry is the alignment of int32 unless the 1243 // entry is just the address of a block, in which case it is the pointer 1244 // alignment. 1245 switch (getEntryKind()) { 1246 case MachineJumpTableInfo::EK_BlockAddress: 1247 return TD.getPointerABIAlignment(0).value(); 1248 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1249 return TD.getABIIntegerTypeAlignment(64).value(); 1250 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1251 case MachineJumpTableInfo::EK_LabelDifference32: 1252 case MachineJumpTableInfo::EK_Custom32: 1253 return TD.getABIIntegerTypeAlignment(32).value(); 1254 case MachineJumpTableInfo::EK_Inline: 1255 return 1; 1256 } 1257 llvm_unreachable("Unknown jump table encoding!"); 1258 } 1259 1260 /// Create a new jump table entry in the jump table info. 1261 unsigned MachineJumpTableInfo::createJumpTableIndex( 1262 const std::vector<MachineBasicBlock*> &DestBBs) { 1263 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 1264 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 1265 return JumpTables.size()-1; 1266 } 1267 1268 /// If Old is the target of any jump tables, update the jump tables to branch 1269 /// to New instead. 1270 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 1271 MachineBasicBlock *New) { 1272 assert(Old != New && "Not making a change?"); 1273 bool MadeChange = false; 1274 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 1275 ReplaceMBBInJumpTable(i, Old, New); 1276 return MadeChange; 1277 } 1278 1279 /// If MBB is present in any jump tables, remove it. 1280 bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) { 1281 bool MadeChange = false; 1282 for (MachineJumpTableEntry &JTE : JumpTables) { 1283 auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB); 1284 MadeChange |= (removeBeginItr != JTE.MBBs.end()); 1285 JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end()); 1286 } 1287 return MadeChange; 1288 } 1289 1290 /// If Old is a target of the jump tables, update the jump table to branch to 1291 /// New instead. 1292 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 1293 MachineBasicBlock *Old, 1294 MachineBasicBlock *New) { 1295 assert(Old != New && "Not making a change?"); 1296 bool MadeChange = false; 1297 MachineJumpTableEntry &JTE = JumpTables[Idx]; 1298 for (MachineBasicBlock *&MBB : JTE.MBBs) 1299 if (MBB == Old) { 1300 MBB = New; 1301 MadeChange = true; 1302 } 1303 return MadeChange; 1304 } 1305 1306 void MachineJumpTableInfo::print(raw_ostream &OS) const { 1307 if (JumpTables.empty()) return; 1308 1309 OS << "Jump Tables:\n"; 1310 1311 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 1312 OS << printJumpTableEntryReference(i) << ':'; 1313 for (const MachineBasicBlock *MBB : JumpTables[i].MBBs) 1314 OS << ' ' << printMBBReference(*MBB); 1315 if (i != e) 1316 OS << '\n'; 1317 } 1318 1319 OS << '\n'; 1320 } 1321 1322 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1323 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 1324 #endif 1325 1326 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 1327 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 1328 } 1329 1330 //===----------------------------------------------------------------------===// 1331 // MachineConstantPool implementation 1332 //===----------------------------------------------------------------------===// 1333 1334 void MachineConstantPoolValue::anchor() {} 1335 1336 unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const { 1337 return DL.getTypeAllocSize(Ty); 1338 } 1339 1340 unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const { 1341 if (isMachineConstantPoolEntry()) 1342 return Val.MachineCPVal->getSizeInBytes(DL); 1343 return DL.getTypeAllocSize(Val.ConstVal->getType()); 1344 } 1345 1346 bool MachineConstantPoolEntry::needsRelocation() const { 1347 if (isMachineConstantPoolEntry()) 1348 return true; 1349 return Val.ConstVal->needsDynamicRelocation(); 1350 } 1351 1352 SectionKind 1353 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 1354 if (needsRelocation()) 1355 return SectionKind::getReadOnlyWithRel(); 1356 switch (getSizeInBytes(*DL)) { 1357 case 4: 1358 return SectionKind::getMergeableConst4(); 1359 case 8: 1360 return SectionKind::getMergeableConst8(); 1361 case 16: 1362 return SectionKind::getMergeableConst16(); 1363 case 32: 1364 return SectionKind::getMergeableConst32(); 1365 default: 1366 return SectionKind::getReadOnly(); 1367 } 1368 } 1369 1370 MachineConstantPool::~MachineConstantPool() { 1371 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 1372 // so keep track of which we've deleted to avoid double deletions. 1373 DenseSet<MachineConstantPoolValue*> Deleted; 1374 for (const MachineConstantPoolEntry &C : Constants) 1375 if (C.isMachineConstantPoolEntry()) { 1376 Deleted.insert(C.Val.MachineCPVal); 1377 delete C.Val.MachineCPVal; 1378 } 1379 for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) { 1380 if (Deleted.count(CPV) == 0) 1381 delete CPV; 1382 } 1383 } 1384 1385 /// Test whether the given two constants can be allocated the same constant pool 1386 /// entry. 1387 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 1388 const DataLayout &DL) { 1389 // Handle the trivial case quickly. 1390 if (A == B) return true; 1391 1392 // If they have the same type but weren't the same constant, quickly 1393 // reject them. 1394 if (A->getType() == B->getType()) return false; 1395 1396 // We can't handle structs or arrays. 1397 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 1398 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 1399 return false; 1400 1401 // For now, only support constants with the same size. 1402 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 1403 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 1404 return false; 1405 1406 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1407 1408 // Try constant folding a bitcast of both instructions to an integer. If we 1409 // get two identical ConstantInt's, then we are good to share them. We use 1410 // the constant folding APIs to do this so that we get the benefit of 1411 // DataLayout. 1412 if (isa<PointerType>(A->getType())) 1413 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1414 const_cast<Constant *>(A), IntTy, DL); 1415 else if (A->getType() != IntTy) 1416 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1417 IntTy, DL); 1418 if (isa<PointerType>(B->getType())) 1419 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1420 const_cast<Constant *>(B), IntTy, DL); 1421 else if (B->getType() != IntTy) 1422 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1423 IntTy, DL); 1424 1425 return A == B; 1426 } 1427 1428 /// Create a new entry in the constant pool or return an existing one. 1429 /// User must specify the log2 of the minimum required alignment for the object. 1430 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1431 Align Alignment) { 1432 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1433 1434 // Check to see if we already have this constant. 1435 // 1436 // FIXME, this could be made much more efficient for large constant pools. 1437 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1438 if (!Constants[i].isMachineConstantPoolEntry() && 1439 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1440 if (Constants[i].getAlign() < Alignment) 1441 Constants[i].Alignment = Alignment; 1442 return i; 1443 } 1444 1445 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1446 return Constants.size()-1; 1447 } 1448 1449 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1450 Align Alignment) { 1451 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1452 1453 // Check to see if we already have this constant. 1454 // 1455 // FIXME, this could be made much more efficient for large constant pools. 1456 int Idx = V->getExistingMachineCPValue(this, Alignment); 1457 if (Idx != -1) { 1458 MachineCPVsSharingEntries.insert(V); 1459 return (unsigned)Idx; 1460 } 1461 1462 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1463 return Constants.size()-1; 1464 } 1465 1466 void MachineConstantPool::print(raw_ostream &OS) const { 1467 if (Constants.empty()) return; 1468 1469 OS << "Constant Pool:\n"; 1470 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1471 OS << " cp#" << i << ": "; 1472 if (Constants[i].isMachineConstantPoolEntry()) 1473 Constants[i].Val.MachineCPVal->print(OS); 1474 else 1475 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1476 OS << ", align=" << Constants[i].getAlign().value(); 1477 OS << "\n"; 1478 } 1479 } 1480 1481 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1482 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1483 #endif 1484