LLVM 22.0.0git
UnreachableBlockElim.cpp
Go to the documentation of this file.
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
32#include "llvm/CodeGen/Passes.h"
34#include "llvm/IR/Dominators.h"
36#include "llvm/Pass.h"
38using namespace llvm;
39
40namespace {
41class UnreachableBlockElimLegacyPass : public FunctionPass {
42 bool runOnFunction(Function &F) override {
44 }
45
46public:
47 static char ID; // Pass identification, replacement for typeid
48 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
51 }
52
53 void getAnalysisUsage(AnalysisUsage &AU) const override {
54 AU.addPreserved<DominatorTreeWrapperPass>();
55 }
56};
57}
58char UnreachableBlockElimLegacyPass::ID = 0;
59INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
60 "Remove unreachable blocks from the CFG", false, false)
61
63 return new UnreachableBlockElimLegacyPass();
64}
65
75
76namespace {
77class UnreachableMachineBlockElim {
80 MachineLoopInfo *MLI;
81
82public:
83 UnreachableMachineBlockElim(MachineDominatorTree *MDT,
85 MachineLoopInfo *MLI)
86 : MDT(MDT), MPDT(MPDT), MLI(MLI) {}
87 bool run(MachineFunction &MF);
88};
89
90class UnreachableMachineBlockElimLegacy : public MachineFunctionPass {
91 bool runOnMachineFunction(MachineFunction &F) override;
92 void getAnalysisUsage(AnalysisUsage &AU) const override;
93
94public:
95 static char ID; // Pass identification, replacement for typeid
96 UnreachableMachineBlockElimLegacy() : MachineFunctionPass(ID) {}
97};
98} // namespace
99
100char UnreachableMachineBlockElimLegacy::ID = 0;
101
102INITIALIZE_PASS(UnreachableMachineBlockElimLegacy,
103 "unreachable-mbb-elimination",
104 "Remove unreachable machine basic blocks", false, false)
105
107 UnreachableMachineBlockElimLegacy::ID;
108
109void UnreachableMachineBlockElimLegacy::getAnalysisUsage(
110 AnalysisUsage &AU) const {
111 AU.addPreserved<MachineLoopInfoWrapperPass>();
112 AU.addPreserved<MachineDominatorTreeWrapperPass>();
113 AU.addPreserved<MachinePostDominatorTreeWrapperPass>();
115}
116
122 auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(MF);
123
124 if (!UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF))
125 return PreservedAnalyses::all();
126
129 .preserve<MachineDominatorTreeAnalysis>()
131}
132
133bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
134 MachineFunction &MF) {
136 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
138 getAnalysisIfAvailable<MachinePostDominatorTreeWrapperPass>();
139 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
141 MPDTWrapper ? &MPDTWrapper->getPostDomTree() : nullptr;
142 MachineLoopInfoWrapperPass *MLIWrapper =
143 getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
144 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
145
146 return UnreachableMachineBlockElim(MDT, MPDT, MLI).run(MF);
147}
148
149bool UnreachableMachineBlockElim::run(MachineFunction &F) {
151 bool ModifiedPHI = false;
152
153 // Mark all reachable blocks.
154 for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
155 (void)BB/* Mark all reachable blocks */;
156
157 // Loop over all dead blocks, remembering them and deleting all instructions
158 // in them.
159 std::vector<MachineBasicBlock*> DeadBlocks;
160 for (MachineBasicBlock &BB : F) {
161 // Test for deadness.
162 if (!Reachable.count(&BB)) {
163 DeadBlocks.push_back(&BB);
164
165 // Update dominator and loop info.
166 if (MLI) MLI->removeBlock(&BB);
167 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
168 if (MPDT && MPDT->getNode(&BB))
169 MPDT->eraseNode(&BB);
170
171 while (!BB.succ_empty()) {
172 (*BB.succ_begin())->removePHIsIncomingValuesForPredecessor(BB);
173 BB.removeSuccessor(BB.succ_begin());
174 }
175 }
176 }
177
178 // Actually remove the blocks now.
179 for (MachineBasicBlock *BB : DeadBlocks) {
180 // Remove any call information for calls in the block.
181 for (auto &I : BB->instrs())
182 if (I.shouldUpdateAdditionalCallInfo())
183 BB->getParent()->eraseAdditionalCallInfo(&I);
184
185 BB->eraseFromParent();
186 }
187
188 // Cleanup PHI nodes.
189 for (MachineBasicBlock &BB : F) {
190 // Prune unneeded PHI entries.
192 BB.predecessors());
193 for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
194 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
195 if (!preds.count(Phi.getOperand(i).getMBB())) {
196 Phi.removeOperand(i);
197 Phi.removeOperand(i - 1);
198 ModifiedPHI = true;
199 }
200 }
201
202 if (Phi.getNumOperands() == 3) {
203 const MachineOperand &Input = Phi.getOperand(1);
204 const MachineOperand &Output = Phi.getOperand(0);
205 Register InputReg = Input.getReg();
206 Register OutputReg = Output.getReg();
207 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
208 ModifiedPHI = true;
209
210 if (InputReg != OutputReg) {
211 MachineRegisterInfo &MRI = F.getRegInfo();
212 unsigned InputSub = Input.getSubReg();
213 if (InputSub == 0 &&
214 MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
215 !Input.isUndef()) {
216 MRI.replaceRegWith(OutputReg, InputReg);
217 } else {
218 // The input register to the PHI has a subregister or it can't be
219 // constrained to the proper register class or it is undef:
220 // insert a COPY instead of simply replacing the output
221 // with the input.
222 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
223 BuildMI(BB, BB.getFirstNonPHI(), Phi.getDebugLoc(),
224 TII->get(TargetOpcode::COPY), OutputReg)
225 .addReg(InputReg, getRegState(Input), InputSub);
226 }
227 Phi.eraseFromParent();
228 }
229 }
230 }
231 }
232
233 F.RenumberBlocks();
234 if (MDT)
235 MDT->updateBlockNumbers();
236
237 if (MPDT)
238 MPDT->updateBlockNumbers();
239
240 return (!DeadBlocks.empty() || ModifiedPHI);
241}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
static bool runOnFunction(Function &F, bool PostInlining)
const HexagonInstrInfo * TII
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the SmallPtrSet class.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:283
std::enable_if_t< GraphHasNodeNumbers< T * >, void > updateBlockNumbers()
Update dominator tree after renumbering blocks.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
Register getReg() const
getReg - Returns the register number.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Wrapper class representing virtual and physical registers.
Definition Register.h:20
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
TargetInstrInfo - Interface to description of machine instruction set.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PreservedAnalyses run(MachineFunction &F, MachineFunctionAnalysisManager &AM)
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr from_range_t from_range
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI void initializeUnreachableBlockElimLegacyPassPass(PassRegistry &)
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
LLVM_ABI bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete all basic blocks from F that are not reachable from its entry node.
unsigned getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...