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