LLVM  4.0.0
UnreachableBlockElim.cpp
Go to the documentation of this file.
1 //===-- UnreachableBlockElim.cpp - Remove unreachable blocks for codegen --===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass is an extremely simple version of the SimplifyCFG pass. Its sole
11 // job is to delete LLVM basic blocks that are not reachable from the entry
12 // node. To do this, it performs a simple depth first traversal of the CFG,
13 // then deletes any unvisited nodes.
14 //
15 // Note that this pass is really a hack. In particular, the instruction
16 // selectors for various targets should just not generate code for unreachable
17 // blocks. Until LLVM has a more systematic way of defining instruction
18 // selectors, however, we cannot really expect them to handle additional
19 // complexity.
20 //
21 //===----------------------------------------------------------------------===//
22 
25 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/IR/CFG.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/Pass.h"
40 using namespace llvm;
41 
44 
45  // Mark all reachable blocks.
46  for (BasicBlock *BB : depth_first_ext(&F, Reachable))
47  (void)BB/* Mark all reachable blocks */;
48 
49  // Loop over all dead blocks, remembering them and deleting all instructions
50  // in them.
51  std::vector<BasicBlock*> DeadBlocks;
52  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
53  if (!Reachable.count(&*I)) {
54  BasicBlock *BB = &*I;
55  DeadBlocks.push_back(BB);
56  while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
57  PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
58  BB->getInstList().pop_front();
59  }
60  for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
61  (*SI)->removePredecessor(BB);
62  BB->dropAllReferences();
63  }
64 
65  // Actually remove the blocks now.
66  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) {
67  DeadBlocks[i]->eraseFromParent();
68  }
69 
70  return !DeadBlocks.empty();
71 }
72 
73 namespace {
74 class UnreachableBlockElimLegacyPass : public FunctionPass {
75  bool runOnFunction(Function &F) override {
76  return eliminateUnreachableBlock(F);
77  }
78 
79 public:
80  static char ID; // Pass identification, replacement for typeid
81  UnreachableBlockElimLegacyPass() : FunctionPass(ID) {
84  }
85 
86  void getAnalysisUsage(AnalysisUsage &AU) const override {
88  }
89 };
90 }
92 INITIALIZE_PASS(UnreachableBlockElimLegacyPass, "unreachableblockelim",
93  "Remove unreachable blocks from the CFG", false, false)
94 
96  return new UnreachableBlockElimLegacyPass();
97 }
98 
101  bool Changed = eliminateUnreachableBlock(F);
102  if (!Changed)
103  return PreservedAnalyses::all();
106  return PA;
107 }
108 
109 namespace {
110  class UnreachableMachineBlockElim : public MachineFunctionPass {
111  bool runOnMachineFunction(MachineFunction &F) override;
112  void getAnalysisUsage(AnalysisUsage &AU) const override;
113  MachineModuleInfo *MMI;
114  public:
115  static char ID; // Pass identification, replacement for typeid
116  UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
117  };
118 }
120 
121 INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
122  "Remove unreachable machine basic blocks", false, false)
123 
124 char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
125 
126 void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
127  AU.addPreserved<MachineLoopInfo>();
128  AU.addPreserved<MachineDominatorTree>();
130 }
131 
132 bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
134  bool ModifiedPHI = false;
135 
136  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
137  MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
138  MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
139 
140  // Mark all reachable blocks.
141  for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
142  (void)BB/* Mark all reachable blocks */;
143 
144  // Loop over all dead blocks, remembering them and deleting all instructions
145  // in them.
146  std::vector<MachineBasicBlock*> DeadBlocks;
147  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
148  MachineBasicBlock *BB = &*I;
149 
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_begin() != BB->succ_end()) {
159  MachineBasicBlock* succ = *BB->succ_begin();
160 
161  MachineBasicBlock::iterator start = succ->begin();
162  while (start != succ->end() && start->isPHI()) {
163  for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
164  if (start->getOperand(i).isMBB() &&
165  start->getOperand(i).getMBB() == BB) {
166  start->RemoveOperand(i);
167  start->RemoveOperand(i-1);
168  }
169 
170  start++;
171  }
172 
173  BB->removeSuccessor(BB->succ_begin());
174  }
175  }
176  }
177 
178  // Actually remove the blocks now.
179  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
180  DeadBlocks[i]->eraseFromParent();
181 
182  // Cleanup PHI nodes.
183  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
184  MachineBasicBlock *BB = &*I;
185  // Prune unneeded PHI entries.
187  BB->pred_end());
189  while (phi != BB->end() && phi->isPHI()) {
190  for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
191  if (!preds.count(phi->getOperand(i).getMBB())) {
192  phi->RemoveOperand(i);
193  phi->RemoveOperand(i-1);
194  ModifiedPHI = true;
195  }
196 
197  if (phi->getNumOperands() == 3) {
198  unsigned Input = phi->getOperand(1).getReg();
199  unsigned Output = phi->getOperand(0).getReg();
200 
201  phi++->eraseFromParent();
202  ModifiedPHI = true;
203 
204  if (Input != Output) {
206  MRI.constrainRegClass(Input, MRI.getRegClass(Output));
207  MRI.replaceRegWith(Output, Input);
208  }
209 
210  continue;
211  }
212 
213  ++phi;
214  }
215  }
216 
217  F.RenumberBlocks();
218 
219  return (!DeadBlocks.empty() || ModifiedPHI);
220 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
size_t i
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
iterator end()
Definition: Function.h:537
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:380
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:189
void initializeUnreachableBlockElimLegacyPassPass(PassRegistry &)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:195
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:228
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
static bool eliminateUnreachableBlock(Function &F)
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:106
char & UnreachableMachineBlockElimID
UnreachableMachineBlockElimination - This pass removes unreachable machine basic blocks.
#define F(x, y, z)
Definition: MD5.cpp:51
INITIALIZE_PASS(UnreachableBlockElimLegacyPass,"unreachableblockelim","Remove unreachable blocks from the CFG", false, false) FunctionPass *llvm
FunctionPass * createUnreachableBlockEliminationPass()
createUnreachableBlockEliminationPass - The LLVM code generator does not work well with unreachable b...
iterator begin()
Definition: Function.h:535
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:109
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
unsigned const MachineRegisterInfo * MRI
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
iterator_range< df_ext_iterator< T, SetTy > > depth_first_ext(const T &G, SetTy &S)
Represent the analysis usage information of a pass.
void pop_front()
Definition: ilist.h:327
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:249
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:425
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:54
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:120
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:217
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
Definition: BasicBlock.cpp:219
This class contains meta information specific to a module.