LLVM 19.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
30#include "llvm/CodeGen/Passes.h"
32#include "llvm/IR/Dominators.h"
34#include "llvm/Pass.h"
36using namespace llvm;
37
38namespace {
39class UnreachableBlockElimLegacyPass : public FunctionPass {
40 bool runOnFunction(Function &F) override {
42 }
43
44public:
45 static char ID; // Pass identification, replacement for typeid
46 UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
49 }
50
51 void getAnalysisUsage(AnalysisUsage &AU) const override {
53 }
54};
55}
56char UnreachableBlockElimLegacyPass::ID = 0;
57INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
58 "Remove unreachable blocks from the CFG", false, false)
59
61 return new UnreachableBlockElimLegacyPass();
62}
63
66 bool Changed = llvm::EliminateUnreachableBlocks(F);
67 if (!Changed)
71 return PA;
72}
73
74namespace {
75 class UnreachableMachineBlockElim : public MachineFunctionPass {
76 bool runOnMachineFunction(MachineFunction &F) override;
77 void getAnalysisUsage(AnalysisUsage &AU) const override;
78
79 public:
80 static char ID; // Pass identification, replacement for typeid
81 UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
82 };
83}
84char UnreachableMachineBlockElim::ID = 0;
85
86INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
87 "Remove unreachable machine basic blocks", false, false)
88
89char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
90
91void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addPreserved<MachineLoopInfo>();
93 AU.addPreserved<MachineDominatorTree>();
95}
96
97bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
99 bool ModifiedPHI = false;
100
101 MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
102 MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
103
104 // Mark all reachable blocks.
105 for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
106 (void)BB/* Mark all reachable blocks */;
107
108 // Loop over all dead blocks, remembering them and deleting all instructions
109 // in them.
110 std::vector<MachineBasicBlock*> DeadBlocks;
111 for (MachineBasicBlock &BB : F) {
112 // Test for deadness.
113 if (!Reachable.count(&BB)) {
114 DeadBlocks.push_back(&BB);
115
116 // Update dominator and loop info.
117 if (MLI) MLI->removeBlock(&BB);
118 if (MDT && MDT->getNode(&BB)) MDT->eraseNode(&BB);
119
120 while (!BB.succ_empty()) {
121 MachineBasicBlock* succ = *BB.succ_begin();
122
123 for (MachineInstr &Phi : succ->phis()) {
124 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
125 if (Phi.getOperand(i).isMBB() &&
126 Phi.getOperand(i).getMBB() == &BB) {
127 Phi.removeOperand(i);
128 Phi.removeOperand(i - 1);
129 }
130 }
131 }
132
133 BB.removeSuccessor(BB.succ_begin());
134 }
135 }
136 }
137
138 // Actually remove the blocks now.
139 for (MachineBasicBlock *BB : DeadBlocks) {
140 // Remove any call site information for calls in the block.
141 for (auto &I : BB->instrs())
142 if (I.shouldUpdateCallSiteInfo())
143 BB->getParent()->eraseCallSiteInfo(&I);
144
145 BB->eraseFromParent();
146 }
147
148 // Cleanup PHI nodes.
149 for (MachineBasicBlock &BB : F) {
150 // Prune unneeded PHI entries.
151 SmallPtrSet<MachineBasicBlock*, 8> preds(BB.pred_begin(),
152 BB.pred_end());
153 for (MachineInstr &Phi : make_early_inc_range(BB.phis())) {
154 for (unsigned i = Phi.getNumOperands() - 1; i >= 2; i -= 2) {
155 if (!preds.count(Phi.getOperand(i).getMBB())) {
156 Phi.removeOperand(i);
157 Phi.removeOperand(i - 1);
158 ModifiedPHI = true;
159 }
160 }
161
162 if (Phi.getNumOperands() == 3) {
163 const MachineOperand &Input = Phi.getOperand(1);
164 const MachineOperand &Output = Phi.getOperand(0);
165 Register InputReg = Input.getReg();
166 Register OutputReg = Output.getReg();
167 assert(Output.getSubReg() == 0 && "Cannot have output subregister");
168 ModifiedPHI = true;
169
170 if (InputReg != OutputReg) {
171 MachineRegisterInfo &MRI = F.getRegInfo();
172 unsigned InputSub = Input.getSubReg();
173 if (InputSub == 0 &&
174 MRI.constrainRegClass(InputReg, MRI.getRegClass(OutputReg)) &&
175 !Input.isUndef()) {
176 MRI.replaceRegWith(OutputReg, InputReg);
177 } else {
178 // The input register to the PHI has a subregister or it can't be
179 // constrained to the proper register class or it is undef:
180 // insert a COPY instead of simply replacing the output
181 // with the input.
182 const TargetInstrInfo *TII = F.getSubtarget().getInstrInfo();
183 BuildMI(BB, BB.getFirstNonPHI(), Phi.getDebugLoc(),
184 TII->get(TargetOpcode::COPY), OutputReg)
185 .addReg(InputReg, getRegState(Input), InputSub);
186 }
187 Phi.eraseFromParent();
188 }
189 }
190 }
191 }
192
193 F.RenumberBlocks();
194
195 return (!DeadBlocks.empty() || ModifiedPHI);
196}
unsigned const MachineRegisterInfo * MRI
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
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:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallPtrSet class.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:348
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:275
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:313
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
MachineDomTreeNode * getNode(MachineBasicBlock *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void eraseNode(MachineBasicBlock *BB)
eraseNode - Removes a node from the dominator tree.
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.
Definition: MachineInstr.h:69
void removeBlock(MachineBasicBlock *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
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 PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:98
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserve()
Mark an analysis as preserved.
Definition: Analysis.h:129
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
TargetInstrInfo - Interface to description of machine instruction set.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
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.
Definition: AddressRanges.h:18
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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:665
void initializeUnreachableBlockElimLegacyPassPass(PassRegistry &)
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.
char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.