Fix a fixme in CondPropagate.cpp by moving a PhiNode optimization into
[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 <iostream>
26 using namespace llvm;
27
28 namespace {
29   Statistic<>
30   NumBrThread("condprop", "Number of CFG edges threaded through branches");
31   Statistic<>
32   NumSwThread("condprop", "Number of CFG edges threaded through switches");
33
34   struct CondProp : public FunctionPass {
35     virtual bool runOnFunction(Function &F);
36
37     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38       AU.addRequiredID(BreakCriticalEdgesID);
39       //AU.addRequired<DominanceFrontier>();
40     }
41
42   private:
43     bool MadeChange;
44     void SimplifyBlock(BasicBlock *BB);
45     void SimplifyPredecessors(BranchInst *BI);
46     void SimplifyPredecessors(SwitchInst *SI);
47     void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
48   };
49   RegisterOpt<CondProp> X("condprop", "Conditional Propagation");
50 }
51
52 FunctionPass *llvm::createCondPropagationPass() {
53   return new CondProp();
54 }
55
56 bool CondProp::runOnFunction(Function &F) {
57   bool EverMadeChange = false;
58
59   // While we are simplifying blocks, keep iterating.
60   do {
61     MadeChange = false;
62     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
63       SimplifyBlock(BB);
64     EverMadeChange = MadeChange;
65   } while (MadeChange);
66   return EverMadeChange;
67 }
68
69 void CondProp::SimplifyBlock(BasicBlock *BB) {
70   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
71     // If this is a conditional branch based on a phi node that is defined in
72     // this block, see if we can simplify predecessors of this block.
73     if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
74         cast<PHINode>(BI->getCondition())->getParent() == BB)
75       SimplifyPredecessors(BI);
76
77   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
78     if (isa<PHINode>(SI->getCondition()) &&
79         cast<PHINode>(SI->getCondition())->getParent() == BB)
80       SimplifyPredecessors(SI);
81   }
82
83   // If possible, simplify the terminator of this block.
84   if (ConstantFoldTerminator(BB))
85     MadeChange = true;
86
87   // If this block ends with an unconditional branch and the only successor has
88   // only this block as a predecessor, merge the two blocks together.
89   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
90     if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor()) {
91       BasicBlock *Succ = BI->getSuccessor(0);
92       // Remove BI.
93       BI->eraseFromParent();
94
95       // Move over all of the instructions.
96       BB->getInstList().splice(BB->end(), Succ->getInstList());
97
98       // Any phi nodes that had entries for Succ now have entries from BB.
99       Succ->replaceAllUsesWith(BB);
100
101       // Succ is now dead, but we cannot delete it without potentially
102       // invalidating iterators elsewhere.  Just insert an unreachable
103       // instruction in it.
104       new UnreachableInst(Succ);
105       MadeChange = true;
106     }
107 }
108
109 // SimplifyPredecessors(branches) - We know that BI is a conditional branch
110 // based on a PHI node defined in this block.  If the phi node contains constant
111 // operands, then the blocks corresponding to those operands can be modified to
112 // jump directly to the destination instead of going through this block.
113 void CondProp::SimplifyPredecessors(BranchInst *BI) {
114   // TODO: We currently only handle the most trival case, where the PHI node has
115   // one use (the branch), and is the only instruction besides the branch in the
116   // block.
117   PHINode *PN = cast<PHINode>(BI->getCondition());
118   if (!PN->hasOneUse()) return;
119
120   BasicBlock *BB = BI->getParent();
121   if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
122     return;
123
124   // Ok, we have this really simple case, walk the PHI operands, looking for
125   // constants.  Walk from the end to remove operands from the end when
126   // possible, and to avoid invalidating "i".
127   for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
128     if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i-1))) {
129       // If we have a constant, forward the edge from its current to its
130       // ultimate destination.
131       bool PHIGone = PN->getNumIncomingValues() == 2;
132       RevectorBlockTo(PN->getIncomingBlock(i-1),
133                       BI->getSuccessor(CB->getValue() == 0));
134       ++NumBrThread;
135
136       // If there were two predecessors before this simplification, the PHI node
137       // will be deleted.  Don't iterate through it the last time.
138       if (PHIGone) return;
139     }
140 }
141
142 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
143 // defined in this block.  If the phi node contains constant operands, then the
144 // blocks corresponding to those operands can be modified to jump directly to
145 // the destination instead of going through this block.
146 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
147   // TODO: We currently only handle the most trival case, where the PHI node has
148   // one use (the branch), and is the only instruction besides the branch in the
149   // block.
150   PHINode *PN = cast<PHINode>(SI->getCondition());
151   if (!PN->hasOneUse()) return;
152
153   BasicBlock *BB = SI->getParent();
154   if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
155     return;
156
157   bool RemovedPreds = false;
158
159   // Ok, we have this really simple case, walk the PHI operands, looking for
160   // constants.  Walk from the end to remove operands from the end when
161   // possible, and to avoid invalidating "i".
162   for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
163     if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
164       // If we have a constant, forward the edge from its current to its
165       // ultimate destination.
166       bool PHIGone = PN->getNumIncomingValues() == 2;
167       unsigned DestCase = SI->findCaseValue(CI);
168       RevectorBlockTo(PN->getIncomingBlock(i-1),
169                       SI->getSuccessor(DestCase));
170       ++NumSwThread;
171       RemovedPreds = true;
172
173       // If there were two predecessors before this simplification, the PHI node
174       // will be deleted.  Don't iterate through it the last time.
175       if (PHIGone) return;
176     }
177 }
178
179
180 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
181 // the ToBB block, which is one of the successors of its current successor.
182 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
183   BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
184   assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
185
186   // Get the old block we are threading through.
187   BasicBlock *OldSucc = FromBr->getSuccessor(0);
188
189   // ToBB should not have any PHI nodes in it to update, because OldSucc had
190   // multiple successors.  If OldSucc had multiple successor and ToBB had
191   // multiple predecessors, the edge between them would be critical, which we
192   // already took care of.
193   assert(!isa<PHINode>(ToBB->begin()) && "Critical Edge Found!");
194
195   // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
196   OldSucc->removePredecessor(FromBB);
197
198   // Change FromBr to branch to the new destination.
199   FromBr->setSuccessor(0, ToBB);
200
201   MadeChange = true;
202 }