LLVM  16.0.0git
RISCVRedundantCopyElimination.cpp
Go to the documentation of this file.
1 //=- RISCVRedundantCopyElimination.cpp - Remove useless copy for RISCV ------=//
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 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "riscv-copyelim"
36 
37 STATISTIC(NumCopiesRemoved, "Number of copies removed.");
38 
39 namespace {
40 class RISCVRedundantCopyElimination : public MachineFunctionPass {
41  const MachineRegisterInfo *MRI;
42  const TargetRegisterInfo *TRI;
43  const TargetInstrInfo *TII;
44 
45 public:
46  static char ID;
47  RISCVRedundantCopyElimination() : MachineFunctionPass(ID) {
50  }
51 
52  bool runOnMachineFunction(MachineFunction &MF) override;
53  MachineFunctionProperties getRequiredProperties() const override {
56  }
57 
58  StringRef getPassName() const override {
59  return "RISCV Redundant Copy Elimination";
60  }
61 
62 private:
64 };
65 
66 } // end anonymous namespace
67 
69 
70 INITIALIZE_PASS(RISCVRedundantCopyElimination, "riscv-copyelim",
71  "RISCV redundant copy elimination pass", false, false)
72 
73 static bool
74 guaranteesZeroRegInBlock(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].getReg() == RISCV::X0 && TBB == &MBB)
81  return true;
82  if (CC == RISCVCC::COND_NE && Cond[2].getReg() == RISCV::X0 && TBB != &MBB)
83  return true;
84  return false;
85 }
86 
88  // Check if the current basic block has a single predecessor.
89  if (MBB.pred_size() != 1)
90  return false;
91 
92  // Check if the predecessor has two successors, implying the block ends in a
93  // conditional branch.
94  MachineBasicBlock *PredMBB = *MBB.pred_begin();
95  if (PredMBB->succ_size() != 2)
96  return false;
97 
98  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
100  if (TII->analyzeBranch(*PredMBB, TBB, FBB, Cond, /*AllowModify*/ false) ||
101  Cond.empty())
102  return false;
103 
104  // Is this a branch with X0?
105  if (!guaranteesZeroRegInBlock(MBB, Cond, TBB))
106  return false;
107 
108  Register TargetReg = Cond[1].getReg();
109  if (!TargetReg)
110  return false;
111 
112  bool Changed = false;
113  MachineBasicBlock::iterator LastChange = MBB.begin();
114  // Remove redundant Copy instructions unless TargetReg is modified.
115  for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E;) {
116  MachineInstr *MI = &*I;
117  ++I;
118  if (MI->isCopy() && MI->getOperand(0).isReg() &&
119  MI->getOperand(1).isReg()) {
120  Register DefReg = MI->getOperand(0).getReg();
121  Register SrcReg = MI->getOperand(1).getReg();
122 
123  if (SrcReg == RISCV::X0 && !MRI->isReserved(DefReg) &&
124  TargetReg == DefReg) {
125  LLVM_DEBUG(dbgs() << "Remove redundant Copy : ");
126  LLVM_DEBUG(MI->print(dbgs()));
127 
128  MI->eraseFromParent();
129  Changed = true;
130  LastChange = I;
131  ++NumCopiesRemoved;
132  continue;
133  }
134  }
135 
136  if (MI->modifiesRegister(TargetReg, TRI))
137  break;
138  }
139 
140  if (!Changed)
141  return false;
142 
144  assert((CondBr->getOpcode() == RISCV::BEQ ||
145  CondBr->getOpcode() == RISCV::BNE) &&
146  "Unexpected opcode");
147  assert(CondBr->getOperand(0).getReg() == TargetReg && "Unexpected register");
148 
149  // Otherwise, we have to fixup the use-def chain, starting with the
150  // BEQ/BNE. Conservatively mark as much as we can live.
151  CondBr->clearRegisterKills(TargetReg, TRI);
152 
153  // Add newly used reg to the block's live-in list if it isn't there already.
154  if (!MBB.isLiveIn(TargetReg))
155  MBB.addLiveIn(TargetReg);
156 
157  // Clear any kills of TargetReg between CondBr and the last removed COPY.
158  for (MachineInstr &MMI : make_range(MBB.begin(), LastChange))
159  MMI.clearRegisterKills(TargetReg, TRI);
160 
161  return true;
162 }
163 
164 bool RISCVRedundantCopyElimination::runOnMachineFunction(MachineFunction &MF) {
165  if (skipFunction(MF.getFunction()))
166  return false;
167 
168  TII = MF.getSubtarget().getInstrInfo();
170  MRI = &MF.getRegInfo();
171 
172  bool Changed = false;
173  for (MachineBasicBlock &MBB : MF)
174  Changed |= optimizeBlock(MBB);
175 
176  return Changed;
177 }
178 
180  return new RISCVRedundantCopyElimination();
181 }
llvm::MachineBasicBlock::succ_size
unsigned succ_size() const
Definition: MachineBasicBlock.h:381
llvm::MachineBasicBlock::pred_begin
pred_iterator pred_begin()
Definition: MachineBasicBlock.h:353
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:109
llvm
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
llvm::make_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Definition: iterator_range.h:53
llvm::MachineBasicBlock::isLiveIn
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Definition: MachineBasicBlock.cpp:591
llvm::AArch64PACKey::ID
ID
Definition: AArch64BaseInfo.h:818
llvm::MachineRegisterInfo
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Definition: MachineRegisterInfo.h:50
assert
assert(TBB !=nullptr &&"Expected branch target basic block")
llvm::TargetSubtargetInfo::getInstrInfo
virtual const TargetInstrInfo * getInstrInfo() const
Definition: TargetSubtargetInfo.h:95
llvm::HexagonInstrInfo::analyzeBranch
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....
Definition: HexagonInstrInfo.cpp:434
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1199
Statistic.h
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
llvm::TargetSubtargetInfo::getRegisterInfo
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Definition: TargetSubtargetInfo.h:127
llvm::TargetRegisterInfo
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Definition: TargetRegisterInfo.h:237
llvm::MachineFunctionProperties
Properties which a MachineFunction may have at a given point in time.
Definition: MachineFunction.h:127
TRI
unsigned const TargetRegisterInfo * TRI
Definition: MachineSink.cpp:1628
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:101
MachineRegisterInfo.h
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::MachineBasicBlock::pred_size
unsigned pred_size() const
Definition: MachineBasicBlock.h:365
llvm::MachineFunction::getRegInfo
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Definition: MachineFunction.h:667
INITIALIZE_PASS
INITIALIZE_PASS(RISCVRedundantCopyElimination, "riscv-copyelim", "RISCV redundant copy elimination pass", false, false) static bool guaranteesZeroRegInBlock(MachineBasicBlock &MBB
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:98
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:24
getReg
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
Definition: MipsDisassembler.cpp:517
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::MachineRegisterInfo::isReserved
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
Definition: MachineRegisterInfo.h:930
llvm::initializeRISCVRedundantCopyEliminationPass
void initializeRISCVRedundantCopyEliminationPass(PassRegistry &)
TBB
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
Definition: RISCVRedundantCopyElimination.cpp:76
TII
const HexagonInstrInfo * TII
Definition: HexagonCopyToCombine.cpp:125
llvm::MachineOperand
MachineOperand class - Representation of each machine instruction operand.
Definition: MachineOperand.h:48
llvm::MachineFunctionProperties::set
MachineFunctionProperties & set(Property P)
Definition: MachineFunction.h:196
Cond
const SmallVectorImpl< MachineOperand > & Cond
Definition: RISCVRedundantCopyElimination.cpp:75
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
llvm::CallingConv::ID
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
llvm::MachineBasicBlock
Definition: MachineBasicBlock.h:94
llvm::Pass::print
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:130
llvm::MachineFunctionProperties::Property::NoVRegs
@ NoVRegs
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:657
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:66
const
aarch64 promote const
Definition: AArch64PromoteConstant.cpp:232
llvm::RISCVCC::COND_EQ
@ COND_EQ
Definition: RISCVInstrInfo.h:31
I
#define I(x, y, z)
Definition: MD5.cpp:58
MachineFunctionPass.h
RISCV.h
llvm::MachineFunction
Definition: MachineFunction.h:257
llvm::MachineBasicBlock::getFirstTerminator
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Definition: MachineBasicBlock.cpp:239
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
CC
auto CC
Definition: RISCVRedundantCopyElimination.cpp:79
MRI
unsigned const MachineRegisterInfo * MRI
Definition: AArch64AdvSIMDScalarPass.cpp:105
llvm::Register
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
llvm::MachineBasicBlock::addLiveIn
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
Definition: MachineBasicBlock.h:404
MBB
MachineBasicBlock & MBB
Definition: AArch64SLSHardening.cpp:74
llvm::MachineFunction::getFunction
Function & getFunction()
Return the LLVM function that this machine code represents.
Definition: MachineFunction.h:623
llvm::createRISCVRedundantCopyEliminationPass
FunctionPass * createRISCVRedundantCopyEliminationPass()
Definition: RISCVRedundantCopyElimination.cpp:179
optimizeBlock
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, DomTreeUpdater *DTU)
Definition: ScalarizeMaskedMemIntrin.cpp:909
RISCVInstrInfo.h
llvm::RISCVCC::CondCode
CondCode
Definition: RISCVInstrInfo.h:30
llvm::MachineBasicBlock::begin
iterator begin()
Definition: MachineBasicBlock.h:305
llvm::SmallVectorImpl
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
llvm::FunctionPass
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:308
llvm::MachineInstrBundleIterator< MachineInstr >
Debug.h
llvm::MachineBasicBlock::end
iterator end()
Definition: MachineBasicBlock.h:307
llvm::RISCVCC::COND_NE
@ COND_NE
Definition: RISCVInstrInfo.h:32