LLVM  12.0.0git
DeadMachineInstructionElim.cpp
Go to the documentation of this file.
1 //===- DeadMachineInstructionElim.cpp - Remove dead machine instructions --===//
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 is an extremely simple MachineInstr-level dead-code-elimination pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/Statistic.h"
16 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/InitializePasses.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/Debug.h"
22 
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "dead-mi-elimination"
26 
27 STATISTIC(NumDeletes, "Number of dead instructions deleted");
28 
29 namespace {
30  class DeadMachineInstructionElim : public MachineFunctionPass {
31  bool runOnMachineFunction(MachineFunction &MF) override;
32 
33  const TargetRegisterInfo *TRI;
34  const MachineRegisterInfo *MRI;
35  const TargetInstrInfo *TII;
37 
38  public:
39  static char ID; // Pass identification, replacement for typeid
40  DeadMachineInstructionElim() : MachineFunctionPass(ID) {
42  }
43 
44  void getAnalysisUsage(AnalysisUsage &AU) const override {
45  AU.setPreservesCFG();
47  }
48 
49  private:
50  bool isDead(const MachineInstr *MI) const;
51  };
52 }
55 
56 INITIALIZE_PASS(DeadMachineInstructionElim, DEBUG_TYPE,
57  "Remove dead machine instructions", false, false)
58 
59 bool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {
60  // Technically speaking inline asm without side effects and no defs can still
61  // be deleted. But there is so much bad inline asm code out there, we should
62  // let them be.
63  if (MI->isInlineAsm())
64  return false;
65 
66  // Don't delete frame allocation labels.
67  if (MI->getOpcode() == TargetOpcode::LOCAL_ESCAPE)
68  return false;
69 
70  // Don't delete instructions with side effects.
71  bool SawStore = false;
72  if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI())
73  return false;
74 
75  // Examine each operand.
76  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
77  const MachineOperand &MO = MI->getOperand(i);
78  if (MO.isReg() && MO.isDef()) {
79  Register Reg = MO.getReg();
81  // Don't delete live physreg defs, or any reserved register defs.
82  if (LivePhysRegs.test(Reg) || MRI->isReserved(Reg))
83  return false;
84  } else {
85  if (MO.isDead()) {
86 #ifndef NDEBUG
87  // Sanity check on uses of this dead register. All of them should be
88  // 'undef'.
89  for (auto &U : MRI->use_nodbg_operands(Reg))
90  assert(U.isUndef() && "'Undef' use on a 'dead' register is found!");
91 #endif
92  continue;
93  }
94  for (const MachineInstr &Use : MRI->use_nodbg_instructions(Reg)) {
95  if (&Use != MI)
96  // This def has a non-debug use. Don't delete the instruction!
97  return false;
98  }
99  }
100  }
101  }
102 
103  // If there are no defs with uses, the instruction is dead.
104  return true;
105 }
106 
107 bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
108  if (skipFunction(MF.getFunction()))
109  return false;
110 
111  bool AnyChanges = false;
112  MRI = &MF.getRegInfo();
113  TRI = MF.getSubtarget().getRegisterInfo();
114  TII = MF.getSubtarget().getInstrInfo();
115 
116  // Loop over all instructions in all blocks, from bottom to top, so that it's
117  // more likely that chains of dependent but ultimately dead instructions will
118  // be cleaned up.
119  for (MachineBasicBlock &MBB : make_range(MF.rbegin(), MF.rend())) {
120  // Start out assuming that reserved registers are live out of this block.
121  LivePhysRegs = MRI->getReservedRegs();
122 
123  // Add live-ins from successors to LivePhysRegs. Normally, physregs are not
124  // live across blocks, but some targets (x86) can have flags live out of a
125  // block.
127  E = MBB.succ_end(); S != E; S++)
128  for (const auto &LI : (*S)->liveins())
129  LivePhysRegs.set(LI.PhysReg);
130 
131  // Now scan the instructions and delete dead ones, tracking physreg
132  // liveness as we go.
134  MIE = MBB.rend(); MII != MIE; ) {
135  MachineInstr *MI = &*MII++;
136 
137  // If the instruction is dead, delete it!
138  if (isDead(MI)) {
139  LLVM_DEBUG(dbgs() << "DeadMachineInstructionElim: DELETING: " << *MI);
140  // It is possible that some DBG_VALUE instructions refer to this
141  // instruction. They get marked as undef and will be deleted
142  // in the live debug variable analysis.
144  AnyChanges = true;
145  ++NumDeletes;
146  continue;
147  }
148 
149  // Record the physreg defs.
150  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
151  const MachineOperand &MO = MI->getOperand(i);
152  if (MO.isReg() && MO.isDef()) {
153  Register Reg = MO.getReg();
154  if (Register::isPhysicalRegister(Reg)) {
155  // Check the subreg set, not the alias set, because a def
156  // of a super-register may still be partially live after
157  // this def.
158  for (MCSubRegIterator SR(Reg, TRI,/*IncludeSelf=*/true);
159  SR.isValid(); ++SR)
160  LivePhysRegs.reset(*SR);
161  }
162  } else if (MO.isRegMask()) {
163  // Register mask of preserved registers. All clobbers are dead.
164  LivePhysRegs.clearBitsNotInMask(MO.getRegMask());
165  }
166  }
167  // Record the physreg uses, after the defs, in case a physreg is
168  // both defined and used in the same instruction.
169  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170  const MachineOperand &MO = MI->getOperand(i);
171  if (MO.isReg() && MO.isUse()) {
172  Register Reg = MO.getReg();
173  if (Register::isPhysicalRegister(Reg)) {
174  for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
175  LivePhysRegs.set(*AI);
176  }
177  }
178  }
179  }
180  }
181 
182  LivePhysRegs.clear();
183  return AnyChanges;
184 }
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
BitVector & set()
Definition: BitVector.h:398
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool isReserved(Register PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:65
unsigned Reg
bool test(unsigned Idx) const
Definition: BitVector.h:502
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
Function & getFunction()
Return the LLVM function that this machine code represents.
MachineBasicBlock & MBB
#define DEBUG_TYPE
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Definition: BitVector.h:367
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:459
A Use represents the edge between a Value definition and its users.
Definition: Use.h:44
MachineBasicBlock iterator that automatically skips over MIs that are inside bundles (i...
void eraseFromParentAndMarkDBGValuesForRemoval()
Unlink &#39;this&#39; from the containing basic block and delete it.
char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
virtual const TargetInstrInfo * getInstrInfo() const
reverse_iterator rend()
reverse_iterator rbegin()
TargetInstrInfo - Interface to description of machine instruction set.
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
clearBitsNotInMask - Clear a bit in this vector for every &#39;0&#39; bit in Mask.
Definition: BitVector.h:798
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void initializeDeadMachineInstructionElimPass(PassRegistry &)
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
BitVector & reset()
Definition: BitVector.h:439
constexpr double e
Definition: MathExtras.h:58
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
MachineOperand class - Representation of each machine instruction operand.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:253
reverse_iterator rend()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
const BitVector & getReservedRegs() const
getReservedRegs - Returns a reference to the frozen set of reserved registers.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:62
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
A set of physical registers with utility functions to track liveness when walking backward/forward th...
Definition: LivePhysRegs.h:48
bool isReg() const
isReg - Tests if this is a MO_Register operand.
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
IRTranslator LLVM IR MI
Register getReg() const
getReg - Returns the register number.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:466
reverse_iterator rbegin()
std::vector< MachineBasicBlock * >::iterator succ_iterator
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
INITIALIZE_PASS(DeadMachineInstructionElim, DEBUG_TYPE, "Remove dead machine instructions", false, false) bool DeadMachineInstructionElim