1 //===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass propagates information about conditional expressions through the
11 // program, allowing it to eliminate conditional branches in some cases.
13 //===----------------------------------------------------------------------===//
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"
30 NumBrThread("condprop", "Number of CFG edges threaded through branches");
32 NumSwThread("condprop", "Number of CFG edges threaded through switches");
34 struct CondProp : public FunctionPass {
35 virtual bool runOnFunction(Function &F);
37 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38 AU.addRequiredID(BreakCriticalEdgesID);
39 //AU.addRequired<DominanceFrontier>();
44 void SimplifyBlock(BasicBlock *BB);
45 void SimplifyPredecessors(BranchInst *BI);
46 void SimplifyPredecessors(SwitchInst *SI);
47 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
49 RegisterPass<CondProp> X("condprop", "Conditional Propagation");
52 FunctionPass *llvm::createCondPropagationPass() {
53 return new CondProp();
56 bool CondProp::runOnFunction(Function &F) {
57 bool EverMadeChange = false;
59 // While we are simplifying blocks, keep iterating.
62 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
64 EverMadeChange = MadeChange;
66 return EverMadeChange;
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);
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);
83 // If possible, simplify the terminator of this block.
84 if (ConstantFoldTerminator(BB))
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 BB != BI->getSuccessor(0)) {
92 BasicBlock *Succ = BI->getSuccessor(0);
94 // If Succ has any PHI nodes, they are all single-entry PHI's.
95 while (PHINode *PN = dyn_cast<PHINode>(Succ->begin())) {
96 assert(PN->getNumIncomingValues() == 1 &&
97 "PHI doesn't match parent block");
98 PN->replaceAllUsesWith(PN->getIncomingValue(0));
99 PN->eraseFromParent();
103 BI->eraseFromParent();
105 // Move over all of the instructions.
106 BB->getInstList().splice(BB->end(), Succ->getInstList());
108 // Any phi nodes that had entries for Succ now have entries from BB.
109 Succ->replaceAllUsesWith(BB);
111 // Succ is now dead, but we cannot delete it without potentially
112 // invalidating iterators elsewhere. Just insert an unreachable
113 // instruction in it.
114 new UnreachableInst(Succ);
119 // SimplifyPredecessors(branches) - We know that BI is a conditional branch
120 // based on a PHI node defined in this block. If the phi node contains constant
121 // operands, then the blocks corresponding to those operands can be modified to
122 // jump directly to the destination instead of going through this block.
123 void CondProp::SimplifyPredecessors(BranchInst *BI) {
124 // TODO: We currently only handle the most trival case, where the PHI node has
125 // one use (the branch), and is the only instruction besides the branch in the
127 PHINode *PN = cast<PHINode>(BI->getCondition());
128 if (!PN->hasOneUse()) return;
130 BasicBlock *BB = BI->getParent();
131 if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
134 // Ok, we have this really simple case, walk the PHI operands, looking for
135 // constants. Walk from the end to remove operands from the end when
136 // possible, and to avoid invalidating "i".
137 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
138 if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i-1))) {
139 // If we have a constant, forward the edge from its current to its
140 // ultimate destination.
141 bool PHIGone = PN->getNumIncomingValues() == 2;
142 RevectorBlockTo(PN->getIncomingBlock(i-1),
143 BI->getSuccessor(CB->getValue() == 0));
146 // If there were two predecessors before this simplification, the PHI node
147 // will be deleted. Don't iterate through it the last time.
152 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
153 // defined in this block. If the phi node contains constant operands, then the
154 // blocks corresponding to those operands can be modified to jump directly to
155 // the destination instead of going through this block.
156 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
157 // TODO: We currently only handle the most trival case, where the PHI node has
158 // one use (the branch), and is the only instruction besides the branch in the
160 PHINode *PN = cast<PHINode>(SI->getCondition());
161 if (!PN->hasOneUse()) return;
163 BasicBlock *BB = SI->getParent();
164 if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
167 bool RemovedPreds = false;
169 // Ok, we have this really simple case, walk the PHI operands, looking for
170 // constants. Walk from the end to remove operands from the end when
171 // possible, and to avoid invalidating "i".
172 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
173 if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
174 // If we have a constant, forward the edge from its current to its
175 // ultimate destination.
176 bool PHIGone = PN->getNumIncomingValues() == 2;
177 unsigned DestCase = SI->findCaseValue(CI);
178 RevectorBlockTo(PN->getIncomingBlock(i-1),
179 SI->getSuccessor(DestCase));
183 // If there were two predecessors before this simplification, the PHI node
184 // will be deleted. Don't iterate through it the last time.
190 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
191 // the ToBB block, which is one of the successors of its current successor.
192 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
193 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
194 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
196 // Get the old block we are threading through.
197 BasicBlock *OldSucc = FromBr->getSuccessor(0);
199 // ToBB should not have any PHI nodes in it to update, because OldSucc had
200 // multiple successors. If OldSucc had multiple successor and ToBB had
201 // multiple predecessors, the edge between them would be critical, which we
202 // already took care of.
203 assert(!isa<PHINode>(ToBB->begin()) && "Critical Edge Found!");
205 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
206 OldSucc->removePredecessor(FromBB);
208 // Change FromBr to branch to the new destination.
209 FromBr->setSuccessor(0, ToBB);