1 //===- MachineSink.cpp - Sinking for machine instructions -----------------===//
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
7 //===----------------------------------------------------------------------===//
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.
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.
16 //===----------------------------------------------------------------------===//
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/DebugInfoMetadata.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/BranchProbability.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
56 #define DEBUG_TYPE "machine-sink"
59 SplitEdges("machine-sink-split",
60 cl::desc("Split critical edges during machine sinking"),
61 cl::init(true), cl::Hidden
);
64 UseBlockFreqInfo("machine-sink-bfi",
65 cl::desc("Use block frequency info to find successors to sink"),
66 cl::init(true), cl::Hidden
);
68 static cl::opt
<unsigned> SplitEdgeProbabilityThreshold(
69 "machine-sink-split-probability-threshold",
71 "Percentage threshold for splitting single-instruction critical edge. "
72 "If the branch threshold is higher than this threshold, we allow "
73 "speculative execution of up to 1 instruction to avoid branching to "
74 "splitted critical edge"),
75 cl::init(40), cl::Hidden
);
77 STATISTIC(NumSunk
, "Number of machine instructions sunk");
78 STATISTIC(NumSplit
, "Number of critical edges split");
79 STATISTIC(NumCoalesces
, "Number of copies coalesced");
80 STATISTIC(NumPostRACopySink
, "Number of copies sunk after RA");
84 class MachineSinking
: public MachineFunctionPass
{
85 const TargetInstrInfo
*TII
;
86 const TargetRegisterInfo
*TRI
;
87 MachineRegisterInfo
*MRI
; // Machine register information
88 MachineDominatorTree
*DT
; // Machine dominator tree
89 MachinePostDominatorTree
*PDT
; // Machine post dominator tree
91 const MachineBlockFrequencyInfo
*MBFI
;
92 const MachineBranchProbabilityInfo
*MBPI
;
95 // Remember which edges have been considered for breaking.
96 SmallSet
<std::pair
<MachineBasicBlock
*, MachineBasicBlock
*>, 8>
98 // Remember which edges we are about to split.
99 // This is different from CEBCandidates since those edges
101 SetVector
<std::pair
<MachineBasicBlock
*, MachineBasicBlock
*>> ToSplit
;
103 SparseBitVector
<> RegsToClearKillFlags
;
105 using AllSuccsCache
=
106 std::map
<MachineBasicBlock
*, SmallVector
<MachineBasicBlock
*, 4>>;
109 static char ID
; // Pass identification
111 MachineSinking() : MachineFunctionPass(ID
) {
112 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
115 bool runOnMachineFunction(MachineFunction
&MF
) override
;
117 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
118 AU
.setPreservesCFG();
119 MachineFunctionPass::getAnalysisUsage(AU
);
120 AU
.addRequired
<AAResultsWrapperPass
>();
121 AU
.addRequired
<MachineDominatorTree
>();
122 AU
.addRequired
<MachinePostDominatorTree
>();
123 AU
.addRequired
<MachineLoopInfo
>();
124 AU
.addRequired
<MachineBranchProbabilityInfo
>();
125 AU
.addPreserved
<MachineDominatorTree
>();
126 AU
.addPreserved
<MachinePostDominatorTree
>();
127 AU
.addPreserved
<MachineLoopInfo
>();
128 if (UseBlockFreqInfo
)
129 AU
.addRequired
<MachineBlockFrequencyInfo
>();
132 void releaseMemory() override
{
133 CEBCandidates
.clear();
137 bool ProcessBlock(MachineBasicBlock
&MBB
);
138 bool isWorthBreakingCriticalEdge(MachineInstr
&MI
,
139 MachineBasicBlock
*From
,
140 MachineBasicBlock
*To
);
142 /// Postpone the splitting of the given critical
143 /// edge (\p From, \p To).
145 /// We do not split the edges on the fly. Indeed, this invalidates
146 /// the dominance information and thus triggers a lot of updates
147 /// of that information underneath.
148 /// Instead, we postpone all the splits after each iteration of
149 /// the main loop. That way, the information is at least valid
150 /// for the lifetime of an iteration.
152 /// \return True if the edge is marked as toSplit, false otherwise.
153 /// False can be returned if, for instance, this is not profitable.
154 bool PostponeSplitCriticalEdge(MachineInstr
&MI
,
155 MachineBasicBlock
*From
,
156 MachineBasicBlock
*To
,
158 bool SinkInstruction(MachineInstr
&MI
, bool &SawStore
,
160 AllSuccsCache
&AllSuccessors
);
161 bool AllUsesDominatedByBlock(unsigned Reg
, MachineBasicBlock
*MBB
,
162 MachineBasicBlock
*DefMBB
,
163 bool &BreakPHIEdge
, bool &LocalUse
) const;
164 MachineBasicBlock
*FindSuccToSinkTo(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
165 bool &BreakPHIEdge
, AllSuccsCache
&AllSuccessors
);
166 bool isProfitableToSinkTo(unsigned Reg
, MachineInstr
&MI
,
167 MachineBasicBlock
*MBB
,
168 MachineBasicBlock
*SuccToSinkTo
,
169 AllSuccsCache
&AllSuccessors
);
171 bool PerformTrivialForwardCoalescing(MachineInstr
&MI
,
172 MachineBasicBlock
*MBB
);
174 SmallVector
<MachineBasicBlock
*, 4> &
175 GetAllSortedSuccessors(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
176 AllSuccsCache
&AllSuccessors
) const;
179 } // end anonymous namespace
181 char MachineSinking::ID
= 0;
183 char &llvm::MachineSinkingID
= MachineSinking::ID
;
185 INITIALIZE_PASS_BEGIN(MachineSinking
, DEBUG_TYPE
,
186 "Machine code sinking", false, false)
187 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo
)
188 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
189 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
190 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
191 INITIALIZE_PASS_END(MachineSinking
, DEBUG_TYPE
,
192 "Machine code sinking", false, false)
194 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr
&MI
,
195 MachineBasicBlock
*MBB
) {
199 Register SrcReg
= MI
.getOperand(1).getReg();
200 Register DstReg
= MI
.getOperand(0).getReg();
201 if (!Register::isVirtualRegister(SrcReg
) ||
202 !Register::isVirtualRegister(DstReg
) || !MRI
->hasOneNonDBGUse(SrcReg
))
205 const TargetRegisterClass
*SRC
= MRI
->getRegClass(SrcReg
);
206 const TargetRegisterClass
*DRC
= MRI
->getRegClass(DstReg
);
210 MachineInstr
*DefMI
= MRI
->getVRegDef(SrcReg
);
211 if (DefMI
->isCopyLike())
213 LLVM_DEBUG(dbgs() << "Coalescing: " << *DefMI
);
214 LLVM_DEBUG(dbgs() << "*** to: " << MI
);
215 MRI
->replaceRegWith(DstReg
, SrcReg
);
216 MI
.eraseFromParent();
218 // Conservatively, clear any kill flags, since it's possible that they are no
220 MRI
->clearKillFlags(SrcReg
);
226 /// AllUsesDominatedByBlock - Return true if all uses of the specified register
227 /// occur in blocks dominated by the specified block. If any use is in the
228 /// definition block, then return false since it is never legal to move def
231 MachineSinking::AllUsesDominatedByBlock(unsigned Reg
,
232 MachineBasicBlock
*MBB
,
233 MachineBasicBlock
*DefMBB
,
235 bool &LocalUse
) const {
236 assert(Register::isVirtualRegister(Reg
) && "Only makes sense for vregs");
238 // Ignore debug uses because debug info doesn't affect the code.
239 if (MRI
->use_nodbg_empty(Reg
))
242 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
243 // into and they are all PHI nodes. In this case, machine-sink must break
244 // the critical edge first. e.g.
246 // %bb.1: derived from LLVM BB %bb4.preheader
247 // Predecessors according to CFG: %bb.0
249 // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
251 // JE_4 <%bb.37>, implicit %eflags
252 // Successors according to CFG: %bb.37 %bb.2
254 // %bb.2: derived from LLVM BB %bb.nph
255 // Predecessors according to CFG: %bb.0 %bb.1
256 // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
258 for (MachineOperand
&MO
: MRI
->use_nodbg_operands(Reg
)) {
259 MachineInstr
*UseInst
= MO
.getParent();
260 unsigned OpNo
= &MO
- &UseInst
->getOperand(0);
261 MachineBasicBlock
*UseBlock
= UseInst
->getParent();
262 if (!(UseBlock
== MBB
&& UseInst
->isPHI() &&
263 UseInst
->getOperand(OpNo
+1).getMBB() == DefMBB
)) {
264 BreakPHIEdge
= false;
271 for (MachineOperand
&MO
: MRI
->use_nodbg_operands(Reg
)) {
272 // Determine the block of the use.
273 MachineInstr
*UseInst
= MO
.getParent();
274 unsigned OpNo
= &MO
- &UseInst
->getOperand(0);
275 MachineBasicBlock
*UseBlock
= UseInst
->getParent();
276 if (UseInst
->isPHI()) {
277 // PHI nodes use the operand in the predecessor block, not the block with
279 UseBlock
= UseInst
->getOperand(OpNo
+1).getMBB();
280 } else if (UseBlock
== DefMBB
) {
285 // Check that it dominates.
286 if (!DT
->dominates(MBB
, UseBlock
))
293 bool MachineSinking::runOnMachineFunction(MachineFunction
&MF
) {
294 if (skipFunction(MF
.getFunction()))
297 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
299 TII
= MF
.getSubtarget().getInstrInfo();
300 TRI
= MF
.getSubtarget().getRegisterInfo();
301 MRI
= &MF
.getRegInfo();
302 DT
= &getAnalysis
<MachineDominatorTree
>();
303 PDT
= &getAnalysis
<MachinePostDominatorTree
>();
304 LI
= &getAnalysis
<MachineLoopInfo
>();
305 MBFI
= UseBlockFreqInfo
? &getAnalysis
<MachineBlockFrequencyInfo
>() : nullptr;
306 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
307 AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
309 bool EverMadeChange
= false;
312 bool MadeChange
= false;
314 // Process all basic blocks.
315 CEBCandidates
.clear();
318 MadeChange
|= ProcessBlock(MBB
);
320 // If we have anything we marked as toSplit, split it now.
321 for (auto &Pair
: ToSplit
) {
322 auto NewSucc
= Pair
.first
->SplitCriticalEdge(Pair
.second
, *this);
323 if (NewSucc
!= nullptr) {
324 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
325 << printMBBReference(*Pair
.first
) << " -- "
326 << printMBBReference(*NewSucc
) << " -- "
327 << printMBBReference(*Pair
.second
) << '\n');
331 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
333 // If this iteration over the code changed anything, keep iterating.
334 if (!MadeChange
) break;
335 EverMadeChange
= true;
338 // Now clear any kill flags for recorded registers.
339 for (auto I
: RegsToClearKillFlags
)
340 MRI
->clearKillFlags(I
);
341 RegsToClearKillFlags
.clear();
343 return EverMadeChange
;
346 bool MachineSinking::ProcessBlock(MachineBasicBlock
&MBB
) {
347 // Can't sink anything out of a block that has less than two successors.
348 if (MBB
.succ_size() <= 1 || MBB
.empty()) return false;
350 // Don't bother sinking code out of unreachable blocks. In addition to being
351 // unprofitable, it can also lead to infinite looping, because in an
352 // unreachable loop there may be nowhere to stop.
353 if (!DT
->isReachableFromEntry(&MBB
)) return false;
355 bool MadeChange
= false;
357 // Cache all successors, sorted by frequency info and loop depth.
358 AllSuccsCache AllSuccessors
;
360 // Walk the basic block bottom-up. Remember if we saw a store.
361 MachineBasicBlock::iterator I
= MBB
.end();
363 bool ProcessedBegin
, SawStore
= false;
365 MachineInstr
&MI
= *I
; // The instruction to sink.
367 // Predecrement I (if it's not begin) so that it isn't invalidated by
369 ProcessedBegin
= I
== MBB
.begin();
373 if (MI
.isDebugInstr())
376 bool Joined
= PerformTrivialForwardCoalescing(MI
, &MBB
);
382 if (SinkInstruction(MI
, SawStore
, AllSuccessors
)) {
387 // If we just processed the first instruction in the block, we're done.
388 } while (!ProcessedBegin
);
393 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr
&MI
,
394 MachineBasicBlock
*From
,
395 MachineBasicBlock
*To
) {
396 // FIXME: Need much better heuristics.
398 // If the pass has already considered breaking this edge (during this pass
399 // through the function), then let's go ahead and break it. This means
400 // sinking multiple "cheap" instructions into the same block.
401 if (!CEBCandidates
.insert(std::make_pair(From
, To
)).second
)
404 if (!MI
.isCopy() && !TII
->isAsCheapAsAMove(MI
))
407 if (From
->isSuccessor(To
) && MBPI
->getEdgeProbability(From
, To
) <=
408 BranchProbability(SplitEdgeProbabilityThreshold
, 100))
411 // MI is cheap, we probably don't want to break the critical edge for it.
412 // However, if this would allow some definitions of its source operands
413 // to be sunk then it's probably worth it.
414 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
415 const MachineOperand
&MO
= MI
.getOperand(i
);
416 if (!MO
.isReg() || !MO
.isUse())
418 Register Reg
= MO
.getReg();
422 // We don't move live definitions of physical registers,
423 // so sinking their uses won't enable any opportunities.
424 if (Register::isPhysicalRegister(Reg
))
427 // If this instruction is the only user of a virtual register,
428 // check if breaking the edge will enable sinking
429 // both this instruction and the defining instruction.
430 if (MRI
->hasOneNonDBGUse(Reg
)) {
431 // If the definition resides in same MBB,
432 // claim it's likely we can sink these together.
433 // If definition resides elsewhere, we aren't
434 // blocking it from being sunk so don't break the edge.
435 MachineInstr
*DefMI
= MRI
->getVRegDef(Reg
);
436 if (DefMI
->getParent() == MI
.getParent())
444 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr
&MI
,
445 MachineBasicBlock
*FromBB
,
446 MachineBasicBlock
*ToBB
,
448 if (!isWorthBreakingCriticalEdge(MI
, FromBB
, ToBB
))
451 // Avoid breaking back edge. From == To means backedge for single BB loop.
452 if (!SplitEdges
|| FromBB
== ToBB
)
455 // Check for backedges of more "complex" loops.
456 if (LI
->getLoopFor(FromBB
) == LI
->getLoopFor(ToBB
) &&
457 LI
->isLoopHeader(ToBB
))
460 // It's not always legal to break critical edges and sink the computation
468 // ... no uses of v1024
474 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
483 // ... no uses of v1024
489 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
490 // flow. We need to ensure the new basic block where the computation is
491 // sunk to dominates all the uses.
492 // It's only legal to break critical edge and sink the computation to the
493 // new block if all the predecessors of "To", except for "From", are
494 // not dominated by "From". Given SSA property, this means these
495 // predecessors are dominated by "To".
497 // There is no need to do this check if all the uses are PHI nodes. PHI
498 // sources are only defined on the specific predecessor edges.
500 for (MachineBasicBlock::pred_iterator PI
= ToBB
->pred_begin(),
501 E
= ToBB
->pred_end(); PI
!= E
; ++PI
) {
504 if (!DT
->dominates(ToBB
, *PI
))
509 ToSplit
.insert(std::make_pair(FromBB
, ToBB
));
514 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
515 bool MachineSinking::isProfitableToSinkTo(unsigned Reg
, MachineInstr
&MI
,
516 MachineBasicBlock
*MBB
,
517 MachineBasicBlock
*SuccToSinkTo
,
518 AllSuccsCache
&AllSuccessors
) {
519 assert (SuccToSinkTo
&& "Invalid SinkTo Candidate BB");
521 if (MBB
== SuccToSinkTo
)
524 // It is profitable if SuccToSinkTo does not post dominate current block.
525 if (!PDT
->dominates(SuccToSinkTo
, MBB
))
528 // It is profitable to sink an instruction from a deeper loop to a shallower
529 // loop, even if the latter post-dominates the former (PR21115).
530 if (LI
->getLoopDepth(MBB
) > LI
->getLoopDepth(SuccToSinkTo
))
533 // Check if only use in post dominated block is PHI instruction.
534 bool NonPHIUse
= false;
535 for (MachineInstr
&UseInst
: MRI
->use_nodbg_instructions(Reg
)) {
536 MachineBasicBlock
*UseBlock
= UseInst
.getParent();
537 if (UseBlock
== SuccToSinkTo
&& !UseInst
.isPHI())
543 // If SuccToSinkTo post dominates then also it may be profitable if MI
544 // can further profitably sinked into another block in next round.
545 bool BreakPHIEdge
= false;
546 // FIXME - If finding successor is compile time expensive then cache results.
547 if (MachineBasicBlock
*MBB2
=
548 FindSuccToSinkTo(MI
, SuccToSinkTo
, BreakPHIEdge
, AllSuccessors
))
549 return isProfitableToSinkTo(Reg
, MI
, SuccToSinkTo
, MBB2
, AllSuccessors
);
551 // If SuccToSinkTo is final destination and it is a post dominator of current
552 // block then it is not profitable to sink MI into SuccToSinkTo block.
556 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
557 /// computing it if it was not already cached.
558 SmallVector
<MachineBasicBlock
*, 4> &
559 MachineSinking::GetAllSortedSuccessors(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
560 AllSuccsCache
&AllSuccessors
) const {
561 // Do we have the sorted successors in cache ?
562 auto Succs
= AllSuccessors
.find(MBB
);
563 if (Succs
!= AllSuccessors
.end())
564 return Succs
->second
;
566 SmallVector
<MachineBasicBlock
*, 4> AllSuccs(MBB
->succ_begin(),
569 // Handle cases where sinking can happen but where the sink point isn't a
570 // successor. For example:
576 const std::vector
<MachineDomTreeNode
*> &Children
=
577 DT
->getNode(MBB
)->getChildren();
578 for (const auto &DTChild
: Children
)
579 // DomTree children of MBB that have MBB as immediate dominator are added.
580 if (DTChild
->getIDom()->getBlock() == MI
.getParent() &&
581 // Skip MBBs already added to the AllSuccs vector above.
582 !MBB
->isSuccessor(DTChild
->getBlock()))
583 AllSuccs
.push_back(DTChild
->getBlock());
585 // Sort Successors according to their loop depth or block frequency info.
587 AllSuccs
, [this](const MachineBasicBlock
*L
, const MachineBasicBlock
*R
) {
588 uint64_t LHSFreq
= MBFI
? MBFI
->getBlockFreq(L
).getFrequency() : 0;
589 uint64_t RHSFreq
= MBFI
? MBFI
->getBlockFreq(R
).getFrequency() : 0;
590 bool HasBlockFreq
= LHSFreq
!= 0 && RHSFreq
!= 0;
591 return HasBlockFreq
? LHSFreq
< RHSFreq
592 : LI
->getLoopDepth(L
) < LI
->getLoopDepth(R
);
595 auto it
= AllSuccessors
.insert(std::make_pair(MBB
, AllSuccs
));
597 return it
.first
->second
;
600 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
602 MachineSinking::FindSuccToSinkTo(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
604 AllSuccsCache
&AllSuccessors
) {
605 assert (MBB
&& "Invalid MachineBasicBlock!");
607 // Loop over all the operands of the specified instruction. If there is
608 // anything we can't handle, bail out.
610 // SuccToSinkTo - This is the successor to sink this instruction to, once we
612 MachineBasicBlock
*SuccToSinkTo
= nullptr;
613 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
614 const MachineOperand
&MO
= MI
.getOperand(i
);
615 if (!MO
.isReg()) continue; // Ignore non-register operands.
617 Register Reg
= MO
.getReg();
618 if (Reg
== 0) continue;
620 if (Register::isPhysicalRegister(Reg
)) {
622 // If the physreg has no defs anywhere, it's just an ambient register
623 // and we can freely move its uses. Alternatively, if it's allocatable,
624 // it could get allocated to something with a def during allocation.
625 if (!MRI
->isConstantPhysReg(Reg
))
627 } else if (!MO
.isDead()) {
628 // A def that isn't dead. We can't move it.
632 // Virtual register uses are always safe to sink.
633 if (MO
.isUse()) continue;
635 // If it's not safe to move defs of the register class, then abort.
636 if (!TII
->isSafeToMoveRegClassDefs(MRI
->getRegClass(Reg
)))
639 // Virtual register defs can only be sunk if all their uses are in blocks
640 // dominated by one of the successors.
642 // If a previous operand picked a block to sink to, then this operand
643 // must be sinkable to the same block.
644 bool LocalUse
= false;
645 if (!AllUsesDominatedByBlock(Reg
, SuccToSinkTo
, MBB
,
646 BreakPHIEdge
, LocalUse
))
652 // Otherwise, we should look at all the successors and decide which one
653 // we should sink to. If we have reliable block frequency information
654 // (frequency != 0) available, give successors with smaller frequencies
655 // higher priority, otherwise prioritize smaller loop depths.
656 for (MachineBasicBlock
*SuccBlock
:
657 GetAllSortedSuccessors(MI
, MBB
, AllSuccessors
)) {
658 bool LocalUse
= false;
659 if (AllUsesDominatedByBlock(Reg
, SuccBlock
, MBB
,
660 BreakPHIEdge
, LocalUse
)) {
661 SuccToSinkTo
= SuccBlock
;
665 // Def is used locally, it's never safe to move this def.
669 // If we couldn't find a block to sink to, ignore this instruction.
672 if (!isProfitableToSinkTo(Reg
, MI
, MBB
, SuccToSinkTo
, AllSuccessors
))
677 // It is not possible to sink an instruction into its own block. This can
678 // happen with loops.
679 if (MBB
== SuccToSinkTo
)
682 // It's not safe to sink instructions to EH landing pad. Control flow into
683 // landing pad is implicitly defined.
684 if (SuccToSinkTo
&& SuccToSinkTo
->isEHPad())
690 /// Return true if MI is likely to be usable as a memory operation by the
691 /// implicit null check optimization.
693 /// This is a "best effort" heuristic, and should not be relied upon for
694 /// correctness. This returning true does not guarantee that the implicit null
695 /// check optimization is legal over MI, and this returning false does not
696 /// guarantee MI cannot possibly be used to do a null check.
697 static bool SinkingPreventsImplicitNullCheck(MachineInstr
&MI
,
698 const TargetInstrInfo
*TII
,
699 const TargetRegisterInfo
*TRI
) {
700 using MachineBranchPredicate
= TargetInstrInfo::MachineBranchPredicate
;
702 auto *MBB
= MI
.getParent();
703 if (MBB
->pred_size() != 1)
706 auto *PredMBB
= *MBB
->pred_begin();
707 auto *PredBB
= PredMBB
->getBasicBlock();
709 // Frontends that don't use implicit null checks have no reason to emit
710 // branches with make.implicit metadata, and this function should always
711 // return false for them.
713 !PredBB
->getTerminator()->getMetadata(LLVMContext::MD_make_implicit
))
716 const MachineOperand
*BaseOp
;
718 if (!TII
->getMemOperandWithOffset(MI
, BaseOp
, Offset
, TRI
))
721 if (!BaseOp
->isReg())
724 if (!(MI
.mayLoad() && !MI
.isPredicable()))
727 MachineBranchPredicate MBP
;
728 if (TII
->analyzeBranchPredicate(*PredMBB
, MBP
, false))
731 return MBP
.LHS
.isReg() && MBP
.RHS
.isImm() && MBP
.RHS
.getImm() == 0 &&
732 (MBP
.Predicate
== MachineBranchPredicate::PRED_NE
||
733 MBP
.Predicate
== MachineBranchPredicate::PRED_EQ
) &&
734 MBP
.LHS
.getReg() == BaseOp
->getReg();
737 /// Sink an instruction and its associated debug instructions. If the debug
738 /// instructions to be sunk are already known, they can be provided in DbgVals.
739 static void performSink(MachineInstr
&MI
, MachineBasicBlock
&SuccToSinkTo
,
740 MachineBasicBlock::iterator InsertPos
,
741 SmallVectorImpl
<MachineInstr
*> *DbgVals
= nullptr) {
742 // If debug values are provided use those, otherwise call collectDebugValues.
743 SmallVector
<MachineInstr
*, 2> DbgValuesToSink
;
745 DbgValuesToSink
.insert(DbgValuesToSink
.begin(),
746 DbgVals
->begin(), DbgVals
->end());
748 MI
.collectDebugValues(DbgValuesToSink
);
750 // If we cannot find a location to use (merge with), then we erase the debug
751 // location to prevent debug-info driven tools from potentially reporting
752 // wrong location information.
753 if (!SuccToSinkTo
.empty() && InsertPos
!= SuccToSinkTo
.end())
754 MI
.setDebugLoc(DILocation::getMergedLocation(MI
.getDebugLoc(),
755 InsertPos
->getDebugLoc()));
757 MI
.setDebugLoc(DebugLoc());
759 // Move the instruction.
760 MachineBasicBlock
*ParentBlock
= MI
.getParent();
761 SuccToSinkTo
.splice(InsertPos
, ParentBlock
, MI
,
762 ++MachineBasicBlock::iterator(MI
));
764 // Move previously adjacent debug value instructions to the insert position.
765 for (SmallVectorImpl
<MachineInstr
*>::iterator DBI
= DbgValuesToSink
.begin(),
766 DBE
= DbgValuesToSink
.end();
768 MachineInstr
*DbgMI
= *DBI
;
769 SuccToSinkTo
.splice(InsertPos
, ParentBlock
, DbgMI
,
770 ++MachineBasicBlock::iterator(DbgMI
));
774 /// SinkInstruction - Determine whether it is safe to sink the specified machine
775 /// instruction out of its current block into a successor.
776 bool MachineSinking::SinkInstruction(MachineInstr
&MI
, bool &SawStore
,
777 AllSuccsCache
&AllSuccessors
) {
778 // Don't sink instructions that the target prefers not to sink.
779 if (!TII
->shouldSink(MI
))
782 // Check if it's safe to move the instruction.
783 if (!MI
.isSafeToMove(AA
, SawStore
))
786 // Convergent operations may not be made control-dependent on additional
788 if (MI
.isConvergent())
791 // Don't break implicit null checks. This is a performance heuristic, and not
792 // required for correctness.
793 if (SinkingPreventsImplicitNullCheck(MI
, TII
, TRI
))
796 // FIXME: This should include support for sinking instructions within the
797 // block they are currently in to shorten the live ranges. We often get
798 // instructions sunk into the top of a large block, but it would be better to
799 // also sink them down before their first use in the block. This xform has to
800 // be careful not to *increase* register pressure though, e.g. sinking
801 // "x = y + z" down if it kills y and z would increase the live ranges of y
802 // and z and only shrink the live range of x.
804 bool BreakPHIEdge
= false;
805 MachineBasicBlock
*ParentBlock
= MI
.getParent();
806 MachineBasicBlock
*SuccToSinkTo
=
807 FindSuccToSinkTo(MI
, ParentBlock
, BreakPHIEdge
, AllSuccessors
);
809 // If there are no outputs, it must have side-effects.
813 // If the instruction to move defines a dead physical register which is live
814 // when leaving the basic block, don't move it because it could turn into a
815 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
816 for (unsigned I
= 0, E
= MI
.getNumOperands(); I
!= E
; ++I
) {
817 const MachineOperand
&MO
= MI
.getOperand(I
);
818 if (!MO
.isReg()) continue;
819 Register Reg
= MO
.getReg();
820 if (Reg
== 0 || !Register::isPhysicalRegister(Reg
))
822 if (SuccToSinkTo
->isLiveIn(Reg
))
826 LLVM_DEBUG(dbgs() << "Sink instr " << MI
<< "\tinto block " << *SuccToSinkTo
);
828 // If the block has multiple predecessors, this is a critical edge.
829 // Decide if we can sink along it or need to break the edge.
830 if (SuccToSinkTo
->pred_size() > 1) {
831 // We cannot sink a load across a critical edge - there may be stores in
833 bool TryBreak
= false;
835 if (!MI
.isSafeToMove(AA
, store
)) {
836 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
840 // We don't want to sink across a critical edge if we don't dominate the
841 // successor. We could be introducing calculations to new code paths.
842 if (!TryBreak
&& !DT
->dominates(ParentBlock
, SuccToSinkTo
)) {
843 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
847 // Don't sink instructions into a loop.
848 if (!TryBreak
&& LI
->isLoopHeader(SuccToSinkTo
)) {
849 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
853 // Otherwise we are OK with sinking along a critical edge.
855 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
857 // Mark this edge as to be split.
858 // If the edge can actually be split, the next iteration of the main loop
859 // will sink MI in the newly created block.
861 PostponeSplitCriticalEdge(MI
, ParentBlock
, SuccToSinkTo
, BreakPHIEdge
);
863 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
864 "break critical edge\n");
865 // The instruction will not be sunk this time.
871 // BreakPHIEdge is true if all the uses are in the successor MBB being
872 // sunken into and they are all PHI nodes. In this case, machine-sink must
873 // break the critical edge first.
874 bool Status
= PostponeSplitCriticalEdge(MI
, ParentBlock
,
875 SuccToSinkTo
, BreakPHIEdge
);
877 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
878 "break critical edge\n");
879 // The instruction will not be sunk this time.
883 // Determine where to insert into. Skip phi nodes.
884 MachineBasicBlock::iterator InsertPos
= SuccToSinkTo
->begin();
885 while (InsertPos
!= SuccToSinkTo
->end() && InsertPos
->isPHI())
888 performSink(MI
, *SuccToSinkTo
, InsertPos
);
890 // Conservatively, clear any kill flags, since it's possible that they are no
892 // Note that we have to clear the kill flags for any register this instruction
893 // uses as we may sink over another instruction which currently kills the
895 for (MachineOperand
&MO
: MI
.operands()) {
896 if (MO
.isReg() && MO
.isUse())
897 RegsToClearKillFlags
.set(MO
.getReg()); // Remember to clear kill flags.
903 //===----------------------------------------------------------------------===//
904 // This pass is not intended to be a replacement or a complete alternative
905 // for the pre-ra machine sink pass. It is only designed to sink COPY
906 // instructions which should be handled after RA.
908 // This pass sinks COPY instructions into a successor block, if the COPY is not
909 // used in the current block and the COPY is live-in to a single successor
910 // (i.e., doesn't require the COPY to be duplicated). This avoids executing the
911 // copy on paths where their results aren't needed. This also exposes
912 // additional opportunites for dead copy elimination and shrink wrapping.
914 // These copies were either not handled by or are inserted after the MachineSink
915 // pass. As an example of the former case, the MachineSink pass cannot sink
916 // COPY instructions with allocatable source registers; for AArch64 these type
917 // of copy instructions are frequently used to move function parameters (PhyReg)
918 // into virtual registers in the entry block.
920 // For the machine IR below, this pass will sink %w19 in the entry into its
921 // successor (%bb.1) because %w19 is only live-in in %bb.1.
923 // %wzr = SUBSWri %w1, 1
929 // %w0 = ADDWrr %w0, %w19
934 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
935 // able to see %bb.0 as a candidate.
936 //===----------------------------------------------------------------------===//
939 class PostRAMachineSinking
: public MachineFunctionPass
{
941 bool runOnMachineFunction(MachineFunction
&MF
) override
;
944 PostRAMachineSinking() : MachineFunctionPass(ID
) {}
945 StringRef
getPassName() const override
{ return "PostRA Machine Sink"; }
947 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
948 AU
.setPreservesCFG();
949 MachineFunctionPass::getAnalysisUsage(AU
);
952 MachineFunctionProperties
getRequiredProperties() const override
{
953 return MachineFunctionProperties().set(
954 MachineFunctionProperties::Property::NoVRegs
);
958 /// Track which register units have been modified and used.
959 LiveRegUnits ModifiedRegUnits
, UsedRegUnits
;
961 /// Track DBG_VALUEs of (unmodified) register units. Each DBG_VALUE has an
962 /// entry in this map for each unit it touches.
963 DenseMap
<unsigned, TinyPtrVector
<MachineInstr
*>> SeenDbgInstrs
;
965 /// Sink Copy instructions unused in the same block close to their uses in
967 bool tryToSinkCopy(MachineBasicBlock
&BB
, MachineFunction
&MF
,
968 const TargetRegisterInfo
*TRI
, const TargetInstrInfo
*TII
);
972 char PostRAMachineSinking::ID
= 0;
973 char &llvm::PostRAMachineSinkingID
= PostRAMachineSinking::ID
;
975 INITIALIZE_PASS(PostRAMachineSinking
, "postra-machine-sink",
976 "PostRA Machine Sink", false, false)
978 static bool aliasWithRegsInLiveIn(MachineBasicBlock
&MBB
, unsigned Reg
,
979 const TargetRegisterInfo
*TRI
) {
980 LiveRegUnits
LiveInRegUnits(*TRI
);
981 LiveInRegUnits
.addLiveIns(MBB
);
982 return !LiveInRegUnits
.available(Reg
);
985 static MachineBasicBlock
*
986 getSingleLiveInSuccBB(MachineBasicBlock
&CurBB
,
987 const SmallPtrSetImpl
<MachineBasicBlock
*> &SinkableBBs
,
988 unsigned Reg
, const TargetRegisterInfo
*TRI
) {
989 // Try to find a single sinkable successor in which Reg is live-in.
990 MachineBasicBlock
*BB
= nullptr;
991 for (auto *SI
: SinkableBBs
) {
992 if (aliasWithRegsInLiveIn(*SI
, Reg
, TRI
)) {
993 // If BB is set here, Reg is live-in to at least two sinkable successors,
1000 // Reg is not live-in to any sinkable successors.
1004 // Check if any register aliased with Reg is live-in in other successors.
1005 for (auto *SI
: CurBB
.successors()) {
1006 if (!SinkableBBs
.count(SI
) && aliasWithRegsInLiveIn(*SI
, Reg
, TRI
))
1012 static MachineBasicBlock
*
1013 getSingleLiveInSuccBB(MachineBasicBlock
&CurBB
,
1014 const SmallPtrSetImpl
<MachineBasicBlock
*> &SinkableBBs
,
1015 ArrayRef
<unsigned> DefedRegsInCopy
,
1016 const TargetRegisterInfo
*TRI
) {
1017 MachineBasicBlock
*SingleBB
= nullptr;
1018 for (auto DefReg
: DefedRegsInCopy
) {
1019 MachineBasicBlock
*BB
=
1020 getSingleLiveInSuccBB(CurBB
, SinkableBBs
, DefReg
, TRI
);
1021 if (!BB
|| (SingleBB
&& SingleBB
!= BB
))
1028 static void clearKillFlags(MachineInstr
*MI
, MachineBasicBlock
&CurBB
,
1029 SmallVectorImpl
<unsigned> &UsedOpsInCopy
,
1030 LiveRegUnits
&UsedRegUnits
,
1031 const TargetRegisterInfo
*TRI
) {
1032 for (auto U
: UsedOpsInCopy
) {
1033 MachineOperand
&MO
= MI
->getOperand(U
);
1034 Register SrcReg
= MO
.getReg();
1035 if (!UsedRegUnits
.available(SrcReg
)) {
1036 MachineBasicBlock::iterator NI
= std::next(MI
->getIterator());
1037 for (MachineInstr
&UI
: make_range(NI
, CurBB
.end())) {
1038 if (UI
.killsRegister(SrcReg
, TRI
)) {
1039 UI
.clearRegisterKills(SrcReg
, TRI
);
1048 static void updateLiveIn(MachineInstr
*MI
, MachineBasicBlock
*SuccBB
,
1049 SmallVectorImpl
<unsigned> &UsedOpsInCopy
,
1050 SmallVectorImpl
<unsigned> &DefedRegsInCopy
) {
1051 MachineFunction
&MF
= *SuccBB
->getParent();
1052 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1053 for (unsigned DefReg
: DefedRegsInCopy
)
1054 for (MCSubRegIterator
S(DefReg
, TRI
, true); S
.isValid(); ++S
)
1055 SuccBB
->removeLiveIn(*S
);
1056 for (auto U
: UsedOpsInCopy
) {
1057 Register Reg
= MI
->getOperand(U
).getReg();
1058 if (!SuccBB
->isLiveIn(Reg
))
1059 SuccBB
->addLiveIn(Reg
);
1063 static bool hasRegisterDependency(MachineInstr
*MI
,
1064 SmallVectorImpl
<unsigned> &UsedOpsInCopy
,
1065 SmallVectorImpl
<unsigned> &DefedRegsInCopy
,
1066 LiveRegUnits
&ModifiedRegUnits
,
1067 LiveRegUnits
&UsedRegUnits
) {
1068 bool HasRegDependency
= false;
1069 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
1070 MachineOperand
&MO
= MI
->getOperand(i
);
1073 Register Reg
= MO
.getReg();
1077 if (!ModifiedRegUnits
.available(Reg
) || !UsedRegUnits
.available(Reg
)) {
1078 HasRegDependency
= true;
1081 DefedRegsInCopy
.push_back(Reg
);
1083 // FIXME: instead of isUse(), readsReg() would be a better fix here,
1084 // For example, we can ignore modifications in reg with undef. However,
1085 // it's not perfectly clear if skipping the internal read is safe in all
1087 } else if (MO
.isUse()) {
1088 if (!ModifiedRegUnits
.available(Reg
)) {
1089 HasRegDependency
= true;
1092 UsedOpsInCopy
.push_back(i
);
1095 return HasRegDependency
;
1098 static SmallSet
<unsigned, 4> getRegUnits(unsigned Reg
,
1099 const TargetRegisterInfo
*TRI
) {
1100 SmallSet
<unsigned, 4> RegUnits
;
1101 for (auto RI
= MCRegUnitIterator(Reg
, TRI
); RI
.isValid(); ++RI
)
1102 RegUnits
.insert(*RI
);
1106 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock
&CurBB
,
1107 MachineFunction
&MF
,
1108 const TargetRegisterInfo
*TRI
,
1109 const TargetInstrInfo
*TII
) {
1110 SmallPtrSet
<MachineBasicBlock
*, 2> SinkableBBs
;
1111 // FIXME: For now, we sink only to a successor which has a single predecessor
1112 // so that we can directly sink COPY instructions to the successor without
1113 // adding any new block or branch instruction.
1114 for (MachineBasicBlock
*SI
: CurBB
.successors())
1115 if (!SI
->livein_empty() && SI
->pred_size() == 1)
1116 SinkableBBs
.insert(SI
);
1118 if (SinkableBBs
.empty())
1121 bool Changed
= false;
1123 // Track which registers have been modified and used between the end of the
1124 // block and the current instruction.
1125 ModifiedRegUnits
.clear();
1126 UsedRegUnits
.clear();
1127 SeenDbgInstrs
.clear();
1129 for (auto I
= CurBB
.rbegin(), E
= CurBB
.rend(); I
!= E
;) {
1130 MachineInstr
*MI
= &*I
;
1133 // Track the operand index for use in Copy.
1134 SmallVector
<unsigned, 2> UsedOpsInCopy
;
1135 // Track the register number defed in Copy.
1136 SmallVector
<unsigned, 2> DefedRegsInCopy
;
1138 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1139 // for DBG_VALUEs later, record them when they're encountered.
1140 if (MI
->isDebugValue()) {
1141 auto &MO
= MI
->getOperand(0);
1142 if (MO
.isReg() && Register::isPhysicalRegister(MO
.getReg())) {
1143 // Bail if we can already tell the sink would be rejected, rather
1144 // than needlessly accumulating lots of DBG_VALUEs.
1145 if (hasRegisterDependency(MI
, UsedOpsInCopy
, DefedRegsInCopy
,
1146 ModifiedRegUnits
, UsedRegUnits
))
1149 // Record debug use of each reg unit.
1150 SmallSet
<unsigned, 4> Units
= getRegUnits(MO
.getReg(), TRI
);
1151 for (unsigned Reg
: Units
)
1152 SeenDbgInstrs
[Reg
].push_back(MI
);
1157 if (MI
->isDebugInstr())
1160 // Do not move any instruction across function call.
1164 if (!MI
->isCopy() || !MI
->getOperand(0).isRenamable()) {
1165 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1170 // Don't sink the COPY if it would violate a register dependency.
1171 if (hasRegisterDependency(MI
, UsedOpsInCopy
, DefedRegsInCopy
,
1172 ModifiedRegUnits
, UsedRegUnits
)) {
1173 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1177 assert((!UsedOpsInCopy
.empty() && !DefedRegsInCopy
.empty()) &&
1178 "Unexpect SrcReg or DefReg");
1179 MachineBasicBlock
*SuccBB
=
1180 getSingleLiveInSuccBB(CurBB
, SinkableBBs
, DefedRegsInCopy
, TRI
);
1181 // Don't sink if we cannot find a single sinkable successor in which Reg
1184 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1188 assert((SuccBB
->pred_size() == 1 && *SuccBB
->pred_begin() == &CurBB
) &&
1189 "Unexpected predecessor");
1191 // Collect DBG_VALUEs that must sink with this copy. We've previously
1192 // recorded which reg units that DBG_VALUEs read, if this instruction
1193 // writes any of those units then the corresponding DBG_VALUEs must sink.
1194 SetVector
<MachineInstr
*> DbgValsToSinkSet
;
1195 SmallVector
<MachineInstr
*, 4> DbgValsToSink
;
1196 for (auto &MO
: MI
->operands()) {
1197 if (!MO
.isReg() || !MO
.isDef())
1200 SmallSet
<unsigned, 4> Units
= getRegUnits(MO
.getReg(), TRI
);
1201 for (unsigned Reg
: Units
)
1202 for (auto *MI
: SeenDbgInstrs
.lookup(Reg
))
1203 DbgValsToSinkSet
.insert(MI
);
1205 DbgValsToSink
.insert(DbgValsToSink
.begin(), DbgValsToSinkSet
.begin(),
1206 DbgValsToSinkSet
.end());
1208 // Clear the kill flag if SrcReg is killed between MI and the end of the
1210 clearKillFlags(MI
, CurBB
, UsedOpsInCopy
, UsedRegUnits
, TRI
);
1211 MachineBasicBlock::iterator InsertPos
= SuccBB
->getFirstNonPHI();
1212 performSink(*MI
, *SuccBB
, InsertPos
, &DbgValsToSink
);
1213 updateLiveIn(MI
, SuccBB
, UsedOpsInCopy
, DefedRegsInCopy
);
1216 ++NumPostRACopySink
;
1221 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction
&MF
) {
1222 if (skipFunction(MF
.getFunction()))
1225 bool Changed
= false;
1226 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1227 const TargetInstrInfo
*TII
= MF
.getSubtarget().getInstrInfo();
1229 ModifiedRegUnits
.init(*TRI
);
1230 UsedRegUnits
.init(*TRI
);
1232 Changed
|= tryToSinkCopy(BB
, MF
, TRI
, TII
);