LLVM 24.0.0git
RISCVRedundantCopyElimination.cpp
Go to the documentation of this file.
1//=- RISCVRedundantCopyElimination.cpp - Remove useless copy for RISC-V -----=//
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 removes unnecessary zero copies in BBs that are targets of
10// beqz/bnez instructions. For instance, the copy instruction in the code below
11// can be removed because the beqz jumps to BB#2 when a0 is zero.
12// BB#1:
13// beqz %a0, <BB#2>
14// BB#2:
15// %a0 = COPY %x0
16//
17// This pass also recognizes Xqcibi branch-immediate forms when compared
18// against non-zero immediates.
19//
20// This pass should be run after register allocation and is based on the
21// earliest versions of AArch64RedundantCopyElimination.
22//
23// The pass also handles register-register branches when one operand is
24// materialized as a non-zero immediate in the predecessor block.
25//
26//===----------------------------------------------------------------------===//
27
28#include "RISCV.h"
29#include "RISCVInstrInfo.h"
30#include "llvm/ADT/Statistic.h"
34#include "llvm/Support/Debug.h"
35#include <optional>
36
37using namespace llvm;
38
39#define DEBUG_TYPE "riscv-copyelim"
40
41STATISTIC(NumCopiesRemoved, "Number of copies removed.");
42
43namespace {
44class RISCVRedundantCopyElimination : public MachineFunctionPass {
45 const MachineRegisterInfo *MRI;
47 const TargetInstrInfo *TII;
48
49public:
50 static char ID;
51 RISCVRedundantCopyElimination() : MachineFunctionPass(ID) {}
52
53 bool runOnMachineFunction(MachineFunction &MF) override;
54 MachineFunctionProperties getRequiredProperties() const override {
55 return MachineFunctionProperties().setNoVRegs();
56 }
57
58 StringRef getPassName() const override {
59 return "RISC-V Redundant Copy Elimination";
60 }
61
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
63 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
65 }
66
67private:
68 bool optimizeBlock(MachineBasicBlock &MBB);
69};
70
71} // end anonymous namespace
72
73char RISCVRedundantCopyElimination::ID = 0;
74
75INITIALIZE_PASS(RISCVRedundantCopyElimination, "riscv-copyelim",
76 "RISC-V Redundant Copy Elimination", false, false)
77
78static bool
79guaranteesZeroRegInBlock(MachineBasicBlock &MBB,
82 assert(Cond.size() == 3 && "Unexpected number of operands");
83 assert(TBB != nullptr && "Expected branch target basic block");
84 auto Opc = Cond[0].getImm();
85 if (Opc == RISCV::BEQ && Cond[2].isReg() && Cond[2].getReg() == RISCV::X0 &&
86 TBB == &MBB)
87 return true;
88 if (Opc == RISCV::BNE && Cond[2].isReg() && Cond[2].getReg() == RISCV::X0 &&
89 TBB != &MBB)
90 return true;
91 return false;
92}
93
94static bool
98 assert(Cond.size() == 3 && "Unexpected number of operands");
99 assert(TBB != nullptr && "Expected branch target basic block");
100 auto Opc = Cond[0].getImm();
101 if ((Opc == RISCV::QC_BEQI || Opc == RISCV::QC_E_BEQI ||
102 Opc == RISCV::NDS_BEQC || Opc == RISCV::BEQI) &&
103 Cond[2].isImm() && Cond[2].getImm() != 0 && TBB == &MBB)
104 return true;
105 if ((Opc == RISCV::QC_BNEI || Opc == RISCV::QC_E_BNEI ||
106 Opc == RISCV::NDS_BNEC || Opc == RISCV::BNEI) &&
107 Cond[2].isImm() && Cond[2].getImm() != 0 && TBB != &MBB)
108 return true;
109 return false;
110}
111
112// Match "addi rd, x0, imm" or "qc.li rd, imm", returning the defined
113// register and the materialized immediate. Reg is invalid if MI isn't a
114// match.
116 if (MI.getOpcode() == RISCV::ADDI && MI.getOperand(0).isReg() &&
117 MI.getOperand(1).isReg() && MI.getOperand(1).getReg() == RISCV::X0 &&
118 MI.getOperand(2).isImm())
119 return RegImmPair(MI.getOperand(0).getReg(), MI.getOperand(2).getImm());
120 if (MI.getOpcode() == RISCV::QC_LI && MI.getOperand(0).isReg() &&
121 MI.getOperand(1).isImm())
122 return RegImmPair(MI.getOperand(0).getReg(), MI.getOperand(1).getImm());
123 return RegImmPair(Register(), 0);
124}
125
126static std::optional<int64_t>
128 const TargetRegisterInfo *TRI) {
129 // A write to X0 is discarded, so it cannot establish a nonzero value.
130 if (Reg == RISCV::X0)
131 return std::nullopt;
132
133 for (auto I = MBB.getFirstTerminator(); I != MBB.begin();) {
134 MachineInstr &MI = *--I;
135 if (!MI.modifiesRegister(Reg, TRI))
136 continue;
137 // The last modification must define Reg itself to a known immediate.
139 if (Match.Reg == Reg)
140 return Match.Imm;
141 return std::nullopt;
142 }
143 return std::nullopt;
144}
145
146bool RISCVRedundantCopyElimination::optimizeBlock(MachineBasicBlock &MBB) {
147 // Check if the current basic block has a single predecessor.
148 if (MBB.pred_size() != 1)
149 return false;
150
151 // Check if the predecessor has two successors, implying the block ends in a
152 // conditional branch.
153 MachineBasicBlock *PredMBB = *MBB.pred_begin();
154 if (PredMBB->succ_size() != 2)
155 return false;
156
157 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
159 if (TII->analyzeBranch(*PredMBB, TBB, FBB, Cond, /*AllowModify*/ false) ||
160 Cond.empty())
161 return false;
162
163 Register TargetReg = Cond[1].getReg();
164
165 if (!TargetReg)
166 return false;
167
168 bool IsZeroCopy = guaranteesZeroRegInBlock(MBB, Cond, TBB);
169 bool IsImmCopy = !IsZeroCopy && guaranteesRegEqualsImmInBlock(MBB, Cond, TBB);
170 int64_t CompareImm = IsImmCopy ? Cond[2].getImm() : 0;
171 if (!IsZeroCopy && !IsImmCopy && Cond.size() == 3 &&
172 (Cond[0].getImm() == RISCV::BEQ || Cond[0].getImm() == RISCV::BNE) &&
173 Cond[2].isReg()) {
174 // One branch operand may have been materialized with ADDI or QC_LI.
175 // The other operand is known to have the same value on the equality edge,
176 // irrespective of the operand order.
177 std::optional<int64_t> Imm =
179 if (Imm && *Imm != 0) {
180 TargetReg = Cond[1].getReg();
181 CompareImm = *Imm;
182 IsImmCopy = true;
183 } else {
185 if (Imm && *Imm != 0) {
186 TargetReg = Cond[2].getReg();
187 CompareImm = *Imm;
188 IsImmCopy = true;
189 }
190 }
191 // For BEQ, equality is guaranteed on the taken edge. For BNE, it is
192 // guaranteed on the fallthrough edge.
193 IsImmCopy &= (Cond[0].getImm() == RISCV::BEQ) == (TBB == &MBB);
194 }
195
196 if (!IsZeroCopy && !IsImmCopy)
197 return false;
198
199 bool Changed = false;
201 // Remove redundant Copy instructions unless TargetReg is modified.
202 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
203 MachineInstr *MI = &*I;
204 ++I;
205 bool RemoveMI = false;
206 if (IsZeroCopy) {
207 if (MI->isCopy() && MI->getOperand(0).isReg() &&
208 MI->getOperand(1).isReg()) {
209 Register DefReg = MI->getOperand(0).getReg();
210 Register SrcReg = MI->getOperand(1).getReg();
211
212 if (SrcReg == RISCV::X0 && TargetReg == DefReg &&
213 !MRI->isReserved(DefReg))
214 RemoveMI = true;
215 }
216 } else {
217 // Compare with non-zero immediate or a known register value:
218 // remove redundant addi rd,x0,imm or qc.li rd,imm as applicable.
219 RegImmPair Match = matchRegImmediate(*MI);
220 if (Match.Reg && TargetReg == Match.Reg && Match.Imm == CompareImm)
221 RemoveMI = true;
222 }
223
224 if (RemoveMI) {
225 LLVM_DEBUG(dbgs() << "Remove redundant Copy: ");
226 LLVM_DEBUG(MI->print(dbgs()));
227
228 MI->eraseFromParent();
229 Changed = true;
230 LastChange = I;
231 ++NumCopiesRemoved;
232 continue;
233 }
234
235 if (MI->modifiesRegister(TargetReg, TRI))
236 break;
237 }
238
239 if (!Changed)
240 return false;
241
243 assert((CondBr->getOpcode() == RISCV::BEQ ||
244 CondBr->getOpcode() == RISCV::BNE ||
245 CondBr->getOpcode() == RISCV::BEQI ||
246 CondBr->getOpcode() == RISCV::BNEI ||
247 CondBr->getOpcode() == RISCV::QC_BEQI ||
248 CondBr->getOpcode() == RISCV::QC_BNEI ||
249 CondBr->getOpcode() == RISCV::QC_E_BEQI ||
250 CondBr->getOpcode() == RISCV::QC_E_BNEI ||
251 CondBr->getOpcode() == RISCV::NDS_BEQC ||
252 CondBr->getOpcode() == RISCV::NDS_BNEC) &&
253 "Unexpected opcode");
254 assert((CondBr->getOperand(0).getReg() == TargetReg ||
255 CondBr->getOperand(1).getReg() == TargetReg) &&
256 "Unexpected register");
257
258 // Otherwise, we have to fixup the use-def chain, starting with the
259 // BEQ(I)/BNE(I). Conservatively mark as much as we can live.
260 CondBr->clearRegisterKills(TargetReg, TRI);
261
262 // Add newly used reg to the block's live-in list if it isn't there already.
263 if (!MBB.isLiveIn(TargetReg))
264 MBB.addLiveIn(TargetReg);
265
266 // Clear any kills of TargetReg between CondBr and the last removed COPY.
267 for (MachineInstr &MMI : make_range(MBB.begin(), LastChange))
268 MMI.clearRegisterKills(TargetReg, TRI);
269
270 return true;
271}
272
273bool RISCVRedundantCopyElimination::runOnMachineFunction(MachineFunction &MF) {
274 if (skipFunction(MF.getFunction()))
275 return false;
276
279 MRI = &MF.getRegInfo();
280
281 bool Changed = false;
282 for (MachineBasicBlock &MBB : MF)
284
285 return Changed;
286}
287
289 return new RISCVRedundantCopyElimination();
290}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned Imm
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool guaranteesRegEqualsImmInBlock(MachineBasicBlock &MBB, const SmallVectorImpl< MachineOperand > &Cond, MachineBasicBlock *TBB)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
assert(TBB !=nullptr &&"Expected branch target basic block")
static RegImmPair matchRegImmediate(const MachineInstr &MI)
static std::optional< int64_t > getRegImmediateBeforeTerminator(MachineBasicBlock &MBB, Register Reg, const TargetRegisterInfo *TRI)
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Changed
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
FunctionPass * createRISCVRedundantCopyEliminationPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Used to describe a register and immediate addition.