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"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/CodeGen/TargetSubtargetInfo.h"
18 #include "llvm/InitializePasses.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.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;
36     BitVector LivePhysRegs;
37 
38   public:
39     static char ID; // Pass identification, replacement for typeid
40     DeadMachineInstructionElim() : MachineFunctionPass(ID) {
41      initializeDeadMachineInstructionElimPass(*PassRegistry::getPassRegistry());
42     }
43 
44     void getAnalysisUsage(AnalysisUsage &AU) const override {
45       AU.setPreservesCFG();
46       MachineFunctionPass::getAnalysisUsage(AU);
47     }
48 
49   private:
50     bool isDead(const MachineInstr *MI) const;
51   };
52 }
53 char DeadMachineInstructionElim::ID = 0;
54 char &llvm::DeadMachineInstructionElimID = DeadMachineInstructionElim::ID;
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();
80       if (Register::isPhysicalRegister(Reg)) {
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         for (const MachineInstr &Use : MRI->use_nodbg_instructions(Reg)) {
86           if (&Use != MI)
87             // This def has a non-debug use. Don't delete the instruction!
88             return false;
89         }
90       }
91     }
92   }
93 
94   // If there are no defs with uses, the instruction is dead.
95   return true;
96 }
97 
98 bool DeadMachineInstructionElim::runOnMachineFunction(MachineFunction &MF) {
99   if (skipFunction(MF.getFunction()))
100     return false;
101 
102   bool AnyChanges = false;
103   MRI = &MF.getRegInfo();
104   TRI = MF.getSubtarget().getRegisterInfo();
105   TII = MF.getSubtarget().getInstrInfo();
106 
107   // Loop over all instructions in all blocks, from bottom to top, so that it's
108   // more likely that chains of dependent but ultimately dead instructions will
109   // be cleaned up.
110   for (MachineBasicBlock &MBB : make_range(MF.rbegin(), MF.rend())) {
111     // Start out assuming that reserved registers are live out of this block.
112     LivePhysRegs = MRI->getReservedRegs();
113 
114     // Add live-ins from successors to LivePhysRegs. Normally, physregs are not
115     // live across blocks, but some targets (x86) can have flags live out of a
116     // block.
117     for (MachineBasicBlock::succ_iterator S = MBB.succ_begin(),
118            E = MBB.succ_end(); S != E; S++)
119       for (const auto &LI : (*S)->liveins())
120         LivePhysRegs.set(LI.PhysReg);
121 
122     // Now scan the instructions and delete dead ones, tracking physreg
123     // liveness as we go.
124     for (MachineBasicBlock::reverse_iterator MII = MBB.rbegin(),
125          MIE = MBB.rend(); MII != MIE; ) {
126       MachineInstr *MI = &*MII++;
127 
128       // If the instruction is dead, delete it!
129       if (isDead(MI)) {
130         LLVM_DEBUG(dbgs() << "DeadMachineInstructionElim: DELETING: " << *MI);
131         // It is possible that some DBG_VALUE instructions refer to this
132         // instruction.  They get marked as undef and will be deleted
133         // in the live debug variable analysis.
134         MI->eraseFromParentAndMarkDBGValuesForRemoval();
135         AnyChanges = true;
136         ++NumDeletes;
137         continue;
138       }
139 
140       // Record the physreg defs.
141       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
142         const MachineOperand &MO = MI->getOperand(i);
143         if (MO.isReg() && MO.isDef()) {
144           Register Reg = MO.getReg();
145           if (Register::isPhysicalRegister(Reg)) {
146             // Check the subreg set, not the alias set, because a def
147             // of a super-register may still be partially live after
148             // this def.
149             for (MCSubRegIterator SR(Reg, TRI,/*IncludeSelf=*/true);
150                  SR.isValid(); ++SR)
151               LivePhysRegs.reset(*SR);
152           }
153         } else if (MO.isRegMask()) {
154           // Register mask of preserved registers. All clobbers are dead.
155           LivePhysRegs.clearBitsNotInMask(MO.getRegMask());
156         }
157       }
158       // Record the physreg uses, after the defs, in case a physreg is
159       // both defined and used in the same instruction.
160       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
161         const MachineOperand &MO = MI->getOperand(i);
162         if (MO.isReg() && MO.isUse()) {
163           Register Reg = MO.getReg();
164           if (Register::isPhysicalRegister(Reg)) {
165             for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
166               LivePhysRegs.set(*AI);
167           }
168         }
169       }
170     }
171   }
172 
173   LivePhysRegs.clear();
174   return AnyChanges;
175 }
176