blob: 000ef60a0db863dedcb4391cb79f0f2725084b60 [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"
20#include "llvm/Pass.h"
21#include "llvm/Type.h"
Chris Lattner29874e02008-12-03 19:44:02 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Local.h"
Chris Lattner36d12732005-04-15 19:28:32 +000024#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
Devang Patel39c873e2009-02-05 19:59:42 +000026#include "llvm/ADT/SmallVector.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000027#include "llvm/Support/Compiler.h"
Bill Wendlingb7427032006-11-26 09:46:52 +000028#include "llvm/Support/Streams.h"
Chris Lattner36d12732005-04-15 19:28:32 +000029using namespace llvm;
30
Chris Lattner0e5f4992006-12-19 21:40:18 +000031STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
32STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");
Chris Lattner36d12732005-04-15 19:28:32 +000033
Chris Lattner0e5f4992006-12-19 21:40:18 +000034namespace {
Reid Spencer9133fe22007-02-05 23:32:05 +000035 struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000036 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000037 CondProp() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000038
Chris Lattner36d12732005-04-15 19:28:32 +000039 virtual bool runOnFunction(Function &F);
40
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequiredID(BreakCriticalEdgesID);
43 //AU.addRequired<DominanceFrontier>();
44 }
45
46 private:
47 bool MadeChange;
Devang Patel39c873e2009-02-05 19:59:42 +000048 SmallVector<BasicBlock *, 4> DeadBlocks;
Chris Lattner36d12732005-04-15 19:28:32 +000049 void SimplifyBlock(BasicBlock *BB);
50 void SimplifyPredecessors(BranchInst *BI);
51 void SimplifyPredecessors(SwitchInst *SI);
52 void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
53 };
Chris Lattner36d12732005-04-15 19:28:32 +000054}
Dan Gohman844731a2008-05-13 00:00:25 +000055
56char CondProp::ID = 0;
57static RegisterPass<CondProp> X("condprop", "Conditional Propagation");
Chris Lattner36d12732005-04-15 19:28:32 +000058
59FunctionPass *llvm::createCondPropagationPass() {
60 return new CondProp();
61}
62
63bool CondProp::runOnFunction(Function &F) {
64 bool EverMadeChange = false;
Devang Patel39c873e2009-02-05 19:59:42 +000065 DeadBlocks.clear();
Chris Lattner36d12732005-04-15 19:28:32 +000066
67 // While we are simplifying blocks, keep iterating.
68 do {
69 MadeChange = false;
Devang Patel39c873e2009-02-05 19:59:42 +000070 for (Function::iterator BB = F.begin(), E = F.end(); BB != E;)
71 SimplifyBlock(BB++);
Devang Patel70b36d92007-07-26 20:21:42 +000072 EverMadeChange = EverMadeChange || MadeChange;
Chris Lattner36d12732005-04-15 19:28:32 +000073 } while (MadeChange);
Devang Patel39c873e2009-02-05 19:59:42 +000074
75 if (EverMadeChange) {
76 while (!DeadBlocks.empty()) {
77 BasicBlock *BB = DeadBlocks.back(); DeadBlocks.pop_back();
78 DeleteDeadBlock(BB);
79 }
80 }
Chris Lattner36d12732005-04-15 19:28:32 +000081 return EverMadeChange;
82}
83
84void 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);
Misha Brukmanfd939082005-04-21 23:48:37 +000091
Chris Lattner36d12732005-04-15 19:28:32 +000092 } 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);
96 }
97
Chris Lattner36d12732005-04-15 19:28:32 +000098 // If possible, simplify the terminator of this block.
99 if (ConstantFoldTerminator(BB))
100 MadeChange = true;
101
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()))
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000105 if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
106 BB != BI->getSuccessor(0)) {
Chris Lattner36d12732005-04-15 19:28:32 +0000107 BasicBlock *Succ = BI->getSuccessor(0);
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000108
Chris Lattner29874e02008-12-03 19:44:02 +0000109 // If Succ has any PHI nodes, they are all single-entry PHI's. Eliminate
110 // them.
111 FoldSingleEntryPHINodes(Succ);
Chris Lattnerdf32aac2006-08-14 21:38:05 +0000112
Chris Lattner36d12732005-04-15 19:28:32 +0000113 // Remove BI.
114 BI->eraseFromParent();
115
116 // Move over all of the instructions.
117 BB->getInstList().splice(BB->end(), Succ->getInstList());
118
119 // Any phi nodes that had entries for Succ now have entries from BB.
120 Succ->replaceAllUsesWith(BB);
121
122 // Succ is now dead, but we cannot delete it without potentially
123 // invalidating iterators elsewhere. Just insert an unreachable
Devang Patel39c873e2009-02-05 19:59:42 +0000124 // instruction in it and delete this block later on.
Chris Lattner36d12732005-04-15 19:28:32 +0000125 new UnreachableInst(Succ);
Devang Patel39c873e2009-02-05 19:59:42 +0000126 DeadBlocks.push_back(Succ);
Chris Lattner36d12732005-04-15 19:28:32 +0000127 MadeChange = true;
128 }
129}
130
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.
135void 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
138 // block.
139 PHINode *PN = cast<PHINode>(BI->getCondition());
Chris Lattner18f02312009-01-26 02:18:20 +0000140
141 if (PN->getNumIncomingValues() == 1) {
142 // Eliminate single-entry PHI nodes.
143 FoldSingleEntryPHINodes(PN->getParent());
144 return;
145 }
146
147
Chris Lattner36d12732005-04-15 19:28:32 +0000148 if (!PN->hasOneUse()) return;
149
150 BasicBlock *BB = BI->getParent();
Devang Patel1851db62009-02-05 19:15:39 +0000151 if (!isTerminatorFirstRelevantInsn (BB, BI))
Chris Lattner36d12732005-04-15 19:28:32 +0000152 return;
153
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)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000158 if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
Chris Lattner36d12732005-04-15 19:28:32 +0000159 // If we have a constant, forward the edge from its current to its
160 // ultimate destination.
Chris Lattner36d12732005-04-15 19:28:32 +0000161 RevectorBlockTo(PN->getIncomingBlock(i-1),
Reid Spencercae57542007-03-02 00:28:52 +0000162 BI->getSuccessor(CB->isZero()));
Chris Lattner36d12732005-04-15 19:28:32 +0000163 ++NumBrThread;
164
Chris Lattner9dd7a512007-08-02 04:47:05 +0000165 // 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
168 // last time.
169 if (BI->getCondition() != PN) return;
Chris Lattner36d12732005-04-15 19:28:32 +0000170 }
171}
172
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.
177void 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
180 // block.
181 PHINode *PN = cast<PHINode>(SI->getCondition());
182 if (!PN->hasOneUse()) return;
183
184 BasicBlock *BB = SI->getParent();
Devang Patel1851db62009-02-05 19:15:39 +0000185 if (!isTerminatorFirstRelevantInsn (BB, SI))
Chris Lattner36d12732005-04-15 19:28:32 +0000186 return;
187
188 bool RemovedPreds = false;
189
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.
Chris Lattner36d12732005-04-15 19:28:32 +0000197 unsigned DestCase = SI->findCaseValue(CI);
198 RevectorBlockTo(PN->getIncomingBlock(i-1),
199 SI->getSuccessor(DestCase));
200 ++NumSwThread;
201 RemovedPreds = true;
202
Chris Lattner9dd7a512007-08-02 04:47:05 +0000203 // 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
206 // last time.
207 if (SI->getCondition() != PN) return;
Chris Lattner36d12732005-04-15 19:28:32 +0000208 }
209}
210
211
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.
214void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
215 BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
216 assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");
217
218 // Get the old block we are threading through.
219 BasicBlock *OldSucc = FromBr->getSuccessor(0);
220
Devang Patele0805a22006-11-01 23:04:45 +0000221 // 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.
Chris Lattner29874e02008-12-03 19:44:02 +0000224 FoldSingleEntryPHINodes(ToBB);
Chris Lattner36d12732005-04-15 19:28:32 +0000225
226 // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
227 OldSucc->removePredecessor(FromBB);
228
229 // Change FromBr to branch to the new destination.
230 FromBr->setSuccessor(0, ToBB);
231
232 MadeChange = true;
233}