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
31#include "llvm/CodeGen/Passes.h"
33#include "llvm/IR/Dominators.h"
35#include "llvm/Pass.h"
37using namespace llvm;
38
39namespace {
40class UnreachableBlockElimLegacyPass : public FunctionPass {
41 bool runOnFunction(Function &F) override {
43 }
44
45public:
46 static char ID; // Pass identification, replacement for typeid
47 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
50 }
51
52 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 AU.addPreserved<DominatorTreeWrapperPass>();
54 }
55};
56}
57char UnreachableBlockElimLegacyPass::ID = 0;
58INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
59 "Remove unreachable blocks from the CFG", false, false)
60
62 return new UnreachableBlockElimLegacyPass();
63}
64
74
75namespace {
76class UnreachableMachineBlockElim {
78 MachineLoopInfo *MLI;
79
80public:
81 UnreachableMachineBlockElim(MachineDominatorTree *MDT, MachineLoopInfo *MLI)
82 : MDT(MDT), MLI(MLI) {}
83 bool run(MachineFunction &MF);
84};
85
86class UnreachableMachineBlockElimLegacy : public MachineFunctionPass {
87 bool runOnMachineFunction(MachineFunction &F) override;
88 void getAnalysisUsage(AnalysisUsage &AU) const override;
89
90public:
91 static char ID; // Pass identification, replacement for typeid
92 UnreachableMachineBlockElimLegacy() : MachineFunctionPass(ID) {}
93};
94} // namespace
95
96char UnreachableMachineBlockElimLegacy::ID = 0;
97
98INITIALIZE_PASS(UnreachableMachineBlockElimLegacy,
99 "unreachable-mbb-elimination",
100 "Remove unreachable machine basic blocks", false, false)
101
103 UnreachableMachineBlockElimLegacy::ID;
104
105void UnreachableMachineBlockElimLegacy::getAnalysisUsage(
106 AnalysisUsage &AU) const {
107 AU.addPreserved<MachineLoopInfoWrapperPass>();
108 AU.addPreserved<MachineDominatorTreeWrapperPass>();
110}
111
116 auto *MLI = AM.getCachedResult<MachineLoopAnalysis>(MF);
117
118 if (!UnreachableMachineBlockElim(MDT, MLI).run(MF))
119 return PreservedAnalyses::all();
120
123 .preserve<MachineDominatorTreeAnalysis>();
124}
125
126bool UnreachableMachineBlockElimLegacy::runOnMachineFunction(
127 MachineFunction &MF) {
129 getAnalysisIfAvailable<MachineDominatorTreeWrapperPass>();
130 MachineDominatorTree *MDT = MDTWrapper ? &MDTWrapper->getDomTree() : nullptr;
131 MachineLoopInfoWrapperPass *MLIWrapper =
132 getAnalysisIfAvailable<MachineLoopInfoWrapperPass>();
133 MachineLoopInfo *MLI = MLIWrapper ? &MLIWrapper->getLI() : nullptr;
134
135 return UnreachableMachineBlockElim(MDT, MLI).run(MF);
136}
137
138bool UnreachableMachineBlockElim::run(MachineFunction &F) {
140 bool ModifiedPHI = false;
141
142 // Mark all reachable blocks.
143 for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
144 (void)BB/* Mark all reachable blocks */;
145
146 // Loop over all dead blocks, remembering them and deleting all instructions
147 // in them.
148 std::vector<MachineBasicBlock*> DeadBlocks;
149 for (MachineBasicBlock &BB : F) {
150 // Test for deadness.
151 if (!Reachable.count(&BB)) {
152 DeadBlocks.push_back(&BB);
153
154 // Update dominator and loop info.
155 if (MLI) MLI->removeBlock(&BB);
156 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
157
158 while (!BB.succ_empty()) {
159 (*BB.succ_begin())->removePHIsIncomingValuesForPredecessor(BB);
160 BB.removeSuccessor(BB.succ_begin());
161 }
162 }
163 }
164
165 // Actually remove the blocks now.
166 for (MachineBasicBlock *BB : DeadBlocks) {
167 // Remove any call information for calls in the block.
168 for (auto &I : BB->instrs())
169 if (I.shouldUpdateAdditionalCallInfo())
170 BB->getParent()->eraseAdditionalCallInfo(&I);
171
172 BB->eraseFromParent();
173 }
174
175 // Cleanup PHI nodes.
176 for (MachineBasicBlock &BB : F) {
177 // Prune unneeded PHI entries.
179 BB.predecessors());
180 for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
181 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
182 if (!preds.count(Phi.getOperand(i).getMBB())) {
183 Phi.removeOperand(i);
184 Phi.removeOperand(i - 1);
185 ModifiedPHI = true;
186 }
187 }
188
189 if (Phi.getNumOperands() == 3) {
190 const MachineOperand &Input = Phi.getOperand(1);
191 const MachineOperand &Output = Phi.getOperand(0);
192 Register InputReg = Input.getReg();
193 Register OutputReg = Output.getReg();
194 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
195 ModifiedPHI = true;
196
197 if (InputReg != OutputReg) {
198 MachineRegisterInfo &MRI = F.getRegInfo();
199 unsigned InputSub = Input.getSubReg();
200 if (InputSub == 0 &&
201 MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
202 !Input.isUndef()) {
203 MRI.replaceRegWith(OutputReg, InputReg);
204 } else {
205 // The input register to the PHI has a subregister or it can't be
206 // constrained to the proper register class or it is undef:
207 // insert a COPY instead of simply replacing the output
208 // with the input.
209 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
210 BuildMI(BB, BB.getFirstNonPHI(), Phi.getDebugLoc(),
211 TII->get(TargetOpcode::COPY), OutputReg)
212 .addReg(InputReg, getRegState(Input), InputSub);
213 }
214 Phi.eraseFromParent();
215 }
216 }
217 }
218 }
219
220 F.RenumberBlocks();
221 if (MDT)
222 MDT->updateBlockNumbers();
223
224 return (!DeadBlocks.empty() || ModifiedPHI);
225}
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:55
#define I(x, y, z)
Definition MD5.cpp:58
#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:284
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.
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:19
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:634
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...