xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/UnreachableBlockElim.cpp (revision 770cf0a5f02dc8983a89c6568d741fbc25baa999)
1 //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
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 is an extremely simple version of the SimplifyCFG pass.  Its sole
10 // job is to delete LLVM basic blocks that are not reachable from the entry
11 // node.  To do this, it performs a simple depth first traversal of the CFG,
12 // then deletes any unvisited nodes.
13 //
14 // Note that this pass is really a hack.  In particular, the instruction
15 // selectors for various targets should just not generate code for unreachable
16 // blocks.  Until LLVM has a more systematic way of defining instruction
17 // selectors, however, we cannot really expect them to handle additional
18 // complexity.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "llvm/CodeGen/UnreachableBlockElim.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/TargetInstrInfo.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 using namespace llvm;
37 
38 namespace {
39 class UnreachableBlockElimLegacyPass : public FunctionPass {
40   bool runOnFunction(Function &F) override {
41     return llvm::EliminateUnreachableBlocks(F);
42   }
43 
44 public:
45   static char ID; // Pass identification, replacement for typeid
46   UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
47     initializeUnreachableBlockElimLegacyPassPass(
48         *PassRegistry::getPassRegistry());
49   }
50 
51   void getAnalysisUsage(AnalysisUsage &AU) const override {
52     AU.addPreserved<DominatorTreeWrapperPass>();
53   }
54 };
55 }
56 char UnreachableBlockElimLegacyPass::ID = 0;
57 INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
58                 "Remove unreachable blocks from the CFG", false, false)
59 
60 FunctionPass *llvm::createUnreachableBlockEliminationPass() {
61   return new UnreachableBlockElimLegacyPass();
62 }
63 
64 PreservedAnalyses UnreachableBlockElimPass::run(Function &F,
65                                                 FunctionAnalysisManager &AM) {
66   bool Changed = llvm::EliminateUnreachableBlocks(F);
67   if (!Changed)
68     return PreservedAnalyses::all();
69   PreservedAnalyses PA;
70   PA.preserve<DominatorTreeAnalysis>();
71   return PA;
72 }
73 
74 namespace {
75 class UnreachableMachineBlockElim {
76   MachineDominatorTree *MDT;
77   MachineLoopInfo *MLI;
78 
79 public:
80   UnreachableMachineBlockElim(MachineDominatorTree *MDT, MachineLoopInfo *MLI)
81       : MDT(MDT), MLI(MLI) {}
82   bool run(MachineFunction &MF);
83 };
84 
85 class UnreachableMachineBlockElimLegacy : public MachineFunctionPass {
86   bool runOnMachineFunction(MachineFunction &F) override;
87   void getAnalysisUsage(AnalysisUsage &AU) const override;
88 
89 public:
90   static char ID; // Pass identification, replacement for typeid
91   UnreachableMachineBlockElimLegacy() : MachineFunctionPass(ID) {}
92 };
93 } // namespace
94 
95 char UnreachableMachineBlockElimLegacy::ID = 0;
96 
97 INITIALIZE_PASS(UnreachableMachineBlockElimLegacy,
98                 "unreachable-mbb-elimination",
99                 "Remove unreachable machine basic blocks", false, false)
100 
101 char &llvm::UnreachableMachineBlockElimID =
102     UnreachableMachineBlockElimLegacy::ID;
103 
104 void UnreachableMachineBlockElimLegacy::getAnalysisUsage(
105     AnalysisUsage &AU) const {
106   AU.addPreserved<MachineLoopInfoWrapperPass>();
107   AU.addPreserved<MachineDominatorTreeWrapperPass>();
108   MachineFunctionPass::getAnalysisUsage(AU);
109 }
110 
111 PreservedAnalyses
112 UnreachableMachineBlockElimPass::run(MachineFunction &MF,
113                                      MachineFunctionAnalysisManager &AM) {
114   auto *MDT = AM.getCachedResult<MachineDominatorTreeAnalysis>(MF);
115   auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(MF);
116 
117   if (!UnreachableMachineBlockElim(MDT, MLI).run(MF))
118     return PreservedAnalyses::all();
119 
120   return getMachineFunctionPassPreservedAnalyses()
121       .preserve<MachineLoopAnalysis>()
122       .preserve<MachineDominatorTreeAnalysis>();
123 }
124 
125 bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
126     MachineFunction &MF) {
127   MachineDominatorTreeWrapperPass *MDTWrapper =
128       getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
129   MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
130   MachineLoopInfoWrapperPass *MLIWrapper =
131       getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
132   MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
133 
134   return UnreachableMachineBlockElim(MDT, MLI).run(MF);
135 }
136 
137 bool UnreachableMachineBlockElim::run(MachineFunction &F) {
138   df_iterator_default_set<MachineBasicBlock *> Reachable;
139   bool ModifiedPHI = false;
140 
141   // Mark all reachable blocks.
142   for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
143     (void)BB/* Mark all reachable blocks */;
144 
145   // Loop over all dead blocks, remembering them and deleting all instructions
146   // in them.
147   std::vector<MachineBasicBlock*> DeadBlocks;
148   for (MachineBasicBlock &BB : F) {
149     // Test for deadness.
150     if (!Reachable.count(&BB)) {
151       DeadBlocks.push_back(&BB);
152 
153       // Update dominator and loop info.
154       if (MLI) MLI->removeBlock(&BB);
155       if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
156 
157       while (!BB.succ_empty()) {
158         MachineBasicBlock* succ = *BB.succ_begin();
159 
160         for (MachineInstr &Phi : succ->phis()) {
161           for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
162             if (Phi.getOperand(i).isMBB() &&
163                 Phi.getOperand(i).getMBB() == &BB) {
164               Phi.removeOperand(i);
165               Phi.removeOperand(i - 1);
166             }
167           }
168         }
169 
170         BB.removeSuccessor(BB.succ_begin());
171       }
172     }
173   }
174 
175   // Actually remove the blocks now.
176   for (MachineBasicBlock *BB : DeadBlocks) {
177     // Remove any call information for calls in the block.
178     for (auto &I : BB->instrs())
179       if (I.shouldUpdateAdditionalCallInfo())
180         BB->getParent()->eraseAdditionalCallInfo(&I);
181 
182     BB->eraseFromParent();
183   }
184 
185   // Cleanup PHI nodes.
186   for (MachineBasicBlock &BB : F) {
187     // Prune unneeded PHI entries.
188     SmallPtrSet<MachineBasicBlock *, 8> preds(llvm::from_range,
189                                               BB.predecessors());
190     for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
191       for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
192         if (!preds.count(Phi.getOperand(i).getMBB())) {
193           Phi.removeOperand(i);
194           Phi.removeOperand(i - 1);
195           ModifiedPHI = true;
196         }
197       }
198 
199       if (Phi.getNumOperands() == 3) {
200         const MachineOperand &Input = Phi.getOperand(1);
201         const MachineOperand &Output = Phi.getOperand(0);
202         Register InputReg = Input.getReg();
203         Register OutputReg = Output.getReg();
204         assert(Output.getSubReg() == 0 && "Cannot have output subregister");
205         ModifiedPHI = true;
206 
207         if (InputReg != OutputReg) {
208           MachineRegisterInfo &MRI = F.getRegInfo();
209           unsigned InputSub = Input.getSubReg();
210           if (InputSub == 0 &&
211               MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
212               !Input.isUndef()) {
213             MRI.replaceRegWith(OutputReg, InputReg);
214           } else {
215             // The input register to the PHI has a subregister or it can't be
216             // constrained to the proper register class or it is undef:
217             // insert a COPY instead of simply replacing the output
218             // with the input.
219             const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
220             BuildMI(BB, BB.getFirstNonPHI(), Phi.getDebugLoc(),
221                     TII->get(TargetOpcode::COPY), OutputReg)
222                 .addReg(InputReg, getRegState(Input), InputSub);
223           }
224           Phi.eraseFromParent();
225         }
226       }
227     }
228   }
229 
230   F.RenumberBlocks();
231   if (MDT)
232     MDT->updateBlockNumbers();
233 
234   return (!DeadBlocks.empty() || ModifiedPHI);
235 }
236