blob: 45bc629e20e5075b121c38c3af8c2d9ae6dd6eb1 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000017#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
Devang Patel115fca82009-02-05 23:32:52 +000020#include "llvm/IntrinsicInst.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Pass.h"
22#include "llvm/Type.h"
Chris Lattnere142fdd2008-12-03 19:44:02 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
24#include "llvm/Transforms/Utils/Local.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
Devang Patel1f205112009-02-05 19:59:42 +000027#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Support/Compiler.h"
29#include "llvm/Support/Streams.h"
30using namespace llvm;
31
32STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
33STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
34
35namespace {
36 struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
37 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000038 CondProp() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039
40 virtual bool runOnFunction(Function &F);
41
42 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43 AU.addRequiredID(BreakCriticalEdgesID);
44 //AU.addRequired<DominanceFrontier>();
45 }
46
47 private:
48 bool MadeChange;
Devang Patel1f205112009-02-05 19:59:42 +000049 SmallVector<BasicBlock *, 4> DeadBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050 void SimplifyBlock(BasicBlock *BB);
51 void SimplifyPredecessors(BranchInst *BI);
52 void SimplifyPredecessors(SwitchInst *SI);
53 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
54 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055}
Dan Gohman089efff2008-05-13 00:00:25 +000056
57char CondProp::ID = 0;
58static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60FunctionPass *llvm::createCondPropagationPass() {
61 return new CondProp();
62}
63
64bool CondProp::runOnFunction(Function &F) {
65 bool EverMadeChange = false;
Devang Patel1f205112009-02-05 19:59:42 +000066 DeadBlocks.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000067
68 // While we are simplifying blocks, keep iterating.
69 do {
70 MadeChange = false;
Devang Patel1f205112009-02-05 19:59:42 +000071 for (Function::iterator BB = F.begin(), E = F.end(); BB != E;)
72 SimplifyBlock(BB++);
Devang Patelfb18f932007-07-26 20:21:42 +000073 EverMadeChange = EverMadeChange || MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 } while (MadeChange);
Devang Patel1f205112009-02-05 19:59:42 +000075
76 if (EverMadeChange) {
77 while (!DeadBlocks.empty()) {
78 BasicBlock *BB = DeadBlocks.back(); DeadBlocks.pop_back();
79 DeleteDeadBlock(BB);
80 }
81 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 return EverMadeChange;
83}
84
85void CondProp::SimplifyBlock(BasicBlock *BB) {
86 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
87 // If this is a conditional branch based on a phi node that is defined in
88 // this block, see if we can simplify predecessors of this block.
89 if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
90 cast<PHINode>(BI->getCondition())->getParent() == BB)
91 SimplifyPredecessors(BI);
92
93 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
94 if (isa<PHINode>(SI->getCondition()) &&
95 cast<PHINode>(SI->getCondition())->getParent() == BB)
96 SimplifyPredecessors(SI);
97 }
98
99 // If possible, simplify the terminator of this block.
100 if (ConstantFoldTerminator(BB))
101 MadeChange = true;
102
103 // If this block ends with an unconditional branch and the only successor has
104 // only this block as a predecessor, merge the two blocks together.
105 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
106 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
107 BB != BI->getSuccessor(0)) {
108 BasicBlock *Succ = BI->getSuccessor(0);
109
Chris Lattnere142fdd2008-12-03 19:44:02 +0000110 // If Succ has any PHI nodes, they are all single-entry PHI's. Eliminate
111 // them.
112 FoldSingleEntryPHINodes(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113
114 // Remove BI.
115 BI->eraseFromParent();
116
117 // Move over all of the instructions.
118 BB->getInstList().splice(BB->end(), Succ->getInstList());
119
120 // Any phi nodes that had entries for Succ now have entries from BB.
121 Succ->replaceAllUsesWith(BB);
122
123 // Succ is now dead, but we cannot delete it without potentially
124 // invalidating iterators elsewhere. Just insert an unreachable
Devang Patel1f205112009-02-05 19:59:42 +0000125 // instruction in it and delete this block later on.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 new UnreachableInst(Succ);
Devang Patel1f205112009-02-05 19:59:42 +0000127 DeadBlocks.push_back(Succ);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 MadeChange = true;
129 }
130}
131
132// SimplifyPredecessors(branches) - We know that BI is a conditional branch
133// based on a PHI node defined in this block. If the phi node contains constant
134// operands, then the blocks corresponding to those operands can be modified to
135// jump directly to the destination instead of going through this block.
136void CondProp::SimplifyPredecessors(BranchInst *BI) {
137 // TODO: We currently only handle the most trival case, where the PHI node has
Devang Patel115fca82009-02-05 23:32:52 +0000138 // one use (the branch), and is the only instruction besides the branch and dbg
139 // intrinsics in the block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140 PHINode *PN = cast<PHINode>(BI->getCondition());
lattnerf76eb8f2009-01-26 02:18:20 +0000141
142 if (PN->getNumIncomingValues() == 1) {
143 // Eliminate single-entry PHI nodes.
144 FoldSingleEntryPHINodes(PN->getParent());
145 return;
146 }
147
148
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149 if (!PN->hasOneUse()) return;
150
151 BasicBlock *BB = BI->getParent();
Devang Patel115fca82009-02-05 23:32:52 +0000152 if (&*BB->begin() != PN)
153 return;
154 BasicBlock::iterator BBI = BB->begin();
155 BasicBlock::iterator BBE = BB->end();
Bill Wendling1252bbf2009-03-05 01:08:35 +0000156 while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI)) /* empty */;
Devang Patel115fca82009-02-05 23:32:52 +0000157 if (&*BBI != BI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 return;
159
160 // Ok, we have this really simple case, walk the PHI operands, looking for
161 // constants. Walk from the end to remove operands from the end when
162 // possible, and to avoid invalidating "i".
163 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
164 if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
165 // If we have a constant, forward the edge from its current to its
166 // ultimate destination.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 RevectorBlockTo(PN->getIncomingBlock(i-1),
168 BI->getSuccessor(CB->isZero()));
169 ++NumBrThread;
170
Chris Lattner5f641f72007-08-02 04:47:05 +0000171 // If there were two predecessors before this simplification, or if the
172 // PHI node contained all the same value except for the one we just
173 // substituted, the PHI node may be deleted. Don't iterate through it the
174 // last time.
175 if (BI->getCondition() != PN) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 }
177}
178
179// SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
180// defined in this block. If the phi node contains constant operands, then the
181// blocks corresponding to those operands can be modified to jump directly to
182// the destination instead of going through this block.
183void CondProp::SimplifyPredecessors(SwitchInst *SI) {
184 // TODO: We currently only handle the most trival case, where the PHI node has
Devang Patel115fca82009-02-05 23:32:52 +0000185 // one use (the branch), and is the only instruction besides the branch and
186 // dbg intrinsics in the block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 PHINode *PN = cast<PHINode>(SI->getCondition());
188 if (!PN->hasOneUse()) return;
189
190 BasicBlock *BB = SI->getParent();
Devang Patel115fca82009-02-05 23:32:52 +0000191 if (&*BB->begin() != PN)
192 return;
193 BasicBlock::iterator BBI = BB->begin();
194 BasicBlock::iterator BBE = BB->end();
Bill Wendling1252bbf2009-03-05 01:08:35 +0000195 while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI)) /* empty */;
Devang Patel115fca82009-02-05 23:32:52 +0000196 if (&*BBI != SI)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 return;
198
199 bool RemovedPreds = false;
200
201 // Ok, we have this really simple case, walk the PHI operands, looking for
202 // constants. Walk from the end to remove operands from the end when
203 // possible, and to avoid invalidating "i".
204 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
205 if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
206 // If we have a constant, forward the edge from its current to its
207 // ultimate destination.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 unsigned DestCase = SI->findCaseValue(CI);
209 RevectorBlockTo(PN->getIncomingBlock(i-1),
210 SI->getSuccessor(DestCase));
211 ++NumSwThread;
212 RemovedPreds = true;
213
Chris Lattner5f641f72007-08-02 04:47:05 +0000214 // If there were two predecessors before this simplification, or if the
215 // PHI node contained all the same value except for the one we just
216 // substituted, the PHI node may be deleted. Don't iterate through it the
217 // last time.
218 if (SI->getCondition() != PN) return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 }
220}
221
222
223// RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
224// the ToBB block, which is one of the successors of its current successor.
225void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
226 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
227 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
228
229 // Get the old block we are threading through.
230 BasicBlock *OldSucc = FromBr->getSuccessor(0);
231
232 // OldSucc had multiple successors. If ToBB has multiple predecessors, then
233 // the edge between them would be critical, which we already took care of.
234 // If ToBB has single operand PHI node then take care of it here.
Chris Lattnere142fdd2008-12-03 19:44:02 +0000235 FoldSingleEntryPHINodes(ToBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236
237 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
238 OldSucc->removePredecessor(FromBB);
239
240 // Change FromBr to branch to the new destination.
241 FromBr->setSuccessor(0, ToBB);
242
243 MadeChange = true;
244}