1 //===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Type.h"
22 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Streams.h"
30 STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
31 STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
34 struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
35 static char ID; // Pass identification, replacement for typeid
36 CondProp() : FunctionPass(&ID) {}
38 virtual bool runOnFunction(Function &F);
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequiredID(BreakCriticalEdgesID);
42 //AU.addRequired<DominanceFrontier>();
47 void SimplifyBlock(BasicBlock *BB);
48 void SimplifyPredecessors(BranchInst *BI);
49 void SimplifyPredecessors(SwitchInst *SI);
50 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
54 char CondProp::ID = 0;
55 static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
57 FunctionPass *llvm::createCondPropagationPass() {
58 return new CondProp();
61 bool CondProp::runOnFunction(Function &F) {
62 bool EverMadeChange = false;
64 // While we are simplifying blocks, keep iterating.
67 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
69 EverMadeChange = EverMadeChange || MadeChange;
71 return EverMadeChange;
74 void CondProp::SimplifyBlock(BasicBlock *BB) {
75 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
76 // If this is a conditional branch based on a phi node that is defined in
77 // this block, see if we can simplify predecessors of this block.
78 if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
79 cast<PHINode>(BI->getCondition())->getParent() == BB)
80 SimplifyPredecessors(BI);
82 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
83 if (isa<PHINode>(SI->getCondition()) &&
84 cast<PHINode>(SI->getCondition())->getParent() == BB)
85 SimplifyPredecessors(SI);
88 // If possible, simplify the terminator of this block.
89 if (ConstantFoldTerminator(BB))
92 // If this block ends with an unconditional branch and the only successor has
93 // only this block as a predecessor, merge the two blocks together.
94 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
95 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
96 BB != BI->getSuccessor(0)) {
97 BasicBlock *Succ = BI->getSuccessor(0);
99 // If Succ has any PHI nodes, they are all single-entry PHI's. Eliminate
101 FoldSingleEntryPHINodes(Succ);
104 BI->eraseFromParent();
106 // Move over all of the instructions.
107 BB->getInstList().splice(BB->end(), Succ->getInstList());
109 // Any phi nodes that had entries for Succ now have entries from BB.
110 Succ->replaceAllUsesWith(BB);
112 // Succ is now dead, but we cannot delete it without potentially
113 // invalidating iterators elsewhere. Just insert an unreachable
114 // instruction in it.
115 new UnreachableInst(Succ);
120 // SimplifyPredecessors(branches) - We know that BI is a conditional branch
121 // based on a PHI node defined in this block. If the phi node contains constant
122 // operands, then the blocks corresponding to those operands can be modified to
123 // jump directly to the destination instead of going through this block.
124 void CondProp::SimplifyPredecessors(BranchInst *BI) {
125 // TODO: We currently only handle the most trival case, where the PHI node has
126 // one use (the branch), and is the only instruction besides the branch in the
128 PHINode *PN = cast<PHINode>(BI->getCondition());
129 if (!PN->hasOneUse()) return;
131 BasicBlock *BB = BI->getParent();
132 if (&*BB->begin() != PN || &*next(BB->begin()) != BI)
135 // Ok, we have this really simple case, walk the PHI operands, looking for
136 // constants. Walk from the end to remove operands from the end when
137 // possible, and to avoid invalidating "i".
138 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
139 if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
140 // If we have a constant, forward the edge from its current to its
141 // ultimate destination.
142 RevectorBlockTo(PN->getIncomingBlock(i-1),
143 BI->getSuccessor(CB->isZero()));
146 // If there were two predecessors before this simplification, or if the
147 // PHI node contained all the same value except for the one we just
148 // substituted, the PHI node may be deleted. Don't iterate through it the
150 if (BI->getCondition() != PN) return;
154 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
155 // defined in this block. If the phi node contains constant operands, then the
156 // blocks corresponding to those operands can be modified to jump directly to
157 // the destination instead of going through this block.
158 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
159 // TODO: We currently only handle the most trival case, where the PHI node has
160 // one use (the branch), and is the only instruction besides the branch in the
162 PHINode *PN = cast<PHINode>(SI->getCondition());
163 if (!PN->hasOneUse()) return;
165 BasicBlock *BB = SI->getParent();
166 if (&*BB->begin() != PN || &*next(BB->begin()) != SI)
169 bool RemovedPreds = false;
171 // Ok, we have this really simple case, walk the PHI operands, looking for
172 // constants. Walk from the end to remove operands from the end when
173 // possible, and to avoid invalidating "i".
174 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
175 if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
176 // If we have a constant, forward the edge from its current to its
177 // ultimate destination.
178 unsigned DestCase = SI->findCaseValue(CI);
179 RevectorBlockTo(PN->getIncomingBlock(i-1),
180 SI->getSuccessor(DestCase));
184 // If there were two predecessors before this simplification, or if the
185 // PHI node contained all the same value except for the one we just
186 // substituted, the PHI node may be deleted. Don't iterate through it the
188 if (SI->getCondition() != PN) return;
193 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
194 // the ToBB block, which is one of the successors of its current successor.
195 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
196 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
197 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
199 // Get the old block we are threading through.
200 BasicBlock *OldSucc = FromBr->getSuccessor(0);
202 // OldSucc had multiple successors. If ToBB has multiple predecessors, then
203 // the edge between them would be critical, which we already took care of.
204 // If ToBB has single operand PHI node then take care of it here.
205 FoldSingleEntryPHINodes(ToBB);
207 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
208 OldSucc->removePredecessor(FromBB);
210 // Change FromBr to branch to the new destination.
211 FromBr->setSuccessor(0, ToBB);