blob: 8df2b6c82f6fcbfe114c48a002b89c26444f0111 [file] [log] [blame]
Chris Lattner36d12732005-04-15 19:28:32 +00001//===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattner36d12732005-04-15 19:28:32 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattner36d12732005-04-15 19:28:32 +00008//===----------------------------------------------------------------------===//
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"
Chris Lattner36d12732005-04-15 19:28:32 +000017#include "llvm/Constants.h"
18#include "llvm/Function.h"
19#include "llvm/Instructions.h"
Devang Patel32d97012009-02-05 23:32:52 +000020#include "llvm/IntrinsicInst.h"
Chris Lattner36d12732005-04-15 19:28:32 +000021#include "llvm/Pass.h"
22#include "llvm/Type.h"
Chris Lattner29874e02008-12-03 19:44:02 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
24#include "llvm/Transforms/Utils/Local.h"
Chris Lattner36d12732005-04-15 19:28:32 +000025#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Statistic.h"
Devang Patel39c873e2009-02-05 19:59:42 +000027#include "llvm/ADT/SmallVector.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000028#include "llvm/Support/Compiler.h"
Bill Wendlingb7427032006-11-26 09:46:52 +000029#include "llvm/Support/Streams.h"
Chris Lattner36d12732005-04-15 19:28:32 +000030using namespace llvm;
31
Chris Lattner0e5f4992006-12-19 21:40:18 +000032STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
33STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
Chris Lattner36d12732005-04-15 19:28:32 +000034
Chris Lattner0e5f4992006-12-19 21:40:18 +000035namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000036 struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000037 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000038 CondProp() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000039
Chris Lattner36d12732005-04-15 19:28:32 +000040 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 Patel39c873e2009-02-05 19:59:42 +000049 SmallVector<BasicBlock *, 4> DeadBlocks;
Chris Lattner36d12732005-04-15 19:28:32 +000050 void SimplifyBlock(BasicBlock *BB);
51 void SimplifyPredecessors(BranchInst *BI);
52 void SimplifyPredecessors(SwitchInst *SI);
53 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
Evan Chengdf2f1182009-04-14 23:40:03 +000054 bool RevectorBlockTo(BasicBlock *FromBB, Value *Cond, BranchInst *BI);
Chris Lattner36d12732005-04-15 19:28:32 +000055 };
Chris Lattner36d12732005-04-15 19:28:32 +000056}
Dan Gohman844731a2008-05-13 00:00:25 +000057
58char CondProp::ID = 0;
59static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
Chris Lattner36d12732005-04-15 19:28:32 +000060
61FunctionPass *llvm::createCondPropagationPass() {
62 return new CondProp();
63}
64
65bool CondProp::runOnFunction(Function &F) {
66 bool EverMadeChange = false;
Devang Patel39c873e2009-02-05 19:59:42 +000067 DeadBlocks.clear();
Chris Lattner36d12732005-04-15 19:28:32 +000068
69 // While we are simplifying blocks, keep iterating.
70 do {
71 MadeChange = false;
Devang Patel39c873e2009-02-05 19:59:42 +000072 for (Function::iterator BB = F.begin(), E = F.end(); BB != E;)
73 SimplifyBlock(BB++);
Devang Patel70b36d92007-07-26 20:21:42 +000074 EverMadeChange = EverMadeChange || MadeChange;
Chris Lattner36d12732005-04-15 19:28:32 +000075 } while (MadeChange);
Devang Patel39c873e2009-02-05 19:59:42 +000076
77 if (EverMadeChange) {
78 while (!DeadBlocks.empty()) {
79 BasicBlock *BB = DeadBlocks.back(); DeadBlocks.pop_back();
80 DeleteDeadBlock(BB);
81 }
82 }
Chris Lattner36d12732005-04-15 19:28:32 +000083 return EverMadeChange;
84}
85
86void CondProp::SimplifyBlock(BasicBlock *BB) {
87 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
88 // If this is a conditional branch based on a phi node that is defined in
89 // this block, see if we can simplify predecessors of this block.
90 if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
91 cast<PHINode>(BI->getCondition())->getParent() == BB)
92 SimplifyPredecessors(BI);
Misha Brukmanfd939082005-04-21 23:48:37 +000093
Chris Lattner36d12732005-04-15 19:28:32 +000094 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
95 if (isa<PHINode>(SI->getCondition()) &&
96 cast<PHINode>(SI->getCondition())->getParent() == BB)
97 SimplifyPredecessors(SI);
98 }
99
Chris Lattner36d12732005-04-15 19:28:32 +0000100 // If possible, simplify the terminator of this block.
101 if (ConstantFoldTerminator(BB))
102 MadeChange = true;
103
104 // If this block ends with an unconditional branch and the only successor has
105 // only this block as a predecessor, merge the two blocks together.
106 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000107 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
108 BB != BI->getSuccessor(0)) {
Chris Lattner36d12732005-04-15 19:28:32 +0000109 BasicBlock *Succ = BI->getSuccessor(0);
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000110
Chris Lattner29874e02008-12-03 19:44:02 +0000111 // If Succ has any PHI nodes, they are all single-entry PHI's. Eliminate
112 // them.
113 FoldSingleEntryPHINodes(Succ);
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000114
Chris Lattner36d12732005-04-15 19:28:32 +0000115 // Remove BI.
116 BI->eraseFromParent();
117
118 // Move over all of the instructions.
119 BB->getInstList().splice(BB->end(), Succ->getInstList());
120
121 // Any phi nodes that had entries for Succ now have entries from BB.
122 Succ->replaceAllUsesWith(BB);
123
124 // Succ is now dead, but we cannot delete it without potentially
125 // invalidating iterators elsewhere. Just insert an unreachable
Devang Patel39c873e2009-02-05 19:59:42 +0000126 // instruction in it and delete this block later on.
Chris Lattner36d12732005-04-15 19:28:32 +0000127 new UnreachableInst(Succ);
Devang Patel39c873e2009-02-05 19:59:42 +0000128 DeadBlocks.push_back(Succ);
Chris Lattner36d12732005-04-15 19:28:32 +0000129 MadeChange = true;
130 }
131}
132
133// SimplifyPredecessors(branches) - We know that BI is a conditional branch
134// based on a PHI node defined in this block. If the phi node contains constant
135// operands, then the blocks corresponding to those operands can be modified to
136// jump directly to the destination instead of going through this block.
137void CondProp::SimplifyPredecessors(BranchInst *BI) {
138 // TODO: We currently only handle the most trival case, where the PHI node has
Devang Patel32d97012009-02-05 23:32:52 +0000139 // one use (the branch), and is the only instruction besides the branch and dbg
140 // intrinsics in the block.
Chris Lattner36d12732005-04-15 19:28:32 +0000141 PHINode *PN = cast<PHINode>(BI->getCondition());
Chris Lattner18f02312009-01-26 02:18:20 +0000142
143 if (PN->getNumIncomingValues() == 1) {
144 // Eliminate single-entry PHI nodes.
145 FoldSingleEntryPHINodes(PN->getParent());
146 return;
147 }
148
149
Chris Lattner36d12732005-04-15 19:28:32 +0000150 if (!PN->hasOneUse()) return;
151
152 BasicBlock *BB = BI->getParent();
Devang Patel32d97012009-02-05 23:32:52 +0000153 if (&*BB->begin() != PN)
154 return;
155 BasicBlock::iterator BBI = BB->begin();
156 BasicBlock::iterator BBE = BB->end();
Bill Wendlinge5621492009-03-05 01:08:35 +0000157 while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI)) /* empty */;
Devang Patel32d97012009-02-05 23:32:52 +0000158 if (&*BBI != BI)
Chris Lattner36d12732005-04-15 19:28:32 +0000159 return;
160
161 // Ok, we have this really simple case, walk the PHI operands, looking for
162 // constants. Walk from the end to remove operands from the end when
163 // possible, and to avoid invalidating "i".
Evan Chengdf2f1182009-04-14 23:40:03 +0000164 for (unsigned i = PN->getNumIncomingValues(); i != 0; --i) {
165 Value *InVal = PN->getIncomingValue(i-1);
166 if (!RevectorBlockTo(PN->getIncomingBlock(i-1), InVal, BI))
167 continue;
Chris Lattner36d12732005-04-15 19:28:32 +0000168
Evan Chengdf2f1182009-04-14 23:40:03 +0000169 ++NumBrThread;
170
171 // 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;
176 }
Chris Lattner36d12732005-04-15 19:28:32 +0000177}
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 Patel32d97012009-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.
Chris Lattner36d12732005-04-15 19:28:32 +0000187 PHINode *PN = cast<PHINode>(SI->getCondition());
188 if (!PN->hasOneUse()) return;
189
190 BasicBlock *BB = SI->getParent();
Devang Patel32d97012009-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 Wendlinge5621492009-03-05 01:08:35 +0000195 while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI)) /* empty */;
Devang Patel32d97012009-02-05 23:32:52 +0000196 if (&*BBI != SI)
Chris Lattner36d12732005-04-15 19:28:32 +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.
Chris Lattner36d12732005-04-15 19:28:32 +0000208 unsigned DestCase = SI->findCaseValue(CI);
209 RevectorBlockTo(PN->getIncomingBlock(i-1),
210 SI->getSuccessor(DestCase));
211 ++NumSwThread;
212 RemovedPreds = true;
213
Chris Lattner9dd7a512007-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;
Chris Lattner36d12732005-04-15 19:28:32 +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
Devang Patele0805a22006-11-01 23:04:45 +0000232 // 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 Lattner29874e02008-12-03 19:44:02 +0000235 FoldSingleEntryPHINodes(ToBB);
Chris Lattner36d12732005-04-15 19:28:32 +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}
Evan Chengdf2f1182009-04-14 23:40:03 +0000245
246bool CondProp::RevectorBlockTo(BasicBlock *FromBB, Value *Cond, BranchInst *BI){
247 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
248 if (!FromBr->isUnconditional())
249 return false;
250
251 // Get the old block we are threading through.
252 BasicBlock *OldSucc = FromBr->getSuccessor(0);
253
254 // If the condition is a constant, simply revector the unconditional branch at
255 // the end of FromBB to one of the successors of its current successor.
256 if (ConstantInt *CB = dyn_cast<ConstantInt>(Cond)) {
257 BasicBlock *ToBB = BI->getSuccessor(CB->isZero());
258
259 // OldSucc had multiple successors. If ToBB has multiple predecessors, then
260 // the edge between them would be critical, which we already took care of.
261 // If ToBB has single operand PHI node then take care of it here.
262 FoldSingleEntryPHINodes(ToBB);
263
264 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
265 OldSucc->removePredecessor(FromBB);
266
267 // Change FromBr to branch to the new destination.
268 FromBr->setSuccessor(0, ToBB);
269 } else {
270 // Insert the new conditional branch.
271 BranchInst::Create(BI->getSuccessor(0), BI->getSuccessor(1), Cond, FromBr);
272
273 FoldSingleEntryPHINodes(BI->getSuccessor(0));
274 FoldSingleEntryPHINodes(BI->getSuccessor(1));
275
276 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
277 OldSucc->removePredecessor(FromBB);
278
279 // Delete the old branch.
280 FromBr->eraseFromParent();
281 }
282
283 MadeChange = true;
284 return true;
285}