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/DenseSet.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/CodeGen/LiveIntervals.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/CodeGen/TargetSubtargetInfo.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "dead-mi-elimination"
27 
28 STATISTIC(NumDeletes,          "Number of dead instructions deleted");
29 
30 namespace {
31   class DeadMachineInstructionElim : public MachineFunctionPass {
32     bool runOnMachineFunction(MachineFunction &MF) override;
33 
34     const TargetRegisterInfo *TRI;
35     const MachineRegisterInfo *MRI;
36     const TargetInstrInfo *TII;
37     LiveIntervals *LIS;
38     BitVector LivePhysRegs;
39 
40   public:
41     static char ID; // Pass identification, replacement for typeid
42     DeadMachineInstructionElim() : MachineFunctionPass(ID) {
43      initializeDeadMachineInstructionElimPass(*PassRegistry::getPassRegistry());
44     }
45 
46     void getAnalysisUsage(AnalysisUsage &AU) const override {
47       AU.setPreservesAll();
48       MachineFunctionPass::getAnalysisUsage(AU);
49     }
50 
51   private:
52     bool isDead(const MachineInstr *MI) const;
53   };
54 }
55 char DeadMachineInstructionElim::ID = 0;
56 char &llvm::DeadMachineInstructionElimID = DeadMachineInstructionElim::ID;
57 
58 INITIALIZE_PASS(DeadMachineInstructionElim, DEBUG_TYPE,
59                 "Remove dead machine instructions", false, false)
60 
61 bool DeadMachineInstructionElim::isDead(const MachineInstr *MI) const {
62   // Technically speaking inline asm without side effects and no defs can still
63   // be deleted. But there is so much bad inline asm code out there, we should
64   // let them be.
65   if (MI->isInlineAsm())
66     return false;
67 
68   // Don't delete frame allocation labels.
69   if (MI->getOpcode() == TargetOpcode::LOCAL_ESCAPE)
70     return false;
71 
72   // Don't delete instructions with side effects.
73   bool SawStore = false;
74   if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI())
75     return false;
76 
77   // Examine each operand.
78   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
79     const MachineOperand &MO = MI->getOperand(i);
80     if (MO.isReg() && MO.isDef()) {
81       unsigned Reg = MO.getReg();
82       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
83         // Don't delete live physreg defs, or any reserved register defs.
84         // Do not remove physreg defs if we have LIS as we may be unable
85         // to accurately recompute its liveness.
86         if (LivePhysRegs.test(Reg) || MRI->isReserved(Reg) || LIS)
87           return false;
88       } else {
89         // An instruction can also use its def in case if it is a tied operand.
90         // TODO: Technically we can also remove it if def dominates the use.
91         //       This can happen when two instructions define different subregs
92         //       of the same register.
93         for (const MachineInstr &Use : MRI->use_nodbg_instructions(Reg)) {
94           if (&Use != MI)
95             // This def has a non-debug use. Don't delete the instruction!
96             return false;
97         }
98       }
99     }
100   }
101 
102   // If there are no defs with uses, the instruction is dead.
103   return true;
104 }
105 
106 bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
107   if (skipFunction(MF.getFunction()))
108     return false;
109 
110   bool AnyChanges = false;
111   MRI = &MF.getRegInfo();
112   TRI = MF.getSubtarget().getRegisterInfo();
113   TII = MF.getSubtarget().getInstrInfo();
114   LIS = getAnalysisIfAvailable<LiveIntervals>();
115   DenseSet<unsigned> RecalcRegs;
116 
117   // Loop over all instructions in all blocks, from bottom to top, so that it's
118   // more likely that chains of dependent but ultimately dead instructions will
119   // be cleaned up.
120   for (MachineBasicBlock &MBB : make_range(MF.rbegin(), MF.rend())) {
121     // Start out assuming that reserved registers are live out of this block.
122     LivePhysRegs = MRI->getReservedRegs();
123 
124     // Add live-ins from successors to LivePhysRegs. Normally, physregs are not
125     // live across blocks, but some targets (x86) can have flags live out of a
126     // block.
127     for (MachineBasicBlock::succ_iterator S = MBB.succ_begin(),
128            E = MBB.succ_end(); S != E; S++)
129       for (const auto &LI : (*S)->liveins())
130         LivePhysRegs.set(LI.PhysReg);
131 
132     // Now scan the instructions and delete dead ones, tracking physreg
133     // liveness as we go.
134     for (MachineBasicBlock::reverse_iterator MII = MBB.rbegin(),
135          MIE = MBB.rend(); MII != MIE; ) {
136       MachineInstr *MI = &*MII++;
137 
138       // If the instruction is dead, delete it!
139       if (isDead(MI)) {
140         LLVM_DEBUG(dbgs() << "DeadMachineInstructionElim: DELETING: " << *MI);
141         if (LIS) {
142           for (const MachineOperand &MO : MI->operands()) {
143             if (MO.isReg() && TRI->isVirtualRegister(MO.getReg()))
144               RecalcRegs.insert(MO.getReg());
145           }
146           LIS->RemoveMachineInstrFromMaps(*MI);
147         }
148 
149         // It is possible that some DBG_VALUE instructions refer to this
150         // instruction.  They get marked as undef and will be deleted
151         // in the live debug variable analysis.
152         MI->eraseFromParentAndMarkDBGValuesForRemoval();
153         AnyChanges = true;
154         ++NumDeletes;
155         continue;
156       }
157 
158       // Record the physreg defs.
159       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
160         const MachineOperand &MO = MI->getOperand(i);
161         if (MO.isReg() && MO.isDef()) {
162           unsigned Reg = MO.getReg();
163           if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
164             // Check the subreg set, not the alias set, because a def
165             // of a super-register may still be partially live after
166             // this def.
167             for (MCSubRegIterator SR(Reg, TRI,/*IncludeSelf=*/true);
168                  SR.isValid(); ++SR)
169               LivePhysRegs.reset(*SR);
170           }
171         } else if (MO.isRegMask()) {
172           // Register mask of preserved registers. All clobbers are dead.
173           LivePhysRegs.clearBitsNotInMask(MO.getRegMask());
174         }
175       }
176       // Record the physreg uses, after the defs, in case a physreg is
177       // both defined and used in the same instruction.
178       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
179         const MachineOperand &MO = MI->getOperand(i);
180         if (MO.isReg() && MO.isUse()) {
181           unsigned Reg = MO.getReg();
182           if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
183             for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
184               LivePhysRegs.set(*AI);
185           }
186         }
187       }
188     }
189   }
190 
191   LivePhysRegs.clear();
192 
193   for (auto Reg : RecalcRegs) {
194     LIS->removeInterval(Reg);
195     if (!MRI->reg_empty(Reg))
196       LIS->createAndComputeVirtRegInterval(Reg);
197   }
198 
199   return AnyChanges;
200 }
201