1 //===- MachineSink.cpp - Sinking for machine instructions -----------------===// 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 // This pass moves instructions into successor blocks when possible, so that 10 // they aren't executed on paths where their results aren't needed. 11 // 12 // This pass is not intended to be a replacement or a complete alternative 13 // for an LLVM-IR-level sinking pass. It is only designed to sink simple 14 // constructs that are not exposed before lowering and instruction selection. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/SetVector.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/SparseBitVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/CodeGen/MachineBasicBlock.h" 25 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 26 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 27 #include "llvm/CodeGen/MachineDominators.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineFunctionPass.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachinePostDominators.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/TargetInstrInfo.h" 36 #include "llvm/CodeGen/TargetRegisterInfo.h" 37 #include "llvm/CodeGen/TargetSubtargetInfo.h" 38 #include "llvm/IR/BasicBlock.h" 39 #include "llvm/IR/LLVMContext.h" 40 #include "llvm/IR/DebugInfoMetadata.h" 41 #include "llvm/Pass.h" 42 #include "llvm/Support/BranchProbability.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include <algorithm> 47 #include <cassert> 48 #include <cstdint> 49 #include <map> 50 #include <utility> 51 #include <vector> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "machine-sink" 56 57 static cl::opt<bool> 58 SplitEdges("machine-sink-split", 59 cl::desc("Split critical edges during machine sinking"), 60 cl::init(true), cl::Hidden); 61 62 static cl::opt<bool> 63 UseBlockFreqInfo("machine-sink-bfi", 64 cl::desc("Use block frequency info to find successors to sink"), 65 cl::init(true), cl::Hidden); 66 67 static cl::opt<unsigned> SplitEdgeProbabilityThreshold( 68 "machine-sink-split-probability-threshold", 69 cl::desc( 70 "Percentage threshold for splitting single-instruction critical edge. " 71 "If the branch threshold is higher than this threshold, we allow " 72 "speculative execution of up to 1 instruction to avoid branching to " 73 "splitted critical edge"), 74 cl::init(40), cl::Hidden); 75 76 STATISTIC(NumSunk, "Number of machine instructions sunk"); 77 STATISTIC(NumSplit, "Number of critical edges split"); 78 STATISTIC(NumCoalesces, "Number of copies coalesced"); 79 STATISTIC(NumPostRACopySink, "Number of copies sunk after RA"); 80 81 namespace { 82 83 class MachineSinking : public MachineFunctionPass { 84 const TargetInstrInfo *TII; 85 const TargetRegisterInfo *TRI; 86 MachineRegisterInfo *MRI; // Machine register information 87 MachineDominatorTree *DT; // Machine dominator tree 88 MachinePostDominatorTree *PDT; // Machine post dominator tree 89 MachineLoopInfo *LI; 90 const MachineBlockFrequencyInfo *MBFI; 91 const MachineBranchProbabilityInfo *MBPI; 92 AliasAnalysis *AA; 93 94 // Remember which edges have been considered for breaking. 95 SmallSet<std::pair<MachineBasicBlock*, MachineBasicBlock*>, 8> 96 CEBCandidates; 97 // Remember which edges we are about to split. 98 // This is different from CEBCandidates since those edges 99 // will be split. 100 SetVector<std::pair<MachineBasicBlock *, MachineBasicBlock *>> ToSplit; 101 102 SparseBitVector<> RegsToClearKillFlags; 103 104 using AllSuccsCache = 105 std::map<MachineBasicBlock *, SmallVector<MachineBasicBlock *, 4>>; 106 107 public: 108 static char ID; // Pass identification 109 110 MachineSinking() : MachineFunctionPass(ID) { 111 initializeMachineSinkingPass(*PassRegistry::getPassRegistry()); 112 } 113 114 bool runOnMachineFunction(MachineFunction &MF) override; 115 116 void getAnalysisUsage(AnalysisUsage &AU) const override { 117 AU.setPreservesCFG(); 118 MachineFunctionPass::getAnalysisUsage(AU); 119 AU.addRequired<AAResultsWrapperPass>(); 120 AU.addRequired<MachineDominatorTree>(); 121 AU.addRequired<MachinePostDominatorTree>(); 122 AU.addRequired<MachineLoopInfo>(); 123 AU.addRequired<MachineBranchProbabilityInfo>(); 124 AU.addPreserved<MachineDominatorTree>(); 125 AU.addPreserved<MachinePostDominatorTree>(); 126 AU.addPreserved<MachineLoopInfo>(); 127 if (UseBlockFreqInfo) 128 AU.addRequired<MachineBlockFrequencyInfo>(); 129 } 130 131 void releaseMemory() override { 132 CEBCandidates.clear(); 133 } 134 135 private: 136 bool ProcessBlock(MachineBasicBlock &MBB); 137 bool isWorthBreakingCriticalEdge(MachineInstr &MI, 138 MachineBasicBlock *From, 139 MachineBasicBlock *To); 140 141 /// Postpone the splitting of the given critical 142 /// edge (\p From, \p To). 143 /// 144 /// We do not split the edges on the fly. Indeed, this invalidates 145 /// the dominance information and thus triggers a lot of updates 146 /// of that information underneath. 147 /// Instead, we postpone all the splits after each iteration of 148 /// the main loop. That way, the information is at least valid 149 /// for the lifetime of an iteration. 150 /// 151 /// \return True if the edge is marked as toSplit, false otherwise. 152 /// False can be returned if, for instance, this is not profitable. 153 bool PostponeSplitCriticalEdge(MachineInstr &MI, 154 MachineBasicBlock *From, 155 MachineBasicBlock *To, 156 bool BreakPHIEdge); 157 bool SinkInstruction(MachineInstr &MI, bool &SawStore, 158 159 AllSuccsCache &AllSuccessors); 160 bool AllUsesDominatedByBlock(unsigned Reg, MachineBasicBlock *MBB, 161 MachineBasicBlock *DefMBB, 162 bool &BreakPHIEdge, bool &LocalUse) const; 163 MachineBasicBlock *FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB, 164 bool &BreakPHIEdge, AllSuccsCache &AllSuccessors); 165 bool isProfitableToSinkTo(unsigned Reg, MachineInstr &MI, 166 MachineBasicBlock *MBB, 167 MachineBasicBlock *SuccToSinkTo, 168 AllSuccsCache &AllSuccessors); 169 170 bool PerformTrivialForwardCoalescing(MachineInstr &MI, 171 MachineBasicBlock *MBB); 172 173 SmallVector<MachineBasicBlock *, 4> & 174 GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB, 175 AllSuccsCache &AllSuccessors) const; 176 }; 177 178 } // end anonymous namespace 179 180 char MachineSinking::ID = 0; 181 182 char &llvm::MachineSinkingID = MachineSinking::ID; 183 184 INITIALIZE_PASS_BEGIN(MachineSinking, DEBUG_TYPE, 185 "Machine code sinking", false, false) 186 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 187 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 188 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 189 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 190 INITIALIZE_PASS_END(MachineSinking, DEBUG_TYPE, 191 "Machine code sinking", false, false) 192 193 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr &MI, 194 MachineBasicBlock *MBB) { 195 if (!MI.isCopy()) 196 return false; 197 198 unsigned SrcReg = MI.getOperand(1).getReg(); 199 unsigned DstReg = MI.getOperand(0).getReg(); 200 if (!Register::isVirtualRegister(SrcReg) || 201 !Register::isVirtualRegister(DstReg) || !MRI->hasOneNonDBGUse(SrcReg)) 202 return false; 203 204 const TargetRegisterClass *SRC = MRI->getRegClass(SrcReg); 205 const TargetRegisterClass *DRC = MRI->getRegClass(DstReg); 206 if (SRC != DRC) 207 return false; 208 209 MachineInstr *DefMI = MRI->getVRegDef(SrcReg); 210 if (DefMI->isCopyLike()) 211 return false; 212 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI); 213 LLVM_DEBUG(dbgs() << "*** to: " << MI); 214 MRI->replaceRegWith(DstReg, SrcReg); 215 MI.eraseFromParent(); 216 217 // Conservatively, clear any kill flags, since it's possible that they are no 218 // longer correct. 219 MRI->clearKillFlags(SrcReg); 220 221 ++NumCoalesces; 222 return true; 223 } 224 225 /// AllUsesDominatedByBlock - Return true if all uses of the specified register 226 /// occur in blocks dominated by the specified block. If any use is in the 227 /// definition block, then return false since it is never legal to move def 228 /// after uses. 229 bool 230 MachineSinking::AllUsesDominatedByBlock(unsigned Reg, 231 MachineBasicBlock *MBB, 232 MachineBasicBlock *DefMBB, 233 bool &BreakPHIEdge, 234 bool &LocalUse) const { 235 assert(Register::isVirtualRegister(Reg) && "Only makes sense for vregs"); 236 237 // Ignore debug uses because debug info doesn't affect the code. 238 if (MRI->use_nodbg_empty(Reg)) 239 return true; 240 241 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken 242 // into and they are all PHI nodes. In this case, machine-sink must break 243 // the critical edge first. e.g. 244 // 245 // %bb.1: derived from LLVM BB %bb4.preheader 246 // Predecessors according to CFG: %bb.0 247 // ... 248 // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags 249 // ... 250 // JE_4 <%bb.37>, implicit %eflags 251 // Successors according to CFG: %bb.37 %bb.2 252 // 253 // %bb.2: derived from LLVM BB %bb.nph 254 // Predecessors according to CFG: %bb.0 %bb.1 255 // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1 256 BreakPHIEdge = true; 257 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 258 MachineInstr *UseInst = MO.getParent(); 259 unsigned OpNo = &MO - &UseInst->getOperand(0); 260 MachineBasicBlock *UseBlock = UseInst->getParent(); 261 if (!(UseBlock == MBB && UseInst->isPHI() && 262 UseInst->getOperand(OpNo+1).getMBB() == DefMBB)) { 263 BreakPHIEdge = false; 264 break; 265 } 266 } 267 if (BreakPHIEdge) 268 return true; 269 270 for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) { 271 // Determine the block of the use. 272 MachineInstr *UseInst = MO.getParent(); 273 unsigned OpNo = &MO - &UseInst->getOperand(0); 274 MachineBasicBlock *UseBlock = UseInst->getParent(); 275 if (UseInst->isPHI()) { 276 // PHI nodes use the operand in the predecessor block, not the block with 277 // the PHI. 278 UseBlock = UseInst->getOperand(OpNo+1).getMBB(); 279 } else if (UseBlock == DefMBB) { 280 LocalUse = true; 281 return false; 282 } 283 284 // Check that it dominates. 285 if (!DT->dominates(MBB, UseBlock)) 286 return false; 287 } 288 289 return true; 290 } 291 292 bool MachineSinking::runOnMachineFunction(MachineFunction &MF) { 293 if (skipFunction(MF.getFunction())) 294 return false; 295 296 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n"); 297 298 TII = MF.getSubtarget().getInstrInfo(); 299 TRI = MF.getSubtarget().getRegisterInfo(); 300 MRI = &MF.getRegInfo(); 301 DT = &getAnalysis<MachineDominatorTree>(); 302 PDT = &getAnalysis<MachinePostDominatorTree>(); 303 LI = &getAnalysis<MachineLoopInfo>(); 304 MBFI = UseBlockFreqInfo ? &getAnalysis<MachineBlockFrequencyInfo>() : nullptr; 305 MBPI = &getAnalysis<MachineBranchProbabilityInfo>(); 306 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 307 308 bool EverMadeChange = false; 309 310 while (true) { 311 bool MadeChange = false; 312 313 // Process all basic blocks. 314 CEBCandidates.clear(); 315 ToSplit.clear(); 316 for (auto &MBB: MF) 317 MadeChange |= ProcessBlock(MBB); 318 319 // If we have anything we marked as toSplit, split it now. 320 for (auto &Pair : ToSplit) { 321 auto NewSucc = Pair.first->SplitCriticalEdge(Pair.second, *this); 322 if (NewSucc != nullptr) { 323 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: " 324 << printMBBReference(*Pair.first) << " -- " 325 << printMBBReference(*NewSucc) << " -- " 326 << printMBBReference(*Pair.second) << '\n'); 327 MadeChange = true; 328 ++NumSplit; 329 } else 330 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n"); 331 } 332 // If this iteration over the code changed anything, keep iterating. 333 if (!MadeChange) break; 334 EverMadeChange = true; 335 } 336 337 // Now clear any kill flags for recorded registers. 338 for (auto I : RegsToClearKillFlags) 339 MRI->clearKillFlags(I); 340 RegsToClearKillFlags.clear(); 341 342 return EverMadeChange; 343 } 344 345 bool MachineSinking::ProcessBlock(MachineBasicBlock &MBB) { 346 // Can't sink anything out of a block that has less than two successors. 347 if (MBB.succ_size() <= 1 || MBB.empty()) return false; 348 349 // Don't bother sinking code out of unreachable blocks. In addition to being 350 // unprofitable, it can also lead to infinite looping, because in an 351 // unreachable loop there may be nowhere to stop. 352 if (!DT->isReachableFromEntry(&MBB)) return false; 353 354 bool MadeChange = false; 355 356 // Cache all successors, sorted by frequency info and loop depth. 357 AllSuccsCache AllSuccessors; 358 359 // Walk the basic block bottom-up. Remember if we saw a store. 360 MachineBasicBlock::iterator I = MBB.end(); 361 --I; 362 bool ProcessedBegin, SawStore = false; 363 do { 364 MachineInstr &MI = *I; // The instruction to sink. 365 366 // Predecrement I (if it's not begin) so that it isn't invalidated by 367 // sinking. 368 ProcessedBegin = I == MBB.begin(); 369 if (!ProcessedBegin) 370 --I; 371 372 if (MI.isDebugInstr()) 373 continue; 374 375 bool Joined = PerformTrivialForwardCoalescing(MI, &MBB); 376 if (Joined) { 377 MadeChange = true; 378 continue; 379 } 380 381 if (SinkInstruction(MI, SawStore, AllSuccessors)) { 382 ++NumSunk; 383 MadeChange = true; 384 } 385 386 // If we just processed the first instruction in the block, we're done. 387 } while (!ProcessedBegin); 388 389 return MadeChange; 390 } 391 392 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr &MI, 393 MachineBasicBlock *From, 394 MachineBasicBlock *To) { 395 // FIXME: Need much better heuristics. 396 397 // If the pass has already considered breaking this edge (during this pass 398 // through the function), then let's go ahead and break it. This means 399 // sinking multiple "cheap" instructions into the same block. 400 if (!CEBCandidates.insert(std::make_pair(From, To)).second) 401 return true; 402 403 if (!MI.isCopy() && !TII->isAsCheapAsAMove(MI)) 404 return true; 405 406 if (From->isSuccessor(To) && MBPI->getEdgeProbability(From, To) <= 407 BranchProbability(SplitEdgeProbabilityThreshold, 100)) 408 return true; 409 410 // MI is cheap, we probably don't want to break the critical edge for it. 411 // However, if this would allow some definitions of its source operands 412 // to be sunk then it's probably worth it. 413 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 414 const MachineOperand &MO = MI.getOperand(i); 415 if (!MO.isReg() || !MO.isUse()) 416 continue; 417 unsigned Reg = MO.getReg(); 418 if (Reg == 0) 419 continue; 420 421 // We don't move live definitions of physical registers, 422 // so sinking their uses won't enable any opportunities. 423 if (Register::isPhysicalRegister(Reg)) 424 continue; 425 426 // If this instruction is the only user of a virtual register, 427 // check if breaking the edge will enable sinking 428 // both this instruction and the defining instruction. 429 if (MRI->hasOneNonDBGUse(Reg)) { 430 // If the definition resides in same MBB, 431 // claim it's likely we can sink these together. 432 // If definition resides elsewhere, we aren't 433 // blocking it from being sunk so don't break the edge. 434 MachineInstr *DefMI = MRI->getVRegDef(Reg); 435 if (DefMI->getParent() == MI.getParent()) 436 return true; 437 } 438 } 439 440 return false; 441 } 442 443 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr &MI, 444 MachineBasicBlock *FromBB, 445 MachineBasicBlock *ToBB, 446 bool BreakPHIEdge) { 447 if (!isWorthBreakingCriticalEdge(MI, FromBB, ToBB)) 448 return false; 449 450 // Avoid breaking back edge. From == To means backedge for single BB loop. 451 if (!SplitEdges || FromBB == ToBB) 452 return false; 453 454 // Check for backedges of more "complex" loops. 455 if (LI->getLoopFor(FromBB) == LI->getLoopFor(ToBB) && 456 LI->isLoopHeader(ToBB)) 457 return false; 458 459 // It's not always legal to break critical edges and sink the computation 460 // to the edge. 461 // 462 // %bb.1: 463 // v1024 464 // Beq %bb.3 465 // <fallthrough> 466 // %bb.2: 467 // ... no uses of v1024 468 // <fallthrough> 469 // %bb.3: 470 // ... 471 // = v1024 472 // 473 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted: 474 // 475 // %bb.1: 476 // ... 477 // Bne %bb.2 478 // %bb.4: 479 // v1024 = 480 // B %bb.3 481 // %bb.2: 482 // ... no uses of v1024 483 // <fallthrough> 484 // %bb.3: 485 // ... 486 // = v1024 487 // 488 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3 489 // flow. We need to ensure the new basic block where the computation is 490 // sunk to dominates all the uses. 491 // It's only legal to break critical edge and sink the computation to the 492 // new block if all the predecessors of "To", except for "From", are 493 // not dominated by "From". Given SSA property, this means these 494 // predecessors are dominated by "To". 495 // 496 // There is no need to do this check if all the uses are PHI nodes. PHI 497 // sources are only defined on the specific predecessor edges. 498 if (!BreakPHIEdge) { 499 for (MachineBasicBlock::pred_iterator PI = ToBB->pred_begin(), 500 E = ToBB->pred_end(); PI != E; ++PI) { 501 if (*PI == FromBB) 502 continue; 503 if (!DT->dominates(ToBB, *PI)) 504 return false; 505 } 506 } 507 508 ToSplit.insert(std::make_pair(FromBB, ToBB)); 509 510 return true; 511 } 512 513 /// isProfitableToSinkTo - Return true if it is profitable to sink MI. 514 bool MachineSinking::isProfitableToSinkTo(unsigned Reg, MachineInstr &MI, 515 MachineBasicBlock *MBB, 516 MachineBasicBlock *SuccToSinkTo, 517 AllSuccsCache &AllSuccessors) { 518 assert (SuccToSinkTo && "Invalid SinkTo Candidate BB"); 519 520 if (MBB == SuccToSinkTo) 521 return false; 522 523 // It is profitable if SuccToSinkTo does not post dominate current block. 524 if (!PDT->dominates(SuccToSinkTo, MBB)) 525 return true; 526 527 // It is profitable to sink an instruction from a deeper loop to a shallower 528 // loop, even if the latter post-dominates the former (PR21115). 529 if (LI->getLoopDepth(MBB) > LI->getLoopDepth(SuccToSinkTo)) 530 return true; 531 532 // Check if only use in post dominated block is PHI instruction. 533 bool NonPHIUse = false; 534 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(Reg)) { 535 MachineBasicBlock *UseBlock = UseInst.getParent(); 536 if (UseBlock == SuccToSinkTo && !UseInst.isPHI()) 537 NonPHIUse = true; 538 } 539 if (!NonPHIUse) 540 return true; 541 542 // If SuccToSinkTo post dominates then also it may be profitable if MI 543 // can further profitably sinked into another block in next round. 544 bool BreakPHIEdge = false; 545 // FIXME - If finding successor is compile time expensive then cache results. 546 if (MachineBasicBlock *MBB2 = 547 FindSuccToSinkTo(MI, SuccToSinkTo, BreakPHIEdge, AllSuccessors)) 548 return isProfitableToSinkTo(Reg, MI, SuccToSinkTo, MBB2, AllSuccessors); 549 550 // If SuccToSinkTo is final destination and it is a post dominator of current 551 // block then it is not profitable to sink MI into SuccToSinkTo block. 552 return false; 553 } 554 555 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly 556 /// computing it if it was not already cached. 557 SmallVector<MachineBasicBlock *, 4> & 558 MachineSinking::GetAllSortedSuccessors(MachineInstr &MI, MachineBasicBlock *MBB, 559 AllSuccsCache &AllSuccessors) const { 560 // Do we have the sorted successors in cache ? 561 auto Succs = AllSuccessors.find(MBB); 562 if (Succs != AllSuccessors.end()) 563 return Succs->second; 564 565 SmallVector<MachineBasicBlock *, 4> AllSuccs(MBB->succ_begin(), 566 MBB->succ_end()); 567 568 // Handle cases where sinking can happen but where the sink point isn't a 569 // successor. For example: 570 // 571 // x = computation 572 // if () {} else {} 573 // use x 574 // 575 const std::vector<MachineDomTreeNode *> &Children = 576 DT->getNode(MBB)->getChildren(); 577 for (const auto &DTChild : Children) 578 // DomTree children of MBB that have MBB as immediate dominator are added. 579 if (DTChild->getIDom()->getBlock() == MI.getParent() && 580 // Skip MBBs already added to the AllSuccs vector above. 581 !MBB->isSuccessor(DTChild->getBlock())) 582 AllSuccs.push_back(DTChild->getBlock()); 583 584 // Sort Successors according to their loop depth or block frequency info. 585 llvm::stable_sort( 586 AllSuccs, [this](const MachineBasicBlock *L, const MachineBasicBlock *R) { 587 uint64_t LHSFreq = MBFI ? MBFI->getBlockFreq(L).getFrequency() : 0; 588 uint64_t RHSFreq = MBFI ? MBFI->getBlockFreq(R).getFrequency() : 0; 589 bool HasBlockFreq = LHSFreq != 0 && RHSFreq != 0; 590 return HasBlockFreq ? LHSFreq < RHSFreq 591 : LI->getLoopDepth(L) < LI->getLoopDepth(R); 592 }); 593 594 auto it = AllSuccessors.insert(std::make_pair(MBB, AllSuccs)); 595 596 return it.first->second; 597 } 598 599 /// FindSuccToSinkTo - Find a successor to sink this instruction to. 600 MachineBasicBlock * 601 MachineSinking::FindSuccToSinkTo(MachineInstr &MI, MachineBasicBlock *MBB, 602 bool &BreakPHIEdge, 603 AllSuccsCache &AllSuccessors) { 604 assert (MBB && "Invalid MachineBasicBlock!"); 605 606 // Loop over all the operands of the specified instruction. If there is 607 // anything we can't handle, bail out. 608 609 // SuccToSinkTo - This is the successor to sink this instruction to, once we 610 // decide. 611 MachineBasicBlock *SuccToSinkTo = nullptr; 612 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 613 const MachineOperand &MO = MI.getOperand(i); 614 if (!MO.isReg()) continue; // Ignore non-register operands. 615 616 unsigned Reg = MO.getReg(); 617 if (Reg == 0) continue; 618 619 if (Register::isPhysicalRegister(Reg)) { 620 if (MO.isUse()) { 621 // If the physreg has no defs anywhere, it's just an ambient register 622 // and we can freely move its uses. Alternatively, if it's allocatable, 623 // it could get allocated to something with a def during allocation. 624 if (!MRI->isConstantPhysReg(Reg)) 625 return nullptr; 626 } else if (!MO.isDead()) { 627 // A def that isn't dead. We can't move it. 628 return nullptr; 629 } 630 } else { 631 // Virtual register uses are always safe to sink. 632 if (MO.isUse()) continue; 633 634 // If it's not safe to move defs of the register class, then abort. 635 if (!TII->isSafeToMoveRegClassDefs(MRI->getRegClass(Reg))) 636 return nullptr; 637 638 // Virtual register defs can only be sunk if all their uses are in blocks 639 // dominated by one of the successors. 640 if (SuccToSinkTo) { 641 // If a previous operand picked a block to sink to, then this operand 642 // must be sinkable to the same block. 643 bool LocalUse = false; 644 if (!AllUsesDominatedByBlock(Reg, SuccToSinkTo, MBB, 645 BreakPHIEdge, LocalUse)) 646 return nullptr; 647 648 continue; 649 } 650 651 // Otherwise, we should look at all the successors and decide which one 652 // we should sink to. If we have reliable block frequency information 653 // (frequency != 0) available, give successors with smaller frequencies 654 // higher priority, otherwise prioritize smaller loop depths. 655 for (MachineBasicBlock *SuccBlock : 656 GetAllSortedSuccessors(MI, MBB, AllSuccessors)) { 657 bool LocalUse = false; 658 if (AllUsesDominatedByBlock(Reg, SuccBlock, MBB, 659 BreakPHIEdge, LocalUse)) { 660 SuccToSinkTo = SuccBlock; 661 break; 662 } 663 if (LocalUse) 664 // Def is used locally, it's never safe to move this def. 665 return nullptr; 666 } 667 668 // If we couldn't find a block to sink to, ignore this instruction. 669 if (!SuccToSinkTo) 670 return nullptr; 671 if (!isProfitableToSinkTo(Reg, MI, MBB, SuccToSinkTo, AllSuccessors)) 672 return nullptr; 673 } 674 } 675 676 // It is not possible to sink an instruction into its own block. This can 677 // happen with loops. 678 if (MBB == SuccToSinkTo) 679 return nullptr; 680 681 // It's not safe to sink instructions to EH landing pad. Control flow into 682 // landing pad is implicitly defined. 683 if (SuccToSinkTo && SuccToSinkTo->isEHPad()) 684 return nullptr; 685 686 return SuccToSinkTo; 687 } 688 689 /// Return true if MI is likely to be usable as a memory operation by the 690 /// implicit null check optimization. 691 /// 692 /// This is a "best effort" heuristic, and should not be relied upon for 693 /// correctness. This returning true does not guarantee that the implicit null 694 /// check optimization is legal over MI, and this returning false does not 695 /// guarantee MI cannot possibly be used to do a null check. 696 static bool SinkingPreventsImplicitNullCheck(MachineInstr &MI, 697 const TargetInstrInfo *TII, 698 const TargetRegisterInfo *TRI) { 699 using MachineBranchPredicate = TargetInstrInfo::MachineBranchPredicate; 700 701 auto *MBB = MI.getParent(); 702 if (MBB->pred_size() != 1) 703 return false; 704 705 auto *PredMBB = *MBB->pred_begin(); 706 auto *PredBB = PredMBB->getBasicBlock(); 707 708 // Frontends that don't use implicit null checks have no reason to emit 709 // branches with make.implicit metadata, and this function should always 710 // return false for them. 711 if (!PredBB || 712 !PredBB->getTerminator()->getMetadata(LLVMContext::MD_make_implicit)) 713 return false; 714 715 const MachineOperand *BaseOp; 716 int64_t Offset; 717 if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, TRI)) 718 return false; 719 720 if (!BaseOp->isReg()) 721 return false; 722 723 if (!(MI.mayLoad() && !MI.isPredicable())) 724 return false; 725 726 MachineBranchPredicate MBP; 727 if (TII->analyzeBranchPredicate(*PredMBB, MBP, false)) 728 return false; 729 730 return MBP.LHS.isReg() && MBP.RHS.isImm() && MBP.RHS.getImm() == 0 && 731 (MBP.Predicate == MachineBranchPredicate::PRED_NE || 732 MBP.Predicate == MachineBranchPredicate::PRED_EQ) && 733 MBP.LHS.getReg() == BaseOp->getReg(); 734 } 735 736 /// Sink an instruction and its associated debug instructions. If the debug 737 /// instructions to be sunk are already known, they can be provided in DbgVals. 738 static void performSink(MachineInstr &MI, MachineBasicBlock &SuccToSinkTo, 739 MachineBasicBlock::iterator InsertPos, 740 SmallVectorImpl<MachineInstr *> *DbgVals = nullptr) { 741 // If debug values are provided use those, otherwise call collectDebugValues. 742 SmallVector<MachineInstr *, 2> DbgValuesToSink; 743 if (DbgVals) 744 DbgValuesToSink.insert(DbgValuesToSink.begin(), 745 DbgVals->begin(), DbgVals->end()); 746 else 747 MI.collectDebugValues(DbgValuesToSink); 748 749 // If we cannot find a location to use (merge with), then we erase the debug 750 // location to prevent debug-info driven tools from potentially reporting 751 // wrong location information. 752 if (!SuccToSinkTo.empty() && InsertPos != SuccToSinkTo.end()) 753 MI.setDebugLoc(DILocation::getMergedLocation(MI.getDebugLoc(), 754 InsertPos->getDebugLoc())); 755 else 756 MI.setDebugLoc(DebugLoc()); 757 758 // Move the instruction. 759 MachineBasicBlock *ParentBlock = MI.getParent(); 760 SuccToSinkTo.splice(InsertPos, ParentBlock, MI, 761 ++MachineBasicBlock::iterator(MI)); 762 763 // Move previously adjacent debug value instructions to the insert position. 764 for (SmallVectorImpl<MachineInstr *>::iterator DBI = DbgValuesToSink.begin(), 765 DBE = DbgValuesToSink.end(); 766 DBI != DBE; ++DBI) { 767 MachineInstr *DbgMI = *DBI; 768 SuccToSinkTo.splice(InsertPos, ParentBlock, DbgMI, 769 ++MachineBasicBlock::iterator(DbgMI)); 770 } 771 } 772 773 /// SinkInstruction - Determine whether it is safe to sink the specified machine 774 /// instruction out of its current block into a successor. 775 bool MachineSinking::SinkInstruction(MachineInstr &MI, bool &SawStore, 776 AllSuccsCache &AllSuccessors) { 777 // Don't sink instructions that the target prefers not to sink. 778 if (!TII->shouldSink(MI)) 779 return false; 780 781 // Check if it's safe to move the instruction. 782 if (!MI.isSafeToMove(AA, SawStore)) 783 return false; 784 785 // Convergent operations may not be made control-dependent on additional 786 // values. 787 if (MI.isConvergent()) 788 return false; 789 790 // Don't break implicit null checks. This is a performance heuristic, and not 791 // required for correctness. 792 if (SinkingPreventsImplicitNullCheck(MI, TII, TRI)) 793 return false; 794 795 // FIXME: This should include support for sinking instructions within the 796 // block they are currently in to shorten the live ranges. We often get 797 // instructions sunk into the top of a large block, but it would be better to 798 // also sink them down before their first use in the block. This xform has to 799 // be careful not to *increase* register pressure though, e.g. sinking 800 // "x = y + z" down if it kills y and z would increase the live ranges of y 801 // and z and only shrink the live range of x. 802 803 bool BreakPHIEdge = false; 804 MachineBasicBlock *ParentBlock = MI.getParent(); 805 MachineBasicBlock *SuccToSinkTo = 806 FindSuccToSinkTo(MI, ParentBlock, BreakPHIEdge, AllSuccessors); 807 808 // If there are no outputs, it must have side-effects. 809 if (!SuccToSinkTo) 810 return false; 811 812 // If the instruction to move defines a dead physical register which is live 813 // when leaving the basic block, don't move it because it could turn into a 814 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>) 815 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) { 816 const MachineOperand &MO = MI.getOperand(I); 817 if (!MO.isReg()) continue; 818 unsigned Reg = MO.getReg(); 819 if (Reg == 0 || !Register::isPhysicalRegister(Reg)) 820 continue; 821 if (SuccToSinkTo->isLiveIn(Reg)) 822 return false; 823 } 824 825 LLVM_DEBUG(dbgs() << "Sink instr " << MI << "\tinto block " << *SuccToSinkTo); 826 827 // If the block has multiple predecessors, this is a critical edge. 828 // Decide if we can sink along it or need to break the edge. 829 if (SuccToSinkTo->pred_size() > 1) { 830 // We cannot sink a load across a critical edge - there may be stores in 831 // other code paths. 832 bool TryBreak = false; 833 bool store = true; 834 if (!MI.isSafeToMove(AA, store)) { 835 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n"); 836 TryBreak = true; 837 } 838 839 // We don't want to sink across a critical edge if we don't dominate the 840 // successor. We could be introducing calculations to new code paths. 841 if (!TryBreak && !DT->dominates(ParentBlock, SuccToSinkTo)) { 842 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n"); 843 TryBreak = true; 844 } 845 846 // Don't sink instructions into a loop. 847 if (!TryBreak && LI->isLoopHeader(SuccToSinkTo)) { 848 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n"); 849 TryBreak = true; 850 } 851 852 // Otherwise we are OK with sinking along a critical edge. 853 if (!TryBreak) 854 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n"); 855 else { 856 // Mark this edge as to be split. 857 // If the edge can actually be split, the next iteration of the main loop 858 // will sink MI in the newly created block. 859 bool Status = 860 PostponeSplitCriticalEdge(MI, ParentBlock, SuccToSinkTo, BreakPHIEdge); 861 if (!Status) 862 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 863 "break critical edge\n"); 864 // The instruction will not be sunk this time. 865 return false; 866 } 867 } 868 869 if (BreakPHIEdge) { 870 // BreakPHIEdge is true if all the uses are in the successor MBB being 871 // sunken into and they are all PHI nodes. In this case, machine-sink must 872 // break the critical edge first. 873 bool Status = PostponeSplitCriticalEdge(MI, ParentBlock, 874 SuccToSinkTo, BreakPHIEdge); 875 if (!Status) 876 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to " 877 "break critical edge\n"); 878 // The instruction will not be sunk this time. 879 return false; 880 } 881 882 // Determine where to insert into. Skip phi nodes. 883 MachineBasicBlock::iterator InsertPos = SuccToSinkTo->begin(); 884 while (InsertPos != SuccToSinkTo->end() && InsertPos->isPHI()) 885 ++InsertPos; 886 887 performSink(MI, *SuccToSinkTo, InsertPos); 888 889 // Conservatively, clear any kill flags, since it's possible that they are no 890 // longer correct. 891 // Note that we have to clear the kill flags for any register this instruction 892 // uses as we may sink over another instruction which currently kills the 893 // used registers. 894 for (MachineOperand &MO : MI.operands()) { 895 if (MO.isReg() && MO.isUse()) 896 RegsToClearKillFlags.set(MO.getReg()); // Remember to clear kill flags. 897 } 898 899 return true; 900 } 901 902 //===----------------------------------------------------------------------===// 903 // This pass is not intended to be a replacement or a complete alternative 904 // for the pre-ra machine sink pass. It is only designed to sink COPY 905 // instructions which should be handled after RA. 906 // 907 // This pass sinks COPY instructions into a successor block, if the COPY is not 908 // used in the current block and the COPY is live-in to a single successor 909 // (i.e., doesn't require the COPY to be duplicated). This avoids executing the 910 // copy on paths where their results aren't needed. This also exposes 911 // additional opportunites for dead copy elimination and shrink wrapping. 912 // 913 // These copies were either not handled by or are inserted after the MachineSink 914 // pass. As an example of the former case, the MachineSink pass cannot sink 915 // COPY instructions with allocatable source registers; for AArch64 these type 916 // of copy instructions are frequently used to move function parameters (PhyReg) 917 // into virtual registers in the entry block. 918 // 919 // For the machine IR below, this pass will sink %w19 in the entry into its 920 // successor (%bb.1) because %w19 is only live-in in %bb.1. 921 // %bb.0: 922 // %wzr = SUBSWri %w1, 1 923 // %w19 = COPY %w0 924 // Bcc 11, %bb.2 925 // %bb.1: 926 // Live Ins: %w19 927 // BL @fun 928 // %w0 = ADDWrr %w0, %w19 929 // RET %w0 930 // %bb.2: 931 // %w0 = COPY %wzr 932 // RET %w0 933 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be 934 // able to see %bb.0 as a candidate. 935 //===----------------------------------------------------------------------===// 936 namespace { 937 938 class PostRAMachineSinking : public MachineFunctionPass { 939 public: 940 bool runOnMachineFunction(MachineFunction &MF) override; 941 942 static char ID; 943 PostRAMachineSinking() : MachineFunctionPass(ID) {} 944 StringRef getPassName() const override { return "PostRA Machine Sink"; } 945 946 void getAnalysisUsage(AnalysisUsage &AU) const override { 947 AU.setPreservesCFG(); 948 MachineFunctionPass::getAnalysisUsage(AU); 949 } 950 951 MachineFunctionProperties getRequiredProperties() const override { 952 return MachineFunctionProperties().set( 953 MachineFunctionProperties::Property::NoVRegs); 954 } 955 956 private: 957 /// Track which register units have been modified and used. 958 LiveRegUnits ModifiedRegUnits, UsedRegUnits; 959 960 /// Track DBG_VALUEs of (unmodified) register units. 961 DenseMap<unsigned, TinyPtrVector<MachineInstr*>> SeenDbgInstrs; 962 963 /// Sink Copy instructions unused in the same block close to their uses in 964 /// successors. 965 bool tryToSinkCopy(MachineBasicBlock &BB, MachineFunction &MF, 966 const TargetRegisterInfo *TRI, const TargetInstrInfo *TII); 967 }; 968 } // namespace 969 970 char PostRAMachineSinking::ID = 0; 971 char &llvm::PostRAMachineSinkingID = PostRAMachineSinking::ID; 972 973 INITIALIZE_PASS(PostRAMachineSinking, "postra-machine-sink", 974 "PostRA Machine Sink", false, false) 975 976 static bool aliasWithRegsInLiveIn(MachineBasicBlock &MBB, unsigned Reg, 977 const TargetRegisterInfo *TRI) { 978 LiveRegUnits LiveInRegUnits(*TRI); 979 LiveInRegUnits.addLiveIns(MBB); 980 return !LiveInRegUnits.available(Reg); 981 } 982 983 static MachineBasicBlock * 984 getSingleLiveInSuccBB(MachineBasicBlock &CurBB, 985 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs, 986 unsigned Reg, const TargetRegisterInfo *TRI) { 987 // Try to find a single sinkable successor in which Reg is live-in. 988 MachineBasicBlock *BB = nullptr; 989 for (auto *SI : SinkableBBs) { 990 if (aliasWithRegsInLiveIn(*SI, Reg, TRI)) { 991 // If BB is set here, Reg is live-in to at least two sinkable successors, 992 // so quit. 993 if (BB) 994 return nullptr; 995 BB = SI; 996 } 997 } 998 // Reg is not live-in to any sinkable successors. 999 if (!BB) 1000 return nullptr; 1001 1002 // Check if any register aliased with Reg is live-in in other successors. 1003 for (auto *SI : CurBB.successors()) { 1004 if (!SinkableBBs.count(SI) && aliasWithRegsInLiveIn(*SI, Reg, TRI)) 1005 return nullptr; 1006 } 1007 return BB; 1008 } 1009 1010 static MachineBasicBlock * 1011 getSingleLiveInSuccBB(MachineBasicBlock &CurBB, 1012 const SmallPtrSetImpl<MachineBasicBlock *> &SinkableBBs, 1013 ArrayRef<unsigned> DefedRegsInCopy, 1014 const TargetRegisterInfo *TRI) { 1015 MachineBasicBlock *SingleBB = nullptr; 1016 for (auto DefReg : DefedRegsInCopy) { 1017 MachineBasicBlock *BB = 1018 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefReg, TRI); 1019 if (!BB || (SingleBB && SingleBB != BB)) 1020 return nullptr; 1021 SingleBB = BB; 1022 } 1023 return SingleBB; 1024 } 1025 1026 static void clearKillFlags(MachineInstr *MI, MachineBasicBlock &CurBB, 1027 SmallVectorImpl<unsigned> &UsedOpsInCopy, 1028 LiveRegUnits &UsedRegUnits, 1029 const TargetRegisterInfo *TRI) { 1030 for (auto U : UsedOpsInCopy) { 1031 MachineOperand &MO = MI->getOperand(U); 1032 unsigned SrcReg = MO.getReg(); 1033 if (!UsedRegUnits.available(SrcReg)) { 1034 MachineBasicBlock::iterator NI = std::next(MI->getIterator()); 1035 for (MachineInstr &UI : make_range(NI, CurBB.end())) { 1036 if (UI.killsRegister(SrcReg, TRI)) { 1037 UI.clearRegisterKills(SrcReg, TRI); 1038 MO.setIsKill(true); 1039 break; 1040 } 1041 } 1042 } 1043 } 1044 } 1045 1046 static void updateLiveIn(MachineInstr *MI, MachineBasicBlock *SuccBB, 1047 SmallVectorImpl<unsigned> &UsedOpsInCopy, 1048 SmallVectorImpl<unsigned> &DefedRegsInCopy) { 1049 MachineFunction &MF = *SuccBB->getParent(); 1050 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1051 for (unsigned DefReg : DefedRegsInCopy) 1052 for (MCSubRegIterator S(DefReg, TRI, true); S.isValid(); ++S) 1053 SuccBB->removeLiveIn(*S); 1054 for (auto U : UsedOpsInCopy) { 1055 unsigned Reg = MI->getOperand(U).getReg(); 1056 if (!SuccBB->isLiveIn(Reg)) 1057 SuccBB->addLiveIn(Reg); 1058 } 1059 } 1060 1061 static bool hasRegisterDependency(MachineInstr *MI, 1062 SmallVectorImpl<unsigned> &UsedOpsInCopy, 1063 SmallVectorImpl<unsigned> &DefedRegsInCopy, 1064 LiveRegUnits &ModifiedRegUnits, 1065 LiveRegUnits &UsedRegUnits) { 1066 bool HasRegDependency = false; 1067 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1068 MachineOperand &MO = MI->getOperand(i); 1069 if (!MO.isReg()) 1070 continue; 1071 unsigned Reg = MO.getReg(); 1072 if (!Reg) 1073 continue; 1074 if (MO.isDef()) { 1075 if (!ModifiedRegUnits.available(Reg) || !UsedRegUnits.available(Reg)) { 1076 HasRegDependency = true; 1077 break; 1078 } 1079 DefedRegsInCopy.push_back(Reg); 1080 1081 // FIXME: instead of isUse(), readsReg() would be a better fix here, 1082 // For example, we can ignore modifications in reg with undef. However, 1083 // it's not perfectly clear if skipping the internal read is safe in all 1084 // other targets. 1085 } else if (MO.isUse()) { 1086 if (!ModifiedRegUnits.available(Reg)) { 1087 HasRegDependency = true; 1088 break; 1089 } 1090 UsedOpsInCopy.push_back(i); 1091 } 1092 } 1093 return HasRegDependency; 1094 } 1095 1096 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock &CurBB, 1097 MachineFunction &MF, 1098 const TargetRegisterInfo *TRI, 1099 const TargetInstrInfo *TII) { 1100 SmallPtrSet<MachineBasicBlock *, 2> SinkableBBs; 1101 // FIXME: For now, we sink only to a successor which has a single predecessor 1102 // so that we can directly sink COPY instructions to the successor without 1103 // adding any new block or branch instruction. 1104 for (MachineBasicBlock *SI : CurBB.successors()) 1105 if (!SI->livein_empty() && SI->pred_size() == 1) 1106 SinkableBBs.insert(SI); 1107 1108 if (SinkableBBs.empty()) 1109 return false; 1110 1111 bool Changed = false; 1112 1113 // Track which registers have been modified and used between the end of the 1114 // block and the current instruction. 1115 ModifiedRegUnits.clear(); 1116 UsedRegUnits.clear(); 1117 SeenDbgInstrs.clear(); 1118 1119 for (auto I = CurBB.rbegin(), E = CurBB.rend(); I != E;) { 1120 MachineInstr *MI = &*I; 1121 ++I; 1122 1123 // Track the operand index for use in Copy. 1124 SmallVector<unsigned, 2> UsedOpsInCopy; 1125 // Track the register number defed in Copy. 1126 SmallVector<unsigned, 2> DefedRegsInCopy; 1127 1128 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching 1129 // for DBG_VALUEs later, record them when they're encountered. 1130 if (MI->isDebugValue()) { 1131 auto &MO = MI->getOperand(0); 1132 if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) { 1133 // Bail if we can already tell the sink would be rejected, rather 1134 // than needlessly accumulating lots of DBG_VALUEs. 1135 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy, 1136 ModifiedRegUnits, UsedRegUnits)) 1137 continue; 1138 1139 // Record debug use of this register. 1140 SeenDbgInstrs[MO.getReg()].push_back(MI); 1141 } 1142 continue; 1143 } 1144 1145 if (MI->isDebugInstr()) 1146 continue; 1147 1148 // Do not move any instruction across function call. 1149 if (MI->isCall()) 1150 return false; 1151 1152 if (!MI->isCopy() || !MI->getOperand(0).isRenamable()) { 1153 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, 1154 TRI); 1155 continue; 1156 } 1157 1158 // Don't sink the COPY if it would violate a register dependency. 1159 if (hasRegisterDependency(MI, UsedOpsInCopy, DefedRegsInCopy, 1160 ModifiedRegUnits, UsedRegUnits)) { 1161 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, 1162 TRI); 1163 continue; 1164 } 1165 assert((!UsedOpsInCopy.empty() && !DefedRegsInCopy.empty()) && 1166 "Unexpect SrcReg or DefReg"); 1167 MachineBasicBlock *SuccBB = 1168 getSingleLiveInSuccBB(CurBB, SinkableBBs, DefedRegsInCopy, TRI); 1169 // Don't sink if we cannot find a single sinkable successor in which Reg 1170 // is live-in. 1171 if (!SuccBB) { 1172 LiveRegUnits::accumulateUsedDefed(*MI, ModifiedRegUnits, UsedRegUnits, 1173 TRI); 1174 continue; 1175 } 1176 assert((SuccBB->pred_size() == 1 && *SuccBB->pred_begin() == &CurBB) && 1177 "Unexpected predecessor"); 1178 1179 // Collect DBG_VALUEs that must sink with this copy. 1180 SmallVector<MachineInstr *, 4> DbgValsToSink; 1181 for (auto &MO : MI->operands()) { 1182 if (!MO.isReg() || !MO.isDef()) 1183 continue; 1184 unsigned reg = MO.getReg(); 1185 for (auto *MI : SeenDbgInstrs.lookup(reg)) 1186 DbgValsToSink.push_back(MI); 1187 } 1188 1189 // Clear the kill flag if SrcReg is killed between MI and the end of the 1190 // block. 1191 clearKillFlags(MI, CurBB, UsedOpsInCopy, UsedRegUnits, TRI); 1192 MachineBasicBlock::iterator InsertPos = SuccBB->getFirstNonPHI(); 1193 performSink(*MI, *SuccBB, InsertPos, &DbgValsToSink); 1194 updateLiveIn(MI, SuccBB, UsedOpsInCopy, DefedRegsInCopy); 1195 1196 Changed = true; 1197 ++NumPostRACopySink; 1198 } 1199 return Changed; 1200 } 1201 1202 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction &MF) { 1203 if (skipFunction(MF.getFunction())) 1204 return false; 1205 1206 bool Changed = false; 1207 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 1208 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1209 1210 ModifiedRegUnits.init(*TRI); 1211 UsedRegUnits.init(*TRI); 1212 for (auto &BB : MF) 1213 Changed |= tryToSinkCopy(BB, MF, TRI, TII); 1214 1215 return Changed; 1216 } 1217