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/ADT/SmallVector.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Streams.h"
31 STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
32 STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
35 struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
36 static char ID; // Pass identification, replacement for typeid
37 CondProp() : FunctionPass(&ID) {}
39 virtual bool runOnFunction(Function &F);
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequiredID(BreakCriticalEdgesID);
43 //AU.addRequired<DominanceFrontier>();
48 SmallVector<BasicBlock *, 4> DeadBlocks;
49 void SimplifyBlock(BasicBlock *BB);
50 void SimplifyPredecessors(BranchInst *BI);
51 void SimplifyPredecessors(SwitchInst *SI);
52 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
56 char CondProp::ID = 0;
57 static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
59 FunctionPass *llvm::createCondPropagationPass() {
60 return new CondProp();
63 bool CondProp::runOnFunction(Function &F) {
64 bool EverMadeChange = false;
67 // While we are simplifying blocks, keep iterating.
70 for (Function::iterator BB = F.begin(), E = F.end(); BB != E;)
72 EverMadeChange = EverMadeChange || MadeChange;
76 while (!DeadBlocks.empty()) {
77 BasicBlock *BB = DeadBlocks.back(); DeadBlocks.pop_back();
81 return EverMadeChange;
84 void CondProp::SimplifyBlock(BasicBlock *BB) {
85 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
86 // If this is a conditional branch based on a phi node that is defined in
87 // this block, see if we can simplify predecessors of this block.
88 if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
89 cast<PHINode>(BI->getCondition())->getParent() == BB)
90 SimplifyPredecessors(BI);
92 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
93 if (isa<PHINode>(SI->getCondition()) &&
94 cast<PHINode>(SI->getCondition())->getParent() == BB)
95 SimplifyPredecessors(SI);
98 // If possible, simplify the terminator of this block.
99 if (ConstantFoldTerminator(BB))
102 // If this block ends with an unconditional branch and the only successor has
103 // only this block as a predecessor, merge the two blocks together.
104 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
105 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
106 BB != BI->getSuccessor(0)) {
107 BasicBlock *Succ = BI->getSuccessor(0);
109 // If Succ has any PHI nodes, they are all single-entry PHI's. Eliminate
111 FoldSingleEntryPHINodes(Succ);
114 BI->eraseFromParent();
116 // Move over all of the instructions.
117 BB->getInstList().splice(BB->end(), Succ->getInstList());
119 // Any phi nodes that had entries for Succ now have entries from BB.
120 Succ->replaceAllUsesWith(BB);
122 // Succ is now dead, but we cannot delete it without potentially
123 // invalidating iterators elsewhere. Just insert an unreachable
124 // instruction in it and delete this block later on.
125 new UnreachableInst(Succ);
126 DeadBlocks.push_back(Succ);
131 // SimplifyPredecessors(branches) - We know that BI is a conditional branch
132 // based on a PHI node defined in this block. If the phi node contains constant
133 // operands, then the blocks corresponding to those operands can be modified to
134 // jump directly to the destination instead of going through this block.
135 void CondProp::SimplifyPredecessors(BranchInst *BI) {
136 // TODO: We currently only handle the most trival case, where the PHI node has
137 // one use (the branch), and is the only instruction besides the branch in the
139 PHINode *PN = cast<PHINode>(BI->getCondition());
141 if (PN->getNumIncomingValues() == 1) {
142 // Eliminate single-entry PHI nodes.
143 FoldSingleEntryPHINodes(PN->getParent());
148 if (!PN->hasOneUse()) return;
150 BasicBlock *BB = BI->getParent();
151 if (!isTerminatorFirstRelevantInsn (BB, BI))
154 // Ok, we have this really simple case, walk the PHI operands, looking for
155 // constants. Walk from the end to remove operands from the end when
156 // possible, and to avoid invalidating "i".
157 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
158 if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
159 // If we have a constant, forward the edge from its current to its
160 // ultimate destination.
161 RevectorBlockTo(PN->getIncomingBlock(i-1),
162 BI->getSuccessor(CB->isZero()));
165 // If there were two predecessors before this simplification, or if the
166 // PHI node contained all the same value except for the one we just
167 // substituted, the PHI node may be deleted. Don't iterate through it the
169 if (BI->getCondition() != PN) return;
173 // SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
174 // defined in this block. If the phi node contains constant operands, then the
175 // blocks corresponding to those operands can be modified to jump directly to
176 // the destination instead of going through this block.
177 void CondProp::SimplifyPredecessors(SwitchInst *SI) {
178 // TODO: We currently only handle the most trival case, where the PHI node has
179 // one use (the branch), and is the only instruction besides the branch in the
181 PHINode *PN = cast<PHINode>(SI->getCondition());
182 if (!PN->hasOneUse()) return;
184 BasicBlock *BB = SI->getParent();
185 if (!isTerminatorFirstRelevantInsn (BB, SI))
188 bool RemovedPreds = false;
190 // Ok, we have this really simple case, walk the PHI operands, looking for
191 // constants. Walk from the end to remove operands from the end when
192 // possible, and to avoid invalidating "i".
193 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
194 if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
195 // If we have a constant, forward the edge from its current to its
196 // ultimate destination.
197 unsigned DestCase = SI->findCaseValue(CI);
198 RevectorBlockTo(PN->getIncomingBlock(i-1),
199 SI->getSuccessor(DestCase));
203 // If there were two predecessors before this simplification, or if the
204 // PHI node contained all the same value except for the one we just
205 // substituted, the PHI node may be deleted. Don't iterate through it the
207 if (SI->getCondition() != PN) return;
212 // RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
213 // the ToBB block, which is one of the successors of its current successor.
214 void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
215 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
216 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
218 // Get the old block we are threading through.
219 BasicBlock *OldSucc = FromBr->getSuccessor(0);
221 // OldSucc had multiple successors. If ToBB has multiple predecessors, then
222 // the edge between them would be critical, which we already took care of.
223 // If ToBB has single operand PHI node then take care of it here.
224 FoldSingleEntryPHINodes(ToBB);
226 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
227 OldSucc->removePredecessor(FromBB);
229 // Change FromBr to branch to the new destination.
230 FromBr->setSuccessor(0, ToBB);