Fix typo in comment.
[oota-llvm.git] / lib / Transforms / Scalar / CondPropagate.cpp
1 //===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass propagates information about conditional expressions through the
11 // program, allowing it to eliminate conditional branches in some cases.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "condprop"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/Local.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Type.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Streams.h"
27 using namespace llvm;
28
29 STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
30 STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
31
32 namespace {
33   struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
34     static char ID; // Pass identification, replacement for typeid
35     CondProp() : FunctionPass((intptr_t)&ID) {}
36
37     virtual bool runOnFunction(Function &F);
38
39     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.addRequiredID(BreakCriticalEdgesID);
41       //AU.addRequired<DominanceFrontier>();
42     }
43
44   private:
45     bool MadeChange;
46     void SimplifyBlock(BasicBlock *BB);
47     void SimplifyPredecessors(BranchInst *BI);
48     void SimplifyPredecessors(SwitchInst *SI);
49     void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
50   };
51   
52   char CondProp::ID = 0;
53   RegisterPass<CondProp> X("condprop", "Conditional Propagation");
54 }
55
56 FunctionPass *llvm::createCondPropagationPass() {
57   return new CondProp();
58 }
59
60 bool CondProp::runOnFunction(Function &F) {
61   bool EverMadeChange = false;
62
63   // While we are simplifying blocks, keep iterating.
64   do {
65     MadeChange = false;
66     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
67       SimplifyBlock(BB);
68     EverMadeChange = MadeChange;
69   } while (MadeChange);
70   return EverMadeChange;
71 }
72
73 void CondProp::SimplifyBlock(BasicBlock *BB) {
74   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
75     // If this is a conditional branch based on a phi node that is defined in
76     // this block, see if we can simplify predecessors of this block.
77     if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
78         cast<PHINode>(BI->getCondition())->getParent() == BB)
79       SimplifyPredecessors(BI);
80
81   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
82     if (isa<PHINode>(SI->getCondition()) &&
83         cast<PHINode>(SI->getCondition())->getParent() == BB)
84       SimplifyPredecessors(SI);
85   }
86
87   // If possible, simplify the terminator of this block.
88   if (ConstantFoldTerminator(BB))
89     MadeChange = true;
90
91   // If this block ends with an unconditional branch and the only successor has
92   // only this block as a predecessor, merge the two blocks together.
93   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
94     if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
95         BB != BI->getSuccessor(0)) {
96       BasicBlock *Succ = BI->getSuccessor(0);
97       
98       // If Succ has any PHI nodes, they are all single-entry PHI's.
99       while (PHINode *PN = dyn_cast<PHINode>(Succ->begin())) {
100         assert(PN->getNumIncomingValues() == 1 &&
101                "PHI doesn't match parent block");
102         PN->replaceAllUsesWith(PN->getIncomingValue(0));
103         PN->eraseFromParent();
104       }
105       
106       // Remove BI.
107       BI->eraseFromParent();
108
109       // Move over all of the instructions.
110       BB->getInstList().splice(BB->end(), Succ->getInstList());
111
112       // Any phi nodes that had entries for Succ now have entries from BB.
113       Succ->replaceAllUsesWith(BB);
114
115       // Succ is now dead, but we cannot delete it without potentially
116       // invalidating iterators elsewhere.  Just insert an unreachable
117       // instruction in it.
118       new UnreachableInst(Succ);
119       MadeChange = true;
120     }
121 }
122
123 // SimplifyPredecessors(branches) - We know that BI is a conditional branch
124 // based on a PHI node defined in this block.  If the phi node contains constant
125 // operands, then the blocks corresponding to those operands can be modified to
126 // jump directly to the destination instead of going through this block.
127 void CondProp::SimplifyPredecessors(BranchInst *BI) {
128   // TODO: We currently only handle the most trival case, where the PHI node has
129   // one use (the branch), and is the only instruction besides the branch in the
130   // block.
131   PHINode *PN = cast<PHINode>(BI->getCondition());
132   if (!PN->hasOneUse()) return;
133
134   BasicBlock *BB = BI->getParent();
135   if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
136     return;
137
138   // Ok, we have this really simple case, walk the PHI operands, looking for
139   // constants.  Walk from the end to remove operands from the end when
140   // possible, and to avoid invalidating "i".
141   for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
142     if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
143       // If we have a constant, forward the edge from its current to its
144       // ultimate destination.
145       bool PHIGone = PN->getNumIncomingValues() == 2;
146       RevectorBlockTo(PN->getIncomingBlock(i-1),
147                       BI->getSuccessor(CB->isZero()));
148       ++NumBrThread;
149
150       // If there were two predecessors before this simplification, the PHI node
151       // will be deleted.  Don't iterate through it the last time.
152       if (PHIGone) return;
153     }
154 }
155
156 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
157 // defined in this block.  If the phi node contains constant operands, then the
158 // blocks corresponding to those operands can be modified to jump directly to
159 // the destination instead of going through this block.
160 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
161   // TODO: We currently only handle the most trival case, where the PHI node has
162   // one use (the branch), and is the only instruction besides the branch in the
163   // block.
164   PHINode *PN = cast<PHINode>(SI->getCondition());
165   if (!PN->hasOneUse()) return;
166
167   BasicBlock *BB = SI->getParent();
168   if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
169     return;
170
171   bool RemovedPreds = false;
172
173   // Ok, we have this really simple case, walk the PHI operands, looking for
174   // constants.  Walk from the end to remove operands from the end when
175   // possible, and to avoid invalidating "i".
176   for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
177     if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
178       // If we have a constant, forward the edge from its current to its
179       // ultimate destination.
180       bool PHIGone = PN->getNumIncomingValues() == 2;
181       unsigned DestCase = SI->findCaseValue(CI);
182       RevectorBlockTo(PN->getIncomingBlock(i-1),
183                       SI->getSuccessor(DestCase));
184       ++NumSwThread;
185       RemovedPreds = true;
186
187       // If there were two predecessors before this simplification, the PHI node
188       // will be deleted.  Don't iterate through it the last time.
189       if (PHIGone) return;
190     }
191 }
192
193
194 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
195 // the ToBB block, which is one of the successors of its current successor.
196 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
197   BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
198   assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
199
200   // Get the old block we are threading through.
201   BasicBlock *OldSucc = FromBr->getSuccessor(0);
202
203   // OldSucc had multiple successors. If ToBB has multiple predecessors, then 
204   // the edge between them would be critical, which we already took care of.
205   // If ToBB has single operand PHI node then take care of it here.
206   while (PHINode *PN = dyn_cast<PHINode>(ToBB->begin())) {
207     assert(PN->getNumIncomingValues() == 1 && "Critical Edge Found!");    
208     PN->replaceAllUsesWith(PN->getIncomingValue(0));
209     PN->eraseFromParent();
210   }
211
212   // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
213   OldSucc->removePredecessor(FromBB);
214
215   // Change FromBr to branch to the new destination.
216   FromBr->setSuccessor(0, ToBB);
217
218   MadeChange = true;
219 }