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// FIXME: Support compare with non-zero immediates where the immediate is stored
24// in a register.
25//
26//===----------------------------------------------------------------------===//
27
28#include "RISCV.h"
29#include "RISCVInstrInfo.h"
30#include "llvm/ADT/Statistic.h"
34#include "llvm/Support/Debug.h"
35
36using namespace llvm;
37
38#define DEBUG_TYPE "riscv-copyelim"
39
40STATISTIC(NumCopiesRemoved, "Number of copies removed.");
41
42namespace {
43class RISCVRedundantCopyElimination : public MachineFunctionPass {
44 const MachineRegisterInfo *MRI;
46 const TargetInstrInfo *TII;
47
48public:
49 static char ID;
50 RISCVRedundantCopyElimination() : MachineFunctionPass(ID) {}
51
52 bool runOnMachineFunction(MachineFunction &MF) override;
53 MachineFunctionProperties getRequiredProperties() const override {
54 return MachineFunctionProperties().setNoVRegs();
55 }
56
57 StringRef getPassName() const override {
58 return "RISC-V Redundant Copy Elimination";
59 }
60
61 void getAnalysisUsage(AnalysisUsage &AU) const override {
62 AU.addPreserved<MachineRegisterClassInfoWrapperPass>();
64 }
65
66private:
67 bool optimizeBlock(MachineBasicBlock &MBB);
68};
69
70} // end anonymous namespace
71
72char RISCVRedundantCopyElimination::ID = 0;
73
74INITIALIZE_PASS(RISCVRedundantCopyElimination, "riscv-copyelim",
75 "RISC-V Redundant Copy Elimination", false, false)
76
77static bool
78guaranteesZeroRegInBlock(MachineBasicBlock &MBB,
81 assert(Cond.size() == 3 && "Unexpected number of operands");
82 assert(TBB != nullptr && "Expected branch target basic block");
83 auto Opc = Cond[0].getImm();
84 if (Opc == RISCV::BEQ && Cond[2].isReg() && Cond[2].getReg() == RISCV::X0 &&
85 TBB == &MBB)
86 return true;
87 if (Opc == RISCV::BNE && Cond[2].isReg() && Cond[2].getReg() == RISCV::X0 &&
88 TBB != &MBB)
89 return true;
90 return false;
91}
92
93static bool
97 assert(Cond.size() == 3 && "Unexpected number of operands");
98 assert(TBB != nullptr && "Expected branch target basic block");
99 auto Opc = Cond[0].getImm();
100 if ((Opc == RISCV::QC_BEQI || Opc == RISCV::QC_E_BEQI ||
101 Opc == RISCV::NDS_BEQC || Opc == RISCV::BEQI) &&
102 Cond[2].isImm() && Cond[2].getImm() != 0 && TBB == &MBB)
103 return true;
104 if ((Opc == RISCV::QC_BNEI || Opc == RISCV::QC_E_BNEI ||
105 Opc == RISCV::NDS_BNEC || Opc == RISCV::BNEI) &&
106 Cond[2].isImm() && Cond[2].getImm() != 0 && TBB != &MBB)
107 return true;
108 return false;
109}
110
111bool RISCVRedundantCopyElimination::optimizeBlock(MachineBasicBlock &MBB) {
112 // Check if the current basic block has a single predecessor.
113 if (MBB.pred_size() != 1)
114 return false;
115
116 // Check if the predecessor has two successors, implying the block ends in a
117 // conditional branch.
118 MachineBasicBlock *PredMBB = *MBB.pred_begin();
119 if (PredMBB->succ_size() != 2)
120 return false;
121
122 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
124 if (TII->analyzeBranch(*PredMBB, TBB, FBB, Cond, /*AllowModify*/ false) ||
125 Cond.empty())
126 return false;
127
128 Register TargetReg = Cond[1].getReg();
129
130 if (!TargetReg)
131 return false;
132
133 bool IsZeroCopy = guaranteesZeroRegInBlock(MBB, Cond, TBB);
134
135 if (!IsZeroCopy && !guaranteesRegEqualsImmInBlock(MBB, Cond, TBB))
136 return false;
137
138 bool Changed = false;
140 // Remove redundant Copy instructions unless TargetReg is modified.
141 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
142 MachineInstr *MI = &*I;
143 ++I;
144 bool RemoveMI = false;
145 if (IsZeroCopy) {
146 if (MI->isCopy() && MI->getOperand(0).isReg() &&
147 MI->getOperand(1).isReg()) {
148 Register DefReg = MI->getOperand(0).getReg();
149 Register SrcReg = MI->getOperand(1).getReg();
150
151 if (SrcReg == RISCV::X0 && !MRI->isReserved(DefReg) &&
152 TargetReg == DefReg)
153 RemoveMI = true;
154 }
155 } else {
156 // Xqcibi, XAndesPref and Zibi compare with non-zero immediate:
157 // remove redundant addi rd,x0,imm or qc.li rd,imm as applicable.
158 if (MI->getOpcode() == RISCV::ADDI && MI->getOperand(0).isReg() &&
159 MI->getOperand(1).isReg() && MI->getOperand(2).isImm()) {
160 Register DefReg = MI->getOperand(0).getReg();
161 Register SrcReg = MI->getOperand(1).getReg();
162 int64_t Imm = MI->getOperand(2).getImm();
163 if (SrcReg == RISCV::X0 && !MRI->isReserved(DefReg) &&
164 TargetReg == DefReg && Imm == Cond[2].getImm())
165 RemoveMI = true;
166 } else if (MI->getOpcode() == RISCV::QC_LI && MI->getOperand(0).isReg() &&
167 MI->getOperand(1).isImm()) {
168 Register DefReg = MI->getOperand(0).getReg();
169 int64_t Imm = MI->getOperand(1).getImm();
170 if (!MRI->isReserved(DefReg) && TargetReg == DefReg &&
171 Imm == Cond[2].getImm())
172 RemoveMI = true;
173 }
174 }
175
176 if (RemoveMI) {
177 LLVM_DEBUG(dbgs() << "Remove redundant Copy: ");
178 LLVM_DEBUG(MI->print(dbgs()));
179
180 MI->eraseFromParent();
181 Changed = true;
182 LastChange = I;
183 ++NumCopiesRemoved;
184 continue;
185 }
186
187 if (MI->modifiesRegister(TargetReg, TRI))
188 break;
189 }
190
191 if (!Changed)
192 return false;
193
195 assert((CondBr->getOpcode() == RISCV::BEQ ||
196 CondBr->getOpcode() == RISCV::BNE ||
197 CondBr->getOpcode() == RISCV::BEQI ||
198 CondBr->getOpcode() == RISCV::BNEI ||
199 CondBr->getOpcode() == RISCV::QC_BEQI ||
200 CondBr->getOpcode() == RISCV::QC_BNEI ||
201 CondBr->getOpcode() == RISCV::QC_E_BEQI ||
202 CondBr->getOpcode() == RISCV::QC_E_BNEI ||
203 CondBr->getOpcode() == RISCV::NDS_BEQC ||
204 CondBr->getOpcode() == RISCV::NDS_BNEC) &&
205 "Unexpected opcode");
206 assert(CondBr->getOperand(0).getReg() == TargetReg && "Unexpected register");
207
208 // Otherwise, we have to fixup the use-def chain, starting with the
209 // BEQ(I)/BNE(I). Conservatively mark as much as we can live.
210 CondBr->clearRegisterKills(TargetReg, TRI);
211
212 // Add newly used reg to the block's live-in list if it isn't there already.
213 if (!MBB.isLiveIn(TargetReg))
214 MBB.addLiveIn(TargetReg);
215
216 // Clear any kills of TargetReg between CondBr and the last removed COPY.
217 for (MachineInstr &MMI : make_range(MBB.begin(), LastChange))
218 MMI.clearRegisterKills(TargetReg, TRI);
219
220 return true;
221}
222
223bool RISCVRedundantCopyElimination::runOnMachineFunction(MachineFunction &MF) {
224 if (skipFunction(MF.getFunction()))
225 return false;
226
229 MRI = &MF.getRegInfo();
230
231 bool Changed = false;
232 for (MachineBasicBlock &MBB : MF)
234
235 return Changed;
236}
237
239 return new RISCVRedundantCopyElimination();
240}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
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 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 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.
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.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition Pass.cpp:140
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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
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...