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/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"
55 #define DEBUG_TYPE "machine-sink"
58 SplitEdges("machine-sink-split",
59 cl::desc("Split critical edges during machine sinking"),
60 cl::init(true), cl::Hidden
);
63 UseBlockFreqInfo("machine-sink-bfi",
64 cl::desc("Use block frequency info to find successors to sink"),
65 cl::init(true), cl::Hidden
);
67 static cl::opt
<unsigned> SplitEdgeProbabilityThreshold(
68 "machine-sink-split-probability-threshold",
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
);
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");
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
90 const MachineBlockFrequencyInfo
*MBFI
;
91 const MachineBranchProbabilityInfo
*MBPI
;
94 // Remember which edges have been considered for breaking.
95 SmallSet
<std::pair
<MachineBasicBlock
*, MachineBasicBlock
*>, 8>
97 // Remember which edges we are about to split.
98 // This is different from CEBCandidates since those edges
100 SetVector
<std::pair
<MachineBasicBlock
*, MachineBasicBlock
*>> ToSplit
;
102 SparseBitVector
<> RegsToClearKillFlags
;
104 using AllSuccsCache
=
105 std::map
<MachineBasicBlock
*, SmallVector
<MachineBasicBlock
*, 4>>;
108 static char ID
; // Pass identification
110 MachineSinking() : MachineFunctionPass(ID
) {
111 initializeMachineSinkingPass(*PassRegistry::getPassRegistry());
114 bool runOnMachineFunction(MachineFunction
&MF
) override
;
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
>();
131 void releaseMemory() override
{
132 CEBCandidates
.clear();
136 bool ProcessBlock(MachineBasicBlock
&MBB
);
137 bool isWorthBreakingCriticalEdge(MachineInstr
&MI
,
138 MachineBasicBlock
*From
,
139 MachineBasicBlock
*To
);
141 /// Postpone the splitting of the given critical
142 /// edge (\p From, \p To).
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.
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
,
157 bool SinkInstruction(MachineInstr
&MI
, bool &SawStore
,
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
);
170 bool PerformTrivialForwardCoalescing(MachineInstr
&MI
,
171 MachineBasicBlock
*MBB
);
173 SmallVector
<MachineBasicBlock
*, 4> &
174 GetAllSortedSuccessors(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
175 AllSuccsCache
&AllSuccessors
) const;
178 } // end anonymous namespace
180 char MachineSinking::ID
= 0;
182 char &llvm::MachineSinkingID
= MachineSinking::ID
;
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)
193 bool MachineSinking::PerformTrivialForwardCoalescing(MachineInstr
&MI
,
194 MachineBasicBlock
*MBB
) {
198 unsigned SrcReg
= MI
.getOperand(1).getReg();
199 unsigned DstReg
= MI
.getOperand(0).getReg();
200 if (!TargetRegisterInfo::isVirtualRegister(SrcReg
) ||
201 !TargetRegisterInfo::isVirtualRegister(DstReg
) ||
202 !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(TargetRegisterInfo::isVirtualRegister(Reg
) &&
237 "Only makes sense for vregs");
239 // Ignore debug uses because debug info doesn't affect the code.
240 if (MRI
->use_nodbg_empty(Reg
))
243 // BreakPHIEdge is true if all the uses are in the successor MBB being sunken
244 // into and they are all PHI nodes. In this case, machine-sink must break
245 // the critical edge first. e.g.
247 // %bb.1: derived from LLVM BB %bb4.preheader
248 // Predecessors according to CFG: %bb.0
250 // %reg16385 = DEC64_32r %reg16437, implicit-def dead %eflags
252 // JE_4 <%bb.37>, implicit %eflags
253 // Successors according to CFG: %bb.37 %bb.2
255 // %bb.2: derived from LLVM BB %bb.nph
256 // Predecessors according to CFG: %bb.0 %bb.1
257 // %reg16386 = PHI %reg16434, %bb.0, %reg16385, %bb.1
259 for (MachineOperand
&MO
: MRI
->use_nodbg_operands(Reg
)) {
260 MachineInstr
*UseInst
= MO
.getParent();
261 unsigned OpNo
= &MO
- &UseInst
->getOperand(0);
262 MachineBasicBlock
*UseBlock
= UseInst
->getParent();
263 if (!(UseBlock
== MBB
&& UseInst
->isPHI() &&
264 UseInst
->getOperand(OpNo
+1).getMBB() == DefMBB
)) {
265 BreakPHIEdge
= false;
272 for (MachineOperand
&MO
: MRI
->use_nodbg_operands(Reg
)) {
273 // Determine the block of the use.
274 MachineInstr
*UseInst
= MO
.getParent();
275 unsigned OpNo
= &MO
- &UseInst
->getOperand(0);
276 MachineBasicBlock
*UseBlock
= UseInst
->getParent();
277 if (UseInst
->isPHI()) {
278 // PHI nodes use the operand in the predecessor block, not the block with
280 UseBlock
= UseInst
->getOperand(OpNo
+1).getMBB();
281 } else if (UseBlock
== DefMBB
) {
286 // Check that it dominates.
287 if (!DT
->dominates(MBB
, UseBlock
))
294 bool MachineSinking::runOnMachineFunction(MachineFunction
&MF
) {
295 if (skipFunction(MF
.getFunction()))
298 LLVM_DEBUG(dbgs() << "******** Machine Sinking ********\n");
300 TII
= MF
.getSubtarget().getInstrInfo();
301 TRI
= MF
.getSubtarget().getRegisterInfo();
302 MRI
= &MF
.getRegInfo();
303 DT
= &getAnalysis
<MachineDominatorTree
>();
304 PDT
= &getAnalysis
<MachinePostDominatorTree
>();
305 LI
= &getAnalysis
<MachineLoopInfo
>();
306 MBFI
= UseBlockFreqInfo
? &getAnalysis
<MachineBlockFrequencyInfo
>() : nullptr;
307 MBPI
= &getAnalysis
<MachineBranchProbabilityInfo
>();
308 AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
310 bool EverMadeChange
= false;
313 bool MadeChange
= false;
315 // Process all basic blocks.
316 CEBCandidates
.clear();
319 MadeChange
|= ProcessBlock(MBB
);
321 // If we have anything we marked as toSplit, split it now.
322 for (auto &Pair
: ToSplit
) {
323 auto NewSucc
= Pair
.first
->SplitCriticalEdge(Pair
.second
, *this);
324 if (NewSucc
!= nullptr) {
325 LLVM_DEBUG(dbgs() << " *** Splitting critical edge: "
326 << printMBBReference(*Pair
.first
) << " -- "
327 << printMBBReference(*NewSucc
) << " -- "
328 << printMBBReference(*Pair
.second
) << '\n');
332 LLVM_DEBUG(dbgs() << " *** Not legal to break critical edge\n");
334 // If this iteration over the code changed anything, keep iterating.
335 if (!MadeChange
) break;
336 EverMadeChange
= true;
339 // Now clear any kill flags for recorded registers.
340 for (auto I
: RegsToClearKillFlags
)
341 MRI
->clearKillFlags(I
);
342 RegsToClearKillFlags
.clear();
344 return EverMadeChange
;
347 bool MachineSinking::ProcessBlock(MachineBasicBlock
&MBB
) {
348 // Can't sink anything out of a block that has less than two successors.
349 if (MBB
.succ_size() <= 1 || MBB
.empty()) return false;
351 // Don't bother sinking code out of unreachable blocks. In addition to being
352 // unprofitable, it can also lead to infinite looping, because in an
353 // unreachable loop there may be nowhere to stop.
354 if (!DT
->isReachableFromEntry(&MBB
)) return false;
356 bool MadeChange
= false;
358 // Cache all successors, sorted by frequency info and loop depth.
359 AllSuccsCache AllSuccessors
;
361 // Walk the basic block bottom-up. Remember if we saw a store.
362 MachineBasicBlock::iterator I
= MBB
.end();
364 bool ProcessedBegin
, SawStore
= false;
366 MachineInstr
&MI
= *I
; // The instruction to sink.
368 // Predecrement I (if it's not begin) so that it isn't invalidated by
370 ProcessedBegin
= I
== MBB
.begin();
374 if (MI
.isDebugInstr())
377 bool Joined
= PerformTrivialForwardCoalescing(MI
, &MBB
);
383 if (SinkInstruction(MI
, SawStore
, AllSuccessors
)) {
388 // If we just processed the first instruction in the block, we're done.
389 } while (!ProcessedBegin
);
394 bool MachineSinking::isWorthBreakingCriticalEdge(MachineInstr
&MI
,
395 MachineBasicBlock
*From
,
396 MachineBasicBlock
*To
) {
397 // FIXME: Need much better heuristics.
399 // If the pass has already considered breaking this edge (during this pass
400 // through the function), then let's go ahead and break it. This means
401 // sinking multiple "cheap" instructions into the same block.
402 if (!CEBCandidates
.insert(std::make_pair(From
, To
)).second
)
405 if (!MI
.isCopy() && !TII
->isAsCheapAsAMove(MI
))
408 if (From
->isSuccessor(To
) && MBPI
->getEdgeProbability(From
, To
) <=
409 BranchProbability(SplitEdgeProbabilityThreshold
, 100))
412 // MI is cheap, we probably don't want to break the critical edge for it.
413 // However, if this would allow some definitions of its source operands
414 // to be sunk then it's probably worth it.
415 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
416 const MachineOperand
&MO
= MI
.getOperand(i
);
417 if (!MO
.isReg() || !MO
.isUse())
419 unsigned Reg
= MO
.getReg();
423 // We don't move live definitions of physical registers,
424 // so sinking their uses won't enable any opportunities.
425 if (TargetRegisterInfo::isPhysicalRegister(Reg
))
428 // If this instruction is the only user of a virtual register,
429 // check if breaking the edge will enable sinking
430 // both this instruction and the defining instruction.
431 if (MRI
->hasOneNonDBGUse(Reg
)) {
432 // If the definition resides in same MBB,
433 // claim it's likely we can sink these together.
434 // If definition resides elsewhere, we aren't
435 // blocking it from being sunk so don't break the edge.
436 MachineInstr
*DefMI
= MRI
->getVRegDef(Reg
);
437 if (DefMI
->getParent() == MI
.getParent())
445 bool MachineSinking::PostponeSplitCriticalEdge(MachineInstr
&MI
,
446 MachineBasicBlock
*FromBB
,
447 MachineBasicBlock
*ToBB
,
449 if (!isWorthBreakingCriticalEdge(MI
, FromBB
, ToBB
))
452 // Avoid breaking back edge. From == To means backedge for single BB loop.
453 if (!SplitEdges
|| FromBB
== ToBB
)
456 // Check for backedges of more "complex" loops.
457 if (LI
->getLoopFor(FromBB
) == LI
->getLoopFor(ToBB
) &&
458 LI
->isLoopHeader(ToBB
))
461 // It's not always legal to break critical edges and sink the computation
469 // ... no uses of v1024
475 // If %bb.1 -> %bb.3 edge is broken and computation of v1024 is inserted:
484 // ... no uses of v1024
490 // This is incorrect since v1024 is not computed along the %bb.1->%bb.2->%bb.3
491 // flow. We need to ensure the new basic block where the computation is
492 // sunk to dominates all the uses.
493 // It's only legal to break critical edge and sink the computation to the
494 // new block if all the predecessors of "To", except for "From", are
495 // not dominated by "From". Given SSA property, this means these
496 // predecessors are dominated by "To".
498 // There is no need to do this check if all the uses are PHI nodes. PHI
499 // sources are only defined on the specific predecessor edges.
501 for (MachineBasicBlock::pred_iterator PI
= ToBB
->pred_begin(),
502 E
= ToBB
->pred_end(); PI
!= E
; ++PI
) {
505 if (!DT
->dominates(ToBB
, *PI
))
510 ToSplit
.insert(std::make_pair(FromBB
, ToBB
));
515 /// isProfitableToSinkTo - Return true if it is profitable to sink MI.
516 bool MachineSinking::isProfitableToSinkTo(unsigned Reg
, MachineInstr
&MI
,
517 MachineBasicBlock
*MBB
,
518 MachineBasicBlock
*SuccToSinkTo
,
519 AllSuccsCache
&AllSuccessors
) {
520 assert (SuccToSinkTo
&& "Invalid SinkTo Candidate BB");
522 if (MBB
== SuccToSinkTo
)
525 // It is profitable if SuccToSinkTo does not post dominate current block.
526 if (!PDT
->dominates(SuccToSinkTo
, MBB
))
529 // It is profitable to sink an instruction from a deeper loop to a shallower
530 // loop, even if the latter post-dominates the former (PR21115).
531 if (LI
->getLoopDepth(MBB
) > LI
->getLoopDepth(SuccToSinkTo
))
534 // Check if only use in post dominated block is PHI instruction.
535 bool NonPHIUse
= false;
536 for (MachineInstr
&UseInst
: MRI
->use_nodbg_instructions(Reg
)) {
537 MachineBasicBlock
*UseBlock
= UseInst
.getParent();
538 if (UseBlock
== SuccToSinkTo
&& !UseInst
.isPHI())
544 // If SuccToSinkTo post dominates then also it may be profitable if MI
545 // can further profitably sinked into another block in next round.
546 bool BreakPHIEdge
= false;
547 // FIXME - If finding successor is compile time expensive then cache results.
548 if (MachineBasicBlock
*MBB2
=
549 FindSuccToSinkTo(MI
, SuccToSinkTo
, BreakPHIEdge
, AllSuccessors
))
550 return isProfitableToSinkTo(Reg
, MI
, SuccToSinkTo
, MBB2
, AllSuccessors
);
552 // If SuccToSinkTo is final destination and it is a post dominator of current
553 // block then it is not profitable to sink MI into SuccToSinkTo block.
557 /// Get the sorted sequence of successors for this MachineBasicBlock, possibly
558 /// computing it if it was not already cached.
559 SmallVector
<MachineBasicBlock
*, 4> &
560 MachineSinking::GetAllSortedSuccessors(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
561 AllSuccsCache
&AllSuccessors
) const {
562 // Do we have the sorted successors in cache ?
563 auto Succs
= AllSuccessors
.find(MBB
);
564 if (Succs
!= AllSuccessors
.end())
565 return Succs
->second
;
567 SmallVector
<MachineBasicBlock
*, 4> AllSuccs(MBB
->succ_begin(),
570 // Handle cases where sinking can happen but where the sink point isn't a
571 // successor. For example:
577 const std::vector
<MachineDomTreeNode
*> &Children
=
578 DT
->getNode(MBB
)->getChildren();
579 for (const auto &DTChild
: Children
)
580 // DomTree children of MBB that have MBB as immediate dominator are added.
581 if (DTChild
->getIDom()->getBlock() == MI
.getParent() &&
582 // Skip MBBs already added to the AllSuccs vector above.
583 !MBB
->isSuccessor(DTChild
->getBlock()))
584 AllSuccs
.push_back(DTChild
->getBlock());
586 // Sort Successors according to their loop depth or block frequency info.
588 AllSuccs
.begin(), AllSuccs
.end(),
589 [this](const MachineBasicBlock
*L
, const MachineBasicBlock
*R
) {
590 uint64_t LHSFreq
= MBFI
? MBFI
->getBlockFreq(L
).getFrequency() : 0;
591 uint64_t RHSFreq
= MBFI
? MBFI
->getBlockFreq(R
).getFrequency() : 0;
592 bool HasBlockFreq
= LHSFreq
!= 0 && RHSFreq
!= 0;
593 return HasBlockFreq
? LHSFreq
< RHSFreq
594 : LI
->getLoopDepth(L
) < LI
->getLoopDepth(R
);
597 auto it
= AllSuccessors
.insert(std::make_pair(MBB
, AllSuccs
));
599 return it
.first
->second
;
602 /// FindSuccToSinkTo - Find a successor to sink this instruction to.
604 MachineSinking::FindSuccToSinkTo(MachineInstr
&MI
, MachineBasicBlock
*MBB
,
606 AllSuccsCache
&AllSuccessors
) {
607 assert (MBB
&& "Invalid MachineBasicBlock!");
609 // Loop over all the operands of the specified instruction. If there is
610 // anything we can't handle, bail out.
612 // SuccToSinkTo - This is the successor to sink this instruction to, once we
614 MachineBasicBlock
*SuccToSinkTo
= nullptr;
615 for (unsigned i
= 0, e
= MI
.getNumOperands(); i
!= e
; ++i
) {
616 const MachineOperand
&MO
= MI
.getOperand(i
);
617 if (!MO
.isReg()) continue; // Ignore non-register operands.
619 unsigned Reg
= MO
.getReg();
620 if (Reg
== 0) continue;
622 if (TargetRegisterInfo::isPhysicalRegister(Reg
)) {
624 // If the physreg has no defs anywhere, it's just an ambient register
625 // and we can freely move its uses. Alternatively, if it's allocatable,
626 // it could get allocated to something with a def during allocation.
627 if (!MRI
->isConstantPhysReg(Reg
))
629 } else if (!MO
.isDead()) {
630 // A def that isn't dead. We can't move it.
634 // Virtual register uses are always safe to sink.
635 if (MO
.isUse()) continue;
637 // If it's not safe to move defs of the register class, then abort.
638 if (!TII
->isSafeToMoveRegClassDefs(MRI
->getRegClass(Reg
)))
641 // Virtual register defs can only be sunk if all their uses are in blocks
642 // dominated by one of the successors.
644 // If a previous operand picked a block to sink to, then this operand
645 // must be sinkable to the same block.
646 bool LocalUse
= false;
647 if (!AllUsesDominatedByBlock(Reg
, SuccToSinkTo
, MBB
,
648 BreakPHIEdge
, LocalUse
))
654 // Otherwise, we should look at all the successors and decide which one
655 // we should sink to. If we have reliable block frequency information
656 // (frequency != 0) available, give successors with smaller frequencies
657 // higher priority, otherwise prioritize smaller loop depths.
658 for (MachineBasicBlock
*SuccBlock
:
659 GetAllSortedSuccessors(MI
, MBB
, AllSuccessors
)) {
660 bool LocalUse
= false;
661 if (AllUsesDominatedByBlock(Reg
, SuccBlock
, MBB
,
662 BreakPHIEdge
, LocalUse
)) {
663 SuccToSinkTo
= SuccBlock
;
667 // Def is used locally, it's never safe to move this def.
671 // If we couldn't find a block to sink to, ignore this instruction.
674 if (!isProfitableToSinkTo(Reg
, MI
, MBB
, SuccToSinkTo
, AllSuccessors
))
679 // It is not possible to sink an instruction into its own block. This can
680 // happen with loops.
681 if (MBB
== SuccToSinkTo
)
684 // It's not safe to sink instructions to EH landing pad. Control flow into
685 // landing pad is implicitly defined.
686 if (SuccToSinkTo
&& SuccToSinkTo
->isEHPad())
692 /// Return true if MI is likely to be usable as a memory operation by the
693 /// implicit null check optimization.
695 /// This is a "best effort" heuristic, and should not be relied upon for
696 /// correctness. This returning true does not guarantee that the implicit null
697 /// check optimization is legal over MI, and this returning false does not
698 /// guarantee MI cannot possibly be used to do a null check.
699 static bool SinkingPreventsImplicitNullCheck(MachineInstr
&MI
,
700 const TargetInstrInfo
*TII
,
701 const TargetRegisterInfo
*TRI
) {
702 using MachineBranchPredicate
= TargetInstrInfo::MachineBranchPredicate
;
704 auto *MBB
= MI
.getParent();
705 if (MBB
->pred_size() != 1)
708 auto *PredMBB
= *MBB
->pred_begin();
709 auto *PredBB
= PredMBB
->getBasicBlock();
711 // Frontends that don't use implicit null checks have no reason to emit
712 // branches with make.implicit metadata, and this function should always
713 // return false for them.
715 !PredBB
->getTerminator()->getMetadata(LLVMContext::MD_make_implicit
))
718 MachineOperand
*BaseOp
;
720 if (!TII
->getMemOperandWithOffset(MI
, BaseOp
, Offset
, TRI
))
723 if (!BaseOp
->isReg())
726 if (!(MI
.mayLoad() && !MI
.isPredicable()))
729 MachineBranchPredicate MBP
;
730 if (TII
->analyzeBranchPredicate(*PredMBB
, MBP
, false))
733 return MBP
.LHS
.isReg() && MBP
.RHS
.isImm() && MBP
.RHS
.getImm() == 0 &&
734 (MBP
.Predicate
== MachineBranchPredicate::PRED_NE
||
735 MBP
.Predicate
== MachineBranchPredicate::PRED_EQ
) &&
736 MBP
.LHS
.getReg() == BaseOp
->getReg();
739 /// Sink an instruction and its associated debug instructions. If the debug
740 /// instructions to be sunk are already known, they can be provided in DbgVals.
741 static void performSink(MachineInstr
&MI
, MachineBasicBlock
&SuccToSinkTo
,
742 MachineBasicBlock::iterator InsertPos
,
743 SmallVectorImpl
<MachineInstr
*> *DbgVals
= nullptr) {
744 // If debug values are provided use those, otherwise call collectDebugValues.
745 SmallVector
<MachineInstr
*, 2> DbgValuesToSink
;
747 DbgValuesToSink
.insert(DbgValuesToSink
.begin(),
748 DbgVals
->begin(), DbgVals
->end());
750 MI
.collectDebugValues(DbgValuesToSink
);
752 // If we cannot find a location to use (merge with), then we erase the debug
753 // location to prevent debug-info driven tools from potentially reporting
754 // wrong location information.
755 if (!SuccToSinkTo
.empty() && InsertPos
!= SuccToSinkTo
.end())
756 MI
.setDebugLoc(DILocation::getMergedLocation(MI
.getDebugLoc(),
757 InsertPos
->getDebugLoc()));
759 MI
.setDebugLoc(DebugLoc());
761 // Move the instruction.
762 MachineBasicBlock
*ParentBlock
= MI
.getParent();
763 SuccToSinkTo
.splice(InsertPos
, ParentBlock
, MI
,
764 ++MachineBasicBlock::iterator(MI
));
766 // Move previously adjacent debug value instructions to the insert position.
767 for (SmallVectorImpl
<MachineInstr
*>::iterator DBI
= DbgValuesToSink
.begin(),
768 DBE
= DbgValuesToSink
.end();
770 MachineInstr
*DbgMI
= *DBI
;
771 SuccToSinkTo
.splice(InsertPos
, ParentBlock
, DbgMI
,
772 ++MachineBasicBlock::iterator(DbgMI
));
776 /// SinkInstruction - Determine whether it is safe to sink the specified machine
777 /// instruction out of its current block into a successor.
778 bool MachineSinking::SinkInstruction(MachineInstr
&MI
, bool &SawStore
,
779 AllSuccsCache
&AllSuccessors
) {
780 // Don't sink instructions that the target prefers not to sink.
781 if (!TII
->shouldSink(MI
))
784 // Check if it's safe to move the instruction.
785 if (!MI
.isSafeToMove(AA
, SawStore
))
788 // Convergent operations may not be made control-dependent on additional
790 if (MI
.isConvergent())
793 // Don't break implicit null checks. This is a performance heuristic, and not
794 // required for correctness.
795 if (SinkingPreventsImplicitNullCheck(MI
, TII
, TRI
))
798 // FIXME: This should include support for sinking instructions within the
799 // block they are currently in to shorten the live ranges. We often get
800 // instructions sunk into the top of a large block, but it would be better to
801 // also sink them down before their first use in the block. This xform has to
802 // be careful not to *increase* register pressure though, e.g. sinking
803 // "x = y + z" down if it kills y and z would increase the live ranges of y
804 // and z and only shrink the live range of x.
806 bool BreakPHIEdge
= false;
807 MachineBasicBlock
*ParentBlock
= MI
.getParent();
808 MachineBasicBlock
*SuccToSinkTo
=
809 FindSuccToSinkTo(MI
, ParentBlock
, BreakPHIEdge
, AllSuccessors
);
811 // If there are no outputs, it must have side-effects.
815 // If the instruction to move defines a dead physical register which is live
816 // when leaving the basic block, don't move it because it could turn into a
817 // "zombie" define of that preg. E.g., EFLAGS. (<rdar://problem/8030636>)
818 for (unsigned I
= 0, E
= MI
.getNumOperands(); I
!= E
; ++I
) {
819 const MachineOperand
&MO
= MI
.getOperand(I
);
820 if (!MO
.isReg()) continue;
821 unsigned Reg
= MO
.getReg();
822 if (Reg
== 0 || !TargetRegisterInfo::isPhysicalRegister(Reg
)) continue;
823 if (SuccToSinkTo
->isLiveIn(Reg
))
827 LLVM_DEBUG(dbgs() << "Sink instr " << MI
<< "\tinto block " << *SuccToSinkTo
);
829 // If the block has multiple predecessors, this is a critical edge.
830 // Decide if we can sink along it or need to break the edge.
831 if (SuccToSinkTo
->pred_size() > 1) {
832 // We cannot sink a load across a critical edge - there may be stores in
834 bool TryBreak
= false;
836 if (!MI
.isSafeToMove(AA
, store
)) {
837 LLVM_DEBUG(dbgs() << " *** NOTE: Won't sink load along critical edge.\n");
841 // We don't want to sink across a critical edge if we don't dominate the
842 // successor. We could be introducing calculations to new code paths.
843 if (!TryBreak
&& !DT
->dominates(ParentBlock
, SuccToSinkTo
)) {
844 LLVM_DEBUG(dbgs() << " *** NOTE: Critical edge found\n");
848 // Don't sink instructions into a loop.
849 if (!TryBreak
&& LI
->isLoopHeader(SuccToSinkTo
)) {
850 LLVM_DEBUG(dbgs() << " *** NOTE: Loop header found\n");
854 // Otherwise we are OK with sinking along a critical edge.
856 LLVM_DEBUG(dbgs() << "Sinking along critical edge.\n");
858 // Mark this edge as to be split.
859 // If the edge can actually be split, the next iteration of the main loop
860 // will sink MI in the newly created block.
862 PostponeSplitCriticalEdge(MI
, ParentBlock
, SuccToSinkTo
, BreakPHIEdge
);
864 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
865 "break critical edge\n");
866 // The instruction will not be sunk this time.
872 // BreakPHIEdge is true if all the uses are in the successor MBB being
873 // sunken into and they are all PHI nodes. In this case, machine-sink must
874 // break the critical edge first.
875 bool Status
= PostponeSplitCriticalEdge(MI
, ParentBlock
,
876 SuccToSinkTo
, BreakPHIEdge
);
878 LLVM_DEBUG(dbgs() << " *** PUNTING: Not legal or profitable to "
879 "break critical edge\n");
880 // The instruction will not be sunk this time.
884 // Determine where to insert into. Skip phi nodes.
885 MachineBasicBlock::iterator InsertPos
= SuccToSinkTo
->begin();
886 while (InsertPos
!= SuccToSinkTo
->end() && InsertPos
->isPHI())
889 performSink(MI
, *SuccToSinkTo
, InsertPos
);
891 // Conservatively, clear any kill flags, since it's possible that they are no
893 // Note that we have to clear the kill flags for any register this instruction
894 // uses as we may sink over another instruction which currently kills the
896 for (MachineOperand
&MO
: MI
.operands()) {
897 if (MO
.isReg() && MO
.isUse())
898 RegsToClearKillFlags
.set(MO
.getReg()); // Remember to clear kill flags.
904 //===----------------------------------------------------------------------===//
905 // This pass is not intended to be a replacement or a complete alternative
906 // for the pre-ra machine sink pass. It is only designed to sink COPY
907 // instructions which should be handled after RA.
909 // This pass sinks COPY instructions into a successor block, if the COPY is not
910 // used in the current block and the COPY is live-in to a single successor
911 // (i.e., doesn't require the COPY to be duplicated). This avoids executing the
912 // copy on paths where their results aren't needed. This also exposes
913 // additional opportunites for dead copy elimination and shrink wrapping.
915 // These copies were either not handled by or are inserted after the MachineSink
916 // pass. As an example of the former case, the MachineSink pass cannot sink
917 // COPY instructions with allocatable source registers; for AArch64 these type
918 // of copy instructions are frequently used to move function parameters (PhyReg)
919 // into virtual registers in the entry block.
921 // For the machine IR below, this pass will sink %w19 in the entry into its
922 // successor (%bb.1) because %w19 is only live-in in %bb.1.
924 // %wzr = SUBSWri %w1, 1
930 // %w0 = ADDWrr %w0, %w19
935 // As we sink %w19 (CSR in AArch64) into %bb.1, the shrink-wrapping pass will be
936 // able to see %bb.0 as a candidate.
937 //===----------------------------------------------------------------------===//
940 class PostRAMachineSinking
: public MachineFunctionPass
{
942 bool runOnMachineFunction(MachineFunction
&MF
) override
;
945 PostRAMachineSinking() : MachineFunctionPass(ID
) {}
946 StringRef
getPassName() const override
{ return "PostRA Machine Sink"; }
948 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
949 AU
.setPreservesCFG();
950 MachineFunctionPass::getAnalysisUsage(AU
);
953 MachineFunctionProperties
getRequiredProperties() const override
{
954 return MachineFunctionProperties().set(
955 MachineFunctionProperties::Property::NoVRegs
);
959 /// Track which register units have been modified and used.
960 LiveRegUnits ModifiedRegUnits
, UsedRegUnits
;
962 /// Track DBG_VALUEs of (unmodified) register units.
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 unsigned 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 unsigned 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 unsigned 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 bool PostRAMachineSinking::tryToSinkCopy(MachineBasicBlock
&CurBB
,
1099 MachineFunction
&MF
,
1100 const TargetRegisterInfo
*TRI
,
1101 const TargetInstrInfo
*TII
) {
1102 SmallPtrSet
<MachineBasicBlock
*, 2> SinkableBBs
;
1103 // FIXME: For now, we sink only to a successor which has a single predecessor
1104 // so that we can directly sink COPY instructions to the successor without
1105 // adding any new block or branch instruction.
1106 for (MachineBasicBlock
*SI
: CurBB
.successors())
1107 if (!SI
->livein_empty() && SI
->pred_size() == 1)
1108 SinkableBBs
.insert(SI
);
1110 if (SinkableBBs
.empty())
1113 bool Changed
= false;
1115 // Track which registers have been modified and used between the end of the
1116 // block and the current instruction.
1117 ModifiedRegUnits
.clear();
1118 UsedRegUnits
.clear();
1119 SeenDbgInstrs
.clear();
1121 for (auto I
= CurBB
.rbegin(), E
= CurBB
.rend(); I
!= E
;) {
1122 MachineInstr
*MI
= &*I
;
1125 // Track the operand index for use in Copy.
1126 SmallVector
<unsigned, 2> UsedOpsInCopy
;
1127 // Track the register number defed in Copy.
1128 SmallVector
<unsigned, 2> DefedRegsInCopy
;
1130 // We must sink this DBG_VALUE if its operand is sunk. To avoid searching
1131 // for DBG_VALUEs later, record them when they're encountered.
1132 if (MI
->isDebugValue()) {
1133 auto &MO
= MI
->getOperand(0);
1134 if (MO
.isReg() && TRI
->isPhysicalRegister(MO
.getReg())) {
1135 // Bail if we can already tell the sink would be rejected, rather
1136 // than needlessly accumulating lots of DBG_VALUEs.
1137 if (hasRegisterDependency(MI
, UsedOpsInCopy
, DefedRegsInCopy
,
1138 ModifiedRegUnits
, UsedRegUnits
))
1141 // Record debug use of this register.
1142 SeenDbgInstrs
[MO
.getReg()].push_back(MI
);
1147 if (MI
->isDebugInstr())
1150 // Do not move any instruction across function call.
1154 if (!MI
->isCopy() || !MI
->getOperand(0).isRenamable()) {
1155 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1160 // Don't sink the COPY if it would violate a register dependency.
1161 if (hasRegisterDependency(MI
, UsedOpsInCopy
, DefedRegsInCopy
,
1162 ModifiedRegUnits
, UsedRegUnits
)) {
1163 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1167 assert((!UsedOpsInCopy
.empty() && !DefedRegsInCopy
.empty()) &&
1168 "Unexpect SrcReg or DefReg");
1169 MachineBasicBlock
*SuccBB
=
1170 getSingleLiveInSuccBB(CurBB
, SinkableBBs
, DefedRegsInCopy
, TRI
);
1171 // Don't sink if we cannot find a single sinkable successor in which Reg
1174 LiveRegUnits::accumulateUsedDefed(*MI
, ModifiedRegUnits
, UsedRegUnits
,
1178 assert((SuccBB
->pred_size() == 1 && *SuccBB
->pred_begin() == &CurBB
) &&
1179 "Unexpected predecessor");
1181 // Collect DBG_VALUEs that must sink with this copy.
1182 SmallVector
<MachineInstr
*, 4> DbgValsToSink
;
1183 for (auto &MO
: MI
->operands()) {
1184 if (!MO
.isReg() || !MO
.isDef())
1186 unsigned reg
= MO
.getReg();
1187 for (auto *MI
: SeenDbgInstrs
.lookup(reg
))
1188 DbgValsToSink
.push_back(MI
);
1191 // Clear the kill flag if SrcReg is killed between MI and the end of the
1193 clearKillFlags(MI
, CurBB
, UsedOpsInCopy
, UsedRegUnits
, TRI
);
1194 MachineBasicBlock::iterator InsertPos
= SuccBB
->getFirstNonPHI();
1195 performSink(*MI
, *SuccBB
, InsertPos
, &DbgValsToSink
);
1196 updateLiveIn(MI
, SuccBB
, UsedOpsInCopy
, DefedRegsInCopy
);
1199 ++NumPostRACopySink
;
1204 bool PostRAMachineSinking::runOnMachineFunction(MachineFunction
&MF
) {
1205 bool Changed
= false;
1206 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1207 const TargetInstrInfo
*TII
= MF
.getSubtarget().getInstrInfo();
1209 ModifiedRegUnits
.init(*TRI
);
1210 UsedRegUnits
.init(*TRI
);
1212 Changed
|= tryToSinkCopy(BB
, MF
, TRI
, TII
);