xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/UnreachableBlockElim.cpp (revision f976241773df2260e6170317080761d1c5814fe5)
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/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/CodeGen/TargetInstrInfo.h"
33 #include "llvm/IR/CFG.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 using namespace llvm;
42 
43 namespace {
44 class UnreachableBlockElimLegacyPass : public FunctionPass {
45   bool runOnFunction(Function &F) override {
46     return llvm::EliminateUnreachableBlocks(F);
47   }
48 
49 public:
50   static char ID; // Pass identification, replacement for typeid
51   UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
52     initializeUnreachableBlockElimLegacyPassPass(
53         *PassRegistry::getPassRegistry());
54   }
55 
56   void getAnalysisUsage(AnalysisUsage &AU) const override {
57     AU.addPreserved<DominatorTreeWrapperPass>();
58   }
59 };
60 }
61 char UnreachableBlockElimLegacyPass::ID = 0;
62 INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
63                 "Remove unreachable blocks from the CFG", false, false)
64 
65 FunctionPass *llvm::createUnreachableBlockEliminationPass() {
66   return new UnreachableBlockElimLegacyPass();
67 }
68 
69 PreservedAnalyses UnreachableBlockElimPass::run(Function &F,
70                                                 FunctionAnalysisManager &AM) {
71   bool Changed = llvm::EliminateUnreachableBlocks(F);
72   if (!Changed)
73     return PreservedAnalyses::all();
74   PreservedAnalyses PA;
75   PA.preserve<DominatorTreeAnalysis>();
76   return PA;
77 }
78 
79 namespace {
80   class UnreachableMachineBlockElim : public MachineFunctionPass {
81     bool runOnMachineFunction(MachineFunction &F) override;
82     void getAnalysisUsage(AnalysisUsage &AU) const override;
83     MachineModuleInfo *MMI;
84   public:
85     static char ID; // Pass identification, replacement for typeid
86     UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
87   };
88 }
89 char UnreachableMachineBlockElim::ID = 0;
90 
91 INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
92   "Remove unreachable machine basic blocks", false, false)
93 
94 char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
95 
96 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
97   AU.addPreserved<MachineLoopInfo>();
98   AU.addPreserved<MachineDominatorTree>();
99   MachineFunctionPass::getAnalysisUsage(AU);
100 }
101 
102 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
103   df_iterator_default_set<MachineBasicBlock*> Reachable;
104   bool ModifiedPHI = false;
105 
106   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
107   MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
108   MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
109 
110   // Mark all reachable blocks.
111   for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
112     (void)BB/* Mark all reachable blocks */;
113 
114   // Loop over all dead blocks, remembering them and deleting all instructions
115   // in them.
116   std::vector<MachineBasicBlock*> DeadBlocks;
117   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
118     MachineBasicBlock *BB = &*I;
119 
120     // Test for deadness.
121     if (!Reachable.count(BB)) {
122       DeadBlocks.push_back(BB);
123 
124       // Update dominator and loop info.
125       if (MLI) MLI->removeBlock(BB);
126       if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB);
127 
128       while (BB->succ_begin() != BB->succ_end()) {
129         MachineBasicBlock* succ = *BB->succ_begin();
130 
131         MachineBasicBlock::iterator start = succ->begin();
132         while (start != succ->end() && start->isPHI()) {
133           for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
134             if (start->getOperand(i).isMBB() &&
135                 start->getOperand(i).getMBB() == BB) {
136               start->RemoveOperand(i);
137               start->RemoveOperand(i-1);
138             }
139 
140           start++;
141         }
142 
143         BB->removeSuccessor(BB->succ_begin());
144       }
145     }
146   }
147 
148   // Actually remove the blocks now.
149   for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
150     DeadBlocks[i]->eraseFromParent();
151 
152   // Cleanup PHI nodes.
153   for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
154     MachineBasicBlock *BB = &*I;
155     // Prune unneeded PHI entries.
156     SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(),
157                                              BB->pred_end());
158     MachineBasicBlock::iterator phi = BB->begin();
159     while (phi != BB->end() && phi->isPHI()) {
160       for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
161         if (!preds.count(phi->getOperand(i).getMBB())) {
162           phi->RemoveOperand(i);
163           phi->RemoveOperand(i-1);
164           ModifiedPHI = true;
165         }
166 
167       if (phi->getNumOperands() == 3) {
168         const MachineOperand &Input = phi->getOperand(1);
169         const MachineOperand &Output = phi->getOperand(0);
170         unsigned InputReg = Input.getReg();
171         unsigned OutputReg = Output.getReg();
172         assert(Output.getSubReg() == 0 && "Cannot have output subregister");
173         ModifiedPHI = true;
174 
175         if (InputReg != OutputReg) {
176           MachineRegisterInfo &MRI = F.getRegInfo();
177           unsigned InputSub = Input.getSubReg();
178           if (InputSub == 0 &&
179               MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
180               !Input.isUndef()) {
181             MRI.replaceRegWith(OutputReg, InputReg);
182           } else {
183             // The input register to the PHI has a subregister or it can't be
184             // constrained to the proper register class or it is undef:
185             // insert a COPY instead of simply replacing the output
186             // with the input.
187             const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
188             BuildMI(*BB, BB->getFirstNonPHI(), phi->getDebugLoc(),
189                     TII->get(TargetOpcode::COPY), OutputReg)
190                 .addReg(InputReg, getRegState(Input), InputSub);
191           }
192           phi++->eraseFromParent();
193         }
194         continue;
195       }
196 
197       ++phi;
198     }
199   }
200 
201   F.RenumberBlocks();
202 
203   return (!DeadBlocks.empty() || ModifiedPHI);
204 }
205