1 //===- LiveRangeShrink.cpp - Move instructions to shrink live range -------===//
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 ///===---------------------------------------------------------------------===//
10 /// This pass moves instructions close to the definition of its operands to
11 /// shrink live range of the def instruction. The code motion is limited within
12 /// the basic block. The moved instruction should have 1 def, and more than one
13 /// uses, all of which are the only use of the def.
15 ///===---------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/TargetInstrInfo.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
36 #define DEBUG_TYPE "lrshrink"
38 STATISTIC(NumInstrsHoistedToShrinkLiveRange
,
39 "Number of insructions hoisted to shrink live range.");
43 class LiveRangeShrink
: public MachineFunctionPass
{
47 LiveRangeShrink() : MachineFunctionPass(ID
) {
48 initializeLiveRangeShrinkPass(*PassRegistry::getPassRegistry());
51 void getAnalysisUsage(AnalysisUsage
&AU
) const override
{
53 MachineFunctionPass::getAnalysisUsage(AU
);
56 StringRef
getPassName() const override
{ return "Live Range Shrink"; }
58 bool runOnMachineFunction(MachineFunction
&MF
) override
;
61 } // end anonymous namespace
63 char LiveRangeShrink::ID
= 0;
65 char &llvm::LiveRangeShrinkID
= LiveRangeShrink::ID
;
67 INITIALIZE_PASS(LiveRangeShrink
, "lrshrink", "Live Range Shrink Pass", false,
70 using InstOrderMap
= DenseMap
<MachineInstr
*, unsigned>;
72 /// Returns \p New if it's dominated by \p Old, otherwise return \p Old.
73 /// \p M maintains a map from instruction to its dominating order that satisfies
74 /// M[A] > M[B] guarantees that A is dominated by B.
75 /// If \p New is not in \p M, return \p Old. Otherwise if \p Old is null, return
77 static MachineInstr
*FindDominatedInstruction(MachineInstr
&New
,
79 const InstOrderMap
&M
) {
80 auto NewIter
= M
.find(&New
);
81 if (NewIter
== M
.end())
85 unsigned OrderOld
= M
.find(Old
)->second
;
86 unsigned OrderNew
= NewIter
->second
;
87 if (OrderOld
!= OrderNew
)
88 return OrderOld
< OrderNew
? &New
: Old
;
89 // OrderOld == OrderNew, we need to iterate down from Old to see if it
90 // can reach New, if yes, New is dominated by Old.
91 for (MachineInstr
*I
= Old
->getNextNode(); M
.find(I
)->second
== OrderNew
;
98 /// Builds Instruction to its dominating order number map \p M by traversing
99 /// from instruction \p Start.
100 static void BuildInstOrderMap(MachineBasicBlock::iterator Start
,
104 for (MachineInstr
&I
: make_range(Start
, Start
->getParent()->end()))
108 bool LiveRangeShrink::runOnMachineFunction(MachineFunction
&MF
) {
109 if (skipFunction(MF
.getFunction()))
112 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
113 const TargetInstrInfo
&TII
= *MF
.getSubtarget().getInstrInfo();
115 LLVM_DEBUG(dbgs() << "**** Analysing " << MF
.getName() << '\n');
118 // Map from register to instruction order (value of IOM) where the
119 // register is used last. When moving instructions up, we need to
120 // make sure all its defs (including dead def) will not cross its
121 // last use when moving up.
122 DenseMap
<unsigned, std::pair
<unsigned, MachineInstr
*>> UseMap
;
124 for (MachineBasicBlock
&MBB
: MF
) {
128 MachineBasicBlock::iterator Next
= MBB
.begin();
130 // Do not track PHIs in IOM when handling EHPads.
131 // Otherwise their uses may be hoisted outside a landingpad range.
132 Next
= MBB
.SkipPHIsLabelsAndDebug(Next
);
133 if (Next
== MBB
.end())
137 BuildInstOrderMap(Next
, IOM
);
138 Next
= MBB
.SkipPHIsLabelsAndDebug(Next
);
140 bool SawStore
= false;
142 while (Next
!= MBB
.end()) {
143 MachineInstr
&MI
= *Next
;
144 Next
= MBB
.SkipPHIsLabelsAndDebug(++Next
);
148 unsigned CurrentOrder
= IOM
[&MI
];
149 unsigned Barrier
= 0;
150 MachineInstr
*BarrierMI
= nullptr;
151 for (const MachineOperand
&MO
: MI
.operands()) {
152 if (!MO
.isReg() || MO
.isDebug())
155 UseMap
[MO
.getReg()] = std::make_pair(CurrentOrder
, &MI
);
156 else if (MO
.isDead() && UseMap
.count(MO
.getReg()))
157 // Barrier is the last instruction where MO get used. MI should not
158 // be moved above Barrier.
159 if (Barrier
< UseMap
[MO
.getReg()].first
) {
160 Barrier
= UseMap
[MO
.getReg()].first
;
161 BarrierMI
= UseMap
[MO
.getReg()].second
;
165 if (!MI
.isSafeToMove(SawStore
)) {
166 // If MI has side effects, it should become a barrier for code motion.
167 // IOM is rebuild from the next instruction to prevent later
168 // instructions from being moved before this MI.
169 if (MI
.hasUnmodeledSideEffects() && !MI
.isPseudoProbe() &&
171 BuildInstOrderMap(Next
, IOM
);
177 const MachineOperand
*DefMO
= nullptr;
178 MachineInstr
*Insert
= nullptr;
180 // Number of live-ranges that will be shortened. We do not count
181 // live-ranges that are defined by a COPY as it could be coalesced later.
182 unsigned NumEligibleUse
= 0;
184 for (const MachineOperand
&MO
: MI
.operands()) {
185 if (!MO
.isReg() || MO
.isDead() || MO
.isDebug())
187 Register Reg
= MO
.getReg();
188 // Do not move the instruction if it def/uses a physical register,
189 // unless it is a constant physical register or a noreg.
190 if (!Reg
.isVirtual()) {
191 if (!Reg
|| MRI
.isConstantPhysReg(Reg
))
197 // Do not move if there is more than one def.
203 } else if (MRI
.hasOneNonDBGUse(Reg
) && MRI
.hasOneDef(Reg
) && DefMO
&&
204 MRI
.getRegClass(DefMO
->getReg()) ==
205 MRI
.getRegClass(MO
.getReg())) {
206 // The heuristic does not handle different register classes yet
207 // (registers of different sizes, looser/tighter constraints). This
208 // is because it needs more accurate model to handle register
209 // pressure correctly.
210 MachineInstr
&DefInstr
= *MRI
.def_instr_begin(Reg
);
211 if (!TII
.isCopyInstr(DefInstr
))
213 Insert
= FindDominatedInstruction(DefInstr
, Insert
, IOM
);
220 // If Barrier equals IOM[I], traverse forward to find if BarrierMI is
221 // after Insert, if yes, then we should not hoist.
222 for (MachineInstr
*I
= Insert
; I
&& IOM
[I
] == Barrier
;
223 I
= I
->getNextNode())
224 if (I
== BarrierMI
) {
228 // Move the instruction when # of shrunk live range > 1.
229 if (DefMO
&& Insert
&& NumEligibleUse
> 1 && Barrier
<= IOM
[Insert
]) {
230 MachineBasicBlock::iterator I
= std::next(Insert
->getIterator());
231 // Skip all the PHI and debug instructions.
232 while (I
!= MBB
.end() && (I
->isPHI() || I
->isDebugOrPseudoInstr()))
234 if (I
== MI
.getIterator())
237 // Update the dominator order to be the same as the insertion point.
238 // We do this to maintain a non-decreasing order without need to update
239 // all instruction orders after the insertion point.
240 unsigned NewOrder
= IOM
[&*I
];
242 NumInstrsHoistedToShrinkLiveRange
++;
244 // Find MI's debug value following MI.
245 MachineBasicBlock::iterator EndIter
= std::next(MI
.getIterator());
246 if (MI
.getOperand(0).isReg())
247 for (; EndIter
!= MBB
.end() && EndIter
->isDebugValue() &&
248 EndIter
->hasDebugOperandForReg(MI
.getOperand(0).getReg());
250 IOM
[&*EndIter
] = NewOrder
;
251 MBB
.splice(I
, &MBB
, MI
.getIterator(), EndIter
);