LLVM 20.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// This pass should be run after register allocation.
17//
18// This pass is based on the earliest versions of
19// AArch64RedundantCopyElimination.
20//
21// FIXME: Support compares with constants other than zero? This is harder to
22// do on RISC-V since branches can't have immediates.
23//
24//===----------------------------------------------------------------------===//
25
26#include "RISCV.h"
27#include "RISCVInstrInfo.h"
28#include "llvm/ADT/Statistic.h"
31#include "llvm/Support/Debug.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "riscv-copyelim"
36
37STATISTIC(NumCopiesRemoved, "Number of copies removed.");
38
39namespace {
40class RISCVRedundantCopyElimination : public MachineFunctionPass {
43 const TargetInstrInfo *TII;
44
45public:
46 static char ID;
47 RISCVRedundantCopyElimination() : MachineFunctionPass(ID) {
50 }
51
52 bool runOnMachineFunction(MachineFunction &MF) override;
55 MachineFunctionProperties::Property::NoVRegs);
56 }
57
58 StringRef getPassName() const override {
59 return "RISC-V Redundant Copy Elimination";
60 }
61
62private:
64};
65
66} // end anonymous namespace
67
68char RISCVRedundantCopyElimination::ID = 0;
69
70INITIALIZE_PASS(RISCVRedundantCopyElimination, "riscv-copyelim",
71 "RISC-V Redundant Copy Elimination", false, false)
72
73static bool
74guaranteesZeroRegInBlock(MachineBasicBlock &MBB,
77 assert(Cond.size() == 3 && "Unexpected number of operands");
78 assert(TBB != nullptr && "Expected branch target basic block");
79 auto CC = static_cast<RISCVCC::CondCode>(Cond[0].getImm());
80 if (CC == RISCVCC::COND_EQ && Cond[2].isReg() &&
81 Cond[2].getReg() == RISCV::X0 && TBB == &MBB)
82 return true;
83 if (CC == RISCVCC::COND_NE && Cond[2].isReg() &&
84 Cond[2].getReg() == RISCV::X0 && TBB != &MBB)
85 return true;
86 return false;
87}
88
89bool RISCVRedundantCopyElimination::optimizeBlock(MachineBasicBlock &MBB) {
90 // Check if the current basic block has a single predecessor.
91 if (MBB.pred_size() != 1)
92 return false;
93
94 // Check if the predecessor has two successors, implying the block ends in a
95 // conditional branch.
96 MachineBasicBlock *PredMBB = *MBB.pred_begin();
97 if (PredMBB->succ_size() != 2)
98 return false;
99
100 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
102 if (TII->analyzeBranch(*PredMBB, TBB, FBB, Cond, /*AllowModify*/ false) ||
103 Cond.empty())
104 return false;
105
106 // Is this a branch with X0?
107 if (!guaranteesZeroRegInBlock(MBB, Cond, TBB))
108 return false;
109
110 Register TargetReg = Cond[1].getReg();
111 if (!TargetReg)
112 return false;
113
114 bool Changed = false;
116 // Remove redundant Copy instructions unless TargetReg is modified.
117 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
118 MachineInstr *MI = &*I;
119 ++I;
120 if (MI->isCopy() && MI->getOperand(0).isReg() &&
121 MI->getOperand(1).isReg()) {
122 Register DefReg = MI->getOperand(0).getReg();
123 Register SrcReg = MI->getOperand(1).getReg();
124
125 if (SrcReg == RISCV::X0 && !MRI->isReserved(DefReg) &&
126 TargetReg == DefReg) {
127 LLVM_DEBUG(dbgs() << "Remove redundant Copy : ");
128 LLVM_DEBUG(MI->print(dbgs()));
129
130 MI->eraseFromParent();
131 Changed = true;
132 LastChange = I;
133 ++NumCopiesRemoved;
134 continue;
135 }
136 }
137
138 if (MI->modifiesRegister(TargetReg, TRI))
139 break;
140 }
141
142 if (!Changed)
143 return false;
144
146 assert((CondBr->getOpcode() == RISCV::BEQ ||
147 CondBr->getOpcode() == RISCV::BNE) &&
148 "Unexpected opcode");
149 assert(CondBr->getOperand(0).getReg() == TargetReg && "Unexpected register");
150
151 // Otherwise, we have to fixup the use-def chain, starting with the
152 // BEQ/BNE. Conservatively mark as much as we can live.
153 CondBr->clearRegisterKills(TargetReg, TRI);
154
155 // Add newly used reg to the block's live-in list if it isn't there already.
156 if (!MBB.isLiveIn(TargetReg))
157 MBB.addLiveIn(TargetReg);
158
159 // Clear any kills of TargetReg between CondBr and the last removed COPY.
160 for (MachineInstr &MMI : make_range(MBB.begin(), LastChange))
161 MMI.clearRegisterKills(TargetReg, TRI);
162
163 return true;
164}
165
166bool RISCVRedundantCopyElimination::runOnMachineFunction(MachineFunction &MF) {
167 if (skipFunction(MF.getFunction()))
168 return false;
169
172 MRI = &MF.getRegInfo();
173
174 bool Changed = false;
175 for (MachineBasicBlock &MBB : MF)
176 Changed |= optimizeBlock(MBB);
177
178 return Changed;
179}
180
182 return new RISCVRedundantCopyElimination();
183}
unsigned const MachineRegisterInfo * MRI
aarch64 promote const
MachineBasicBlock & MBB
#define LLVM_DEBUG(X)
Definition: Debug.h:101
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
static bool isReg(const MCInst &MI, unsigned OpNo)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
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, 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:167
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
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....
unsigned pred_size() const
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned succ_size() const
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
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.
Definition: MachineInstr.h:69
MachineOperand class - Representation of each machine instruction operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:130
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:587
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1210
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
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.
Definition: AddressRanges.h:18
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void initializeRISCVRedundantCopyEliminationPass(PassRegistry &)
FunctionPass * createRISCVRedundantCopyEliminationPass()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163