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
23#include "llvm/CodeGen/Passes.h"
24#include "llvm/ADT/DepthFirstIterator.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/CodeGen/MachineDominators.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineLoopInfo.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/IR/CFG.h"
32#include "llvm/IR/Constant.h"
33#include "llvm/IR/Dominators.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Type.h"
37#include "llvm/Pass.h"
38#include "llvm/Target/TargetInstrInfo.h"
39using namespace llvm;
40
41namespace {
42  class UnreachableBlockElim : public FunctionPass {
43    bool runOnFunction(Function &F) override;
44  public:
45    static char ID; // Pass identification, replacement for typeid
46    UnreachableBlockElim() : FunctionPass(ID) {
47      initializeUnreachableBlockElimPass(*PassRegistry::getPassRegistry());
48    }
49
50    void getAnalysisUsage(AnalysisUsage &AU) const override {
51      AU.addPreserved<DominatorTreeWrapperPass>();
52    }
53  };
54}
55char UnreachableBlockElim::ID = 0;
56INITIALIZE_PASS(UnreachableBlockElim, "unreachableblockelim",
57                "Remove unreachable blocks from the CFG", false, false)
58
59FunctionPass *llvm::createUnreachableBlockEliminationPass() {
60  return new UnreachableBlockElim();
61}
62
63bool UnreachableBlockElim::runOnFunction(Function &F) {
64  SmallPtrSet<BasicBlock*, 8> Reachable;
65
66  // Mark all reachable blocks.
67  for (BasicBlock *BB : depth_first_ext(&F, Reachable))
68    (void)BB/* Mark all reachable blocks */;
69
70  // Loop over all dead blocks, remembering them and deleting all instructions
71  // in them.
72  std::vector<BasicBlock*> DeadBlocks;
73  for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
74    if (!Reachable.count(&*I)) {
75      BasicBlock *BB = &*I;
76      DeadBlocks.push_back(BB);
77      while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
78        PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
79        BB->getInstList().pop_front();
80      }
81      for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
82        (*SI)->removePredecessor(BB);
83      BB->dropAllReferences();
84    }
85
86  // Actually remove the blocks now.
87  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i) {
88    DeadBlocks[i]->eraseFromParent();
89  }
90
91  return !DeadBlocks.empty();
92}
93
94
95namespace {
96  class UnreachableMachineBlockElim : public MachineFunctionPass {
97    bool runOnMachineFunction(MachineFunction &F) override;
98    void getAnalysisUsage(AnalysisUsage &AU) const override;
99    MachineModuleInfo *MMI;
100  public:
101    static char ID; // Pass identification, replacement for typeid
102    UnreachableMachineBlockElim() : MachineFunctionPass(ID) {}
103  };
104}
105char UnreachableMachineBlockElim::ID = 0;
106
107INITIALIZE_PASS(UnreachableMachineBlockElim, "unreachable-mbb-elimination",
108  "Remove unreachable machine basic blocks", false, false)
109
110char &llvm::UnreachableMachineBlockElimID = UnreachableMachineBlockElim::ID;
111
112void UnreachableMachineBlockElim::getAnalysisUsage(AnalysisUsage &AU) const {
113  AU.addPreserved<MachineLoopInfo>();
114  AU.addPreserved<MachineDominatorTree>();
115  MachineFunctionPass::getAnalysisUsage(AU);
116}
117
118bool UnreachableMachineBlockElim::runOnMachineFunction(MachineFunction &F) {
119  SmallPtrSet<MachineBasicBlock*, 8> Reachable;
120  bool ModifiedPHI = false;
121
122  MMI = getAnalysisIfAvailable<MachineModuleInfo>();
123  MachineDominatorTree *MDT = getAnalysisIfAvailable<MachineDominatorTree>();
124  MachineLoopInfo *MLI = getAnalysisIfAvailable<MachineLoopInfo>();
125
126  // Mark all reachable blocks.
127  for (MachineBasicBlock *BB : depth_first_ext(&F, Reachable))
128    (void)BB/* Mark all reachable blocks */;
129
130  // Loop over all dead blocks, remembering them and deleting all instructions
131  // in them.
132  std::vector<MachineBasicBlock*> DeadBlocks;
133  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
134    MachineBasicBlock *BB = &*I;
135
136    // Test for deadness.
137    if (!Reachable.count(BB)) {
138      DeadBlocks.push_back(BB);
139
140      // Update dominator and loop info.
141      if (MLI) MLI->removeBlock(BB);
142      if (MDT && MDT->getNode(BB)) MDT->eraseNode(BB);
143
144      while (BB->succ_begin() != BB->succ_end()) {
145        MachineBasicBlock* succ = *BB->succ_begin();
146
147        MachineBasicBlock::iterator start = succ->begin();
148        while (start != succ->end() && start->isPHI()) {
149          for (unsigned i = start->getNumOperands() - 1; i >= 2; i-=2)
150            if (start->getOperand(i).isMBB() &&
151                start->getOperand(i).getMBB() == BB) {
152              start->RemoveOperand(i);
153              start->RemoveOperand(i-1);
154            }
155
156          start++;
157        }
158
159        BB->removeSuccessor(BB->succ_begin());
160      }
161    }
162  }
163
164  // Actually remove the blocks now.
165  for (unsigned i = 0, e = DeadBlocks.size(); i != e; ++i)
166    DeadBlocks[i]->eraseFromParent();
167
168  // Cleanup PHI nodes.
169  for (MachineFunction::iterator I = F.begin(), E = F.end(); I != E; ++I) {
170    MachineBasicBlock *BB = &*I;
171    // Prune unneeded PHI entries.
172    SmallPtrSet<MachineBasicBlock*, 8> preds(BB->pred_begin(),
173                                             BB->pred_end());
174    MachineBasicBlock::iterator phi = BB->begin();
175    while (phi != BB->end() && phi->isPHI()) {
176      for (unsigned i = phi->getNumOperands() - 1; i >= 2; i-=2)
177        if (!preds.count(phi->getOperand(i).getMBB())) {
178          phi->RemoveOperand(i);
179          phi->RemoveOperand(i-1);
180          ModifiedPHI = true;
181        }
182
183      if (phi->getNumOperands() == 3) {
184        unsigned Input = phi->getOperand(1).getReg();
185        unsigned Output = phi->getOperand(0).getReg();
186
187        MachineInstr* temp = phi;
188        ++phi;
189        temp->eraseFromParent();
190        ModifiedPHI = true;
191
192        if (Input != Output) {
193          MachineRegisterInfo &MRI = F.getRegInfo();
194          MRI.constrainRegClass(Input, MRI.getRegClass(Output));
195          MRI.replaceRegWith(Output, Input);
196        }
197
198        continue;
199      }
200
201      ++phi;
202    }
203  }
204
205  F.RenumberBlocks();
206
207  return (!DeadBlocks.empty() || ModifiedPHI);
208}
209