blob: 912d1d6352040da51e5fa0b67cfa68369f6047f8 [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +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//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner01d1ee32002-05-21 20:50:24 +00009//
Chris Lattnerbb190ac2002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner01d1ee32002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner218a8222004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner01d1ee32002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000016#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Devang Patel383d7ed2009-02-03 22:12:02 +000018#include "llvm/IntrinsicInst.h"
Chris Lattner0d560082004-02-24 05:38:11 +000019#include "llvm/Type.h"
Reid Spencerc1030572007-01-19 21:13:56 +000020#include "llvm/DerivedTypes.h"
Dale Johannesenf8bc3002009-05-13 18:25:07 +000021#include "llvm/GlobalVariable.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000022#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000024#include "llvm/Support/raw_ostream.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000026#include "llvm/Target/TargetData.h"
Chris Lattnereaba3a12005-09-19 23:49:37 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman2c635662009-10-30 22:39:04 +000028#include "llvm/ADT/DenseMap.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000029#include "llvm/ADT/SmallVector.h"
Chris Lattnerc9951232007-04-02 01:44:59 +000030#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng502a4f52008-06-12 21:15:59 +000031#include "llvm/ADT/Statistic.h"
Chris Lattner6d4d21e2010-12-13 02:00:58 +000032#include "llvm/ADT/STLExtras.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000033#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000034#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000035#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Evan Cheng502a4f52008-06-12 21:15:59 +000038STATISTIC(NumSpeculations, "Number of speculative executed instructions");
39
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000040namespace {
41class SimplifyCFGOpt {
42 const TargetData *const TD;
43
44 ConstantInt *GetConstantInt(Value *V);
45 Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values);
46 Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values);
Chris Lattnercd4b7092010-12-13 01:57:34 +000047 bool GatherValueComparisons(Value *Cond, Value *&CompVal,
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000048 std::vector<ConstantInt*> &Values);
49 Value *isValueEqualityComparison(TerminatorInst *TI);
50 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
51 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
52 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
53 BasicBlock *Pred);
54 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI);
55
56public:
57 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
58 bool run(BasicBlock *BB);
59};
60}
61
Chris Lattner2bdcb562005-08-03 00:19:45 +000062/// SafeToMergeTerminators - Return true if it is safe to merge these two
63/// terminator instructions together.
64///
65static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
66 if (SI1 == SI2) return false; // Can't merge with self!
67
68 // It is not safe to merge these two switch instructions if they have a common
69 // successor, and if that successor has a PHI node, and if *that* PHI node has
70 // conflicting incoming values from the two switch blocks.
71 BasicBlock *SI1BB = SI1->getParent();
72 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000073 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000074
75 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
76 if (SI1Succs.count(*I))
77 for (BasicBlock::iterator BBI = (*I)->begin();
78 isa<PHINode>(BBI); ++BBI) {
79 PHINode *PN = cast<PHINode>(BBI);
80 if (PN->getIncomingValueForBlock(SI1BB) !=
81 PN->getIncomingValueForBlock(SI2BB))
82 return false;
83 }
84
85 return true;
86}
87
88/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
89/// now be entries in it from the 'NewPred' block. The values that will be
90/// flowing into the PHI nodes will be the same as those coming in from
91/// ExistPred, an existing predecessor of Succ.
92static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
93 BasicBlock *ExistPred) {
94 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
95 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
96 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
97
Chris Lattner093a4382008-07-13 22:23:11 +000098 PHINode *PN;
99 for (BasicBlock::iterator I = Succ->begin();
100 (PN = dyn_cast<PHINode>(I)); ++I)
101 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000102}
103
Chris Lattner7e663482005-08-03 00:11:16 +0000104
Chris Lattner723c66d2004-02-11 03:36:04 +0000105/// GetIfCondition - Given a basic block (BB) with two predecessors (and
106/// presumably PHI nodes in it), check to see if the merge at this block is due
107/// to an "if condition". If so, return the boolean condition that determines
108/// which entry into BB will be taken. Also, return by references the block
109/// that will be entered from if the condition is true, and the block that will
110/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000111///
Chris Lattner723c66d2004-02-11 03:36:04 +0000112///
113static Value *GetIfCondition(BasicBlock *BB,
114 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
115 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
116 "Function can only handle blocks with 2 predecessors!");
117 BasicBlock *Pred1 = *pred_begin(BB);
118 BasicBlock *Pred2 = *++pred_begin(BB);
119
120 // We can only handle branches. Other control flow will be lowered to
121 // branches if possible anyway.
122 if (!isa<BranchInst>(Pred1->getTerminator()) ||
123 !isa<BranchInst>(Pred2->getTerminator()))
124 return 0;
125 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
126 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
127
128 // Eliminate code duplication by ensuring that Pred1Br is conditional if
129 // either are.
130 if (Pred2Br->isConditional()) {
131 // If both branches are conditional, we don't have an "if statement". In
132 // reality, we could transform this case, but since the condition will be
133 // required anyway, we stand no chance of eliminating it, so the xform is
134 // probably not profitable.
135 if (Pred1Br->isConditional())
136 return 0;
137
138 std::swap(Pred1, Pred2);
139 std::swap(Pred1Br, Pred2Br);
140 }
141
142 if (Pred1Br->isConditional()) {
143 // If we found a conditional branch predecessor, make sure that it branches
144 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
145 if (Pred1Br->getSuccessor(0) == BB &&
146 Pred1Br->getSuccessor(1) == Pred2) {
147 IfTrue = Pred1;
148 IfFalse = Pred2;
149 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
150 Pred1Br->getSuccessor(1) == BB) {
151 IfTrue = Pred2;
152 IfFalse = Pred1;
153 } else {
154 // We know that one arm of the conditional goes to BB, so the other must
155 // go somewhere unrelated, and this must not be an "if statement".
156 return 0;
157 }
158
159 // The only thing we have to watch out for here is to make sure that Pred2
160 // doesn't have incoming edges from other blocks. If it does, the condition
161 // doesn't dominate BB.
162 if (++pred_begin(Pred2) != pred_end(Pred2))
163 return 0;
164
165 return Pred1Br->getCondition();
166 }
167
168 // Ok, if we got here, both predecessors end with an unconditional branch to
169 // BB. Don't panic! If both blocks only have a single (identical)
170 // predecessor, and THAT is a conditional branch, then we're all ok!
171 if (pred_begin(Pred1) == pred_end(Pred1) ||
172 ++pred_begin(Pred1) != pred_end(Pred1) ||
173 pred_begin(Pred2) == pred_end(Pred2) ||
174 ++pred_begin(Pred2) != pred_end(Pred2) ||
175 *pred_begin(Pred1) != *pred_begin(Pred2))
176 return 0;
177
178 // Otherwise, if this is a conditional branch, then we can use it!
179 BasicBlock *CommonPred = *pred_begin(Pred1);
180 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
181 assert(BI->isConditional() && "Two successors but not conditional?");
182 if (BI->getSuccessor(0) == Pred1) {
183 IfTrue = Pred1;
184 IfFalse = Pred2;
185 } else {
186 IfTrue = Pred2;
187 IfFalse = Pred1;
188 }
189 return BI->getCondition();
190 }
191 return 0;
192}
193
Bill Wendling5049fa62009-01-19 23:43:56 +0000194/// DominatesMergePoint - If we have a merge point of an "if condition" as
195/// accepted above, return true if the specified value dominates the block. We
196/// don't handle the true generality of domination here, just a special case
197/// which works well enough for us.
198///
199/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
200/// see if V (which must be an instruction) is cheap to compute and is
201/// non-trapping. If both are true, the instruction is inserted into the set
202/// and true is returned.
Chris Lattner9c078662004-10-14 05:13:36 +0000203static bool DominatesMergePoint(Value *V, BasicBlock *BB,
204 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000205 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000206 if (!I) {
207 // Non-instructions all dominate instructions, but not all constantexprs
208 // can be executed unconditionally.
209 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
210 if (C->canTrap())
211 return false;
212 return true;
213 }
Chris Lattner570751c2004-04-09 22:50:22 +0000214 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000215
Chris Lattnerda895d62005-02-27 06:18:25 +0000216 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000217 // the bottom of this block.
218 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000219
Chris Lattner570751c2004-04-09 22:50:22 +0000220 // If this instruction is defined in a block that contains an unconditional
221 // branch to BB, then it must be in the 'conditional' part of the "if
222 // statement".
223 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
224 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner9c078662004-10-14 05:13:36 +0000225 if (!AggressiveInsts) return false;
Chris Lattner570751c2004-04-09 22:50:22 +0000226 // Okay, it looks like the instruction IS in the "condition". Check to
Dan Gohman4bb31bf2010-03-30 20:04:57 +0000227 // see if it's a cheap instruction to unconditionally compute, and if it
Chris Lattner570751c2004-04-09 22:50:22 +0000228 // only uses stuff defined outside of the condition. If so, hoist it out.
Eli Friedman0b79a772009-07-17 04:28:42 +0000229 if (!I->isSafeToSpeculativelyExecute())
230 return false;
231
Chris Lattner570751c2004-04-09 22:50:22 +0000232 switch (I->getOpcode()) {
233 default: return false; // Cannot hoist this out safely.
Dale Johannesen3a56d142009-03-06 21:08:33 +0000234 case Instruction::Load: {
Eli Friedman0b79a772009-07-17 04:28:42 +0000235 // We have to check to make sure there are no instructions before the
236 // load in its basic block, as we are going to hoist the loop out to
237 // its predecessor.
Dale Johannesen3a56d142009-03-06 21:08:33 +0000238 BasicBlock::iterator IP = PBB->begin();
239 while (isa<DbgInfoIntrinsic>(IP))
240 IP++;
241 if (IP != BasicBlock::iterator(I))
Chris Lattner570751c2004-04-09 22:50:22 +0000242 return false;
243 break;
Dale Johannesen3a56d142009-03-06 21:08:33 +0000244 }
Chris Lattner570751c2004-04-09 22:50:22 +0000245 case Instruction::Add:
246 case Instruction::Sub:
247 case Instruction::And:
248 case Instruction::Or:
249 case Instruction::Xor:
250 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000251 case Instruction::LShr:
252 case Instruction::AShr:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000253 case Instruction::ICmp:
Chris Lattner570751c2004-04-09 22:50:22 +0000254 break; // These are all cheap and non-trapping instructions.
255 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000256
Chris Lattner570751c2004-04-09 22:50:22 +0000257 // Okay, we can only really hoist these out if their operands are not
258 // defined in the conditional region.
Gabor Greiff7ea3632008-06-10 22:03:26 +0000259 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
260 if (!DominatesMergePoint(*i, BB, 0))
Chris Lattner570751c2004-04-09 22:50:22 +0000261 return false;
Chris Lattner9c078662004-10-14 05:13:36 +0000262 // Okay, it's safe to do this! Remember this instruction.
263 AggressiveInsts->insert(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000264 }
265
Chris Lattner723c66d2004-02-11 03:36:04 +0000266 return true;
267}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000268
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000269/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
270/// and PointerNullValue. Return NULL if value is not a constant int.
271ConstantInt *SimplifyCFGOpt::GetConstantInt(Value *V) {
272 // Normal constant int.
273 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000274 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000275 return CI;
276
277 // This is some kind of pointer constant. Turn it into a pointer-sized
278 // ConstantInt if possible.
279 const IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
280
281 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
282 if (isa<ConstantPointerNull>(V))
283 return ConstantInt::get(PtrTy, 0);
284
285 // IntToPtr const int.
286 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
287 if (CE->getOpcode() == Instruction::IntToPtr)
288 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
289 // The constant is very likely to have the right type already.
290 if (CI->getType() == PtrTy)
291 return CI;
292 else
293 return cast<ConstantInt>
294 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
295 }
296 return 0;
297}
298
Bill Wendling5049fa62009-01-19 23:43:56 +0000299/// GatherConstantSetEQs - Given a potentially 'or'd together collection of
300/// icmp_eq instructions that compare a value against a constant, return the
301/// value being compared, and stick the constant into the Values vector.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000302Value *SimplifyCFGOpt::
303GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000304 Instruction *Inst = dyn_cast<Instruction>(V);
305 if (Inst == 0) return 0;
306
307 if (Inst->getOpcode() == Instruction::ICmp &&
308 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
309 if (ConstantInt *C = GetConstantInt(Inst->getOperand(1))) {
310 Values.push_back(C);
311 return Inst->getOperand(0);
Chris Lattner0d560082004-02-24 05:38:11 +0000312 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000313 if (ConstantInt *C = GetConstantInt(Inst->getOperand(0))) {
314 Values.push_back(C);
315 return Inst->getOperand(1);
316 }
317 } else if (Inst->getOpcode() == Instruction::Or) {
318 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
319 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
320 if (LHS == RHS)
321 return LHS;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000322 }
Chris Lattner0d560082004-02-24 05:38:11 +0000323 return 0;
324}
325
Bill Wendling5049fa62009-01-19 23:43:56 +0000326/// GatherConstantSetNEs - Given a potentially 'and'd together collection of
327/// setne instructions that compare a value against a constant, return the value
328/// being compared, and stick the constant into the Values vector.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000329Value *SimplifyCFGOpt::
330GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000331 Instruction *Inst = dyn_cast<Instruction>(V);
332 if (Inst == 0) return 0;
333
334 if (Inst->getOpcode() == Instruction::ICmp &&
335 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
336 if (ConstantInt *C = GetConstantInt(Inst->getOperand(1))) {
337 Values.push_back(C);
338 return Inst->getOperand(0);
Chris Lattner0d560082004-02-24 05:38:11 +0000339 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000340 if (ConstantInt *C = GetConstantInt(Inst->getOperand(0))) {
341 Values.push_back(C);
342 return Inst->getOperand(1);
343 }
344 } else if (Inst->getOpcode() == Instruction::And) {
345 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
346 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
347 if (LHS == RHS)
348 return LHS;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000349 }
Chris Lattner0d560082004-02-24 05:38:11 +0000350 return 0;
351}
352
Chris Lattner0d560082004-02-24 05:38:11 +0000353/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
354/// bunch of comparisons of one value against constants, return the value and
355/// the constants being compared.
Chris Lattnercd4b7092010-12-13 01:57:34 +0000356bool SimplifyCFGOpt::GatherValueComparisons(Value *CondV, Value *&CompVal,
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000357 std::vector<ConstantInt*> &Values) {
Chris Lattnercd4b7092010-12-13 01:57:34 +0000358 Instruction *Cond = dyn_cast<Instruction>(CondV);
359 if (Cond == 0) return false;
360
Chris Lattner0d560082004-02-24 05:38:11 +0000361 if (Cond->getOpcode() == Instruction::Or) {
362 CompVal = GatherConstantSetEQs(Cond, Values);
363
364 // Return true to indicate that the condition is true if the CompVal is
365 // equal to one of the constants.
366 return true;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000367 }
368 if (Cond->getOpcode() == Instruction::And) {
Chris Lattner0d560082004-02-24 05:38:11 +0000369 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanfd939082005-04-21 23:48:37 +0000370
Chris Lattner0d560082004-02-24 05:38:11 +0000371 // Return false to indicate that the condition is false if the CompVal is
372 // equal to one of the constants.
373 return false;
374 }
375 return false;
376}
377
Eli Friedman080efb82008-12-16 20:54:32 +0000378static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
379 Instruction* Cond = 0;
380 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
381 Cond = dyn_cast<Instruction>(SI->getCondition());
382 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
383 if (BI->isConditional())
384 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000385 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
386 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000387 }
388
389 TI->eraseFromParent();
390 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
391}
392
Chris Lattner9fd49552008-11-27 23:25:44 +0000393/// isValueEqualityComparison - Return true if the specified terminator checks
394/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000395Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
396 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000397 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
398 // Do not permit merging of large switch instructions into their
399 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000400 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
401 pred_end(SI->getParent())) <= 128)
402 CV = SI->getCondition();
403 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000404 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000405 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
406 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
407 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000408 GetConstantInt(ICI->getOperand(1)))
409 CV = ICI->getOperand(0);
410
411 // Unwrap any lossless ptrtoint cast.
412 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
413 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
414 CV = PTII->getOperand(0);
415 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000416}
417
Bill Wendling5049fa62009-01-19 23:43:56 +0000418/// GetValueEqualityComparisonCases - Given a value comparison instruction,
419/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000420BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000421GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000422 std::vector<std::pair<ConstantInt*,
423 BasicBlock*> > &Cases) {
424 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
425 Cases.reserve(SI->getNumCases());
426 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000427 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000428 return SI->getDefaultDest();
429 }
430
431 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000432 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000433 Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1)),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000434 BI->getSuccessor(ICI->getPredicate() ==
435 ICmpInst::ICMP_NE)));
436 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000437}
438
439
Bill Wendling5049fa62009-01-19 23:43:56 +0000440/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
441/// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000442static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000443 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
444 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
445 if (Cases[i].second == BB) {
446 Cases.erase(Cases.begin()+i);
447 --i; --e;
448 }
449}
450
Bill Wendling5049fa62009-01-19 23:43:56 +0000451/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
452/// well.
Chris Lattner623369a2005-02-24 06:17:52 +0000453static bool
454ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
455 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
456 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
457
458 // Make V1 be smaller than V2.
459 if (V1->size() > V2->size())
460 std::swap(V1, V2);
461
462 if (V1->size() == 0) return false;
463 if (V1->size() == 1) {
464 // Just scan V2.
465 ConstantInt *TheVal = (*V1)[0].first;
466 for (unsigned i = 0, e = V2->size(); i != e; ++i)
467 if (TheVal == (*V2)[i].first)
468 return true;
469 }
470
471 // Otherwise, just sort both lists and compare element by element.
472 std::sort(V1->begin(), V1->end());
473 std::sort(V2->begin(), V2->end());
474 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
475 while (i1 != e1 && i2 != e2) {
476 if ((*V1)[i1].first == (*V2)[i2].first)
477 return true;
478 if ((*V1)[i1].first < (*V2)[i2].first)
479 ++i1;
480 else
481 ++i2;
482 }
483 return false;
484}
485
Bill Wendling5049fa62009-01-19 23:43:56 +0000486/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
487/// terminator instruction and its block is known to only have a single
488/// predecessor block, check to see if that predecessor is also a value
489/// comparison with the same value, and if that comparison determines the
490/// outcome of this comparison. If so, simplify TI. This does a very limited
491/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000492bool SimplifyCFGOpt::
493SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
494 BasicBlock *Pred) {
Chris Lattner623369a2005-02-24 06:17:52 +0000495 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
496 if (!PredVal) return false; // Not a value comparison in predecessor.
497
498 Value *ThisVal = isValueEqualityComparison(TI);
499 assert(ThisVal && "This isn't a value comparison!!");
500 if (ThisVal != PredVal) return false; // Different predicates.
501
502 // Find out information about when control will move from Pred to TI's block.
503 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
504 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
505 PredCases);
506 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000507
Chris Lattner623369a2005-02-24 06:17:52 +0000508 // Find information about how control leaves this block.
509 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
510 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
511 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
512
513 // If TI's block is the default block from Pred's comparison, potentially
514 // simplify TI based on this knowledge.
515 if (PredDef == TI->getParent()) {
516 // If we are here, we know that the value is none of those cases listed in
517 // PredCases. If there are any cases in ThisCases that are in PredCases, we
518 // can simplify TI.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000519 if (!ValuesOverlap(PredCases, ThisCases))
520 return false;
521
522 if (isa<BranchInst>(TI)) {
523 // Okay, one of the successors of this condbr is dead. Convert it to a
524 // uncond br.
525 assert(ThisCases.size() == 1 && "Branch can only have one case!");
526 // Insert the new branch.
527 Instruction *NI = BranchInst::Create(ThisDef, TI);
528 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000529
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000530 // Remove PHI node entries for the dead edge.
531 ThisCases[0].second->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000532
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000533 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
534 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000535
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000536 EraseTerminatorInstAndDCECond(TI);
537 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000538 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000539
540 SwitchInst *SI = cast<SwitchInst>(TI);
541 // Okay, TI has cases that are statically dead, prune them away.
542 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000543 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000544 DeadCases.insert(PredCases[i].first);
Chris Lattner623369a2005-02-24 06:17:52 +0000545
David Greene89d6fd32010-01-05 01:26:52 +0000546 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000547 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000548
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000549 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
550 if (DeadCases.count(SI->getCaseValue(i))) {
551 SI->getSuccessor(i)->removePredecessor(TI->getParent());
552 SI->removeCase(i);
553 }
554
555 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000556 return true;
557 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000558
559 // Otherwise, TI's block must correspond to some matched value. Find out
560 // which value (or set of values) this is.
561 ConstantInt *TIV = 0;
562 BasicBlock *TIBB = TI->getParent();
563 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
564 if (PredCases[i].second == TIBB) {
565 if (TIV != 0)
566 return false; // Cannot handle multiple values coming to this block.
567 TIV = PredCases[i].first;
568 }
569 assert(TIV && "No edge from pred to succ?");
570
571 // Okay, we found the one constant that our value can be if we get into TI's
572 // BB. Find out which successor will unconditionally be branched to.
573 BasicBlock *TheRealDest = 0;
574 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
575 if (ThisCases[i].first == TIV) {
576 TheRealDest = ThisCases[i].second;
577 break;
578 }
579
580 // If not handled by any explicit cases, it is handled by the default case.
581 if (TheRealDest == 0) TheRealDest = ThisDef;
582
583 // Remove PHI node entries for dead edges.
584 BasicBlock *CheckEdge = TheRealDest;
585 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
586 if (*SI != CheckEdge)
587 (*SI)->removePredecessor(TIBB);
588 else
589 CheckEdge = 0;
590
591 // Insert the new branch.
592 Instruction *NI = BranchInst::Create(TheRealDest, TI);
593 (void) NI;
594
595 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
596 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
597
598 EraseTerminatorInstAndDCECond(TI);
599 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000600}
601
Dale Johannesenc81f5442009-03-12 21:01:11 +0000602namespace {
603 /// ConstantIntOrdering - This class implements a stable ordering of constant
604 /// integers that does not depend on their address. This is important for
605 /// applications that sort ConstantInt's to ensure uniqueness.
606 struct ConstantIntOrdering {
607 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
608 return LHS->getValue().ult(RHS->getValue());
609 }
610 };
611}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000612
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000613static int ConstantIntSortPredicate(const void *P1, const void *P2) {
614 const ConstantInt *LHS = *(const ConstantInt**)P1;
615 const ConstantInt *RHS = *(const ConstantInt**)P2;
616 return LHS->getValue().ult(RHS->getValue());
617}
618
Bill Wendling5049fa62009-01-19 23:43:56 +0000619/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
620/// equality comparison instruction (either a switch or a branch on "X == c").
621/// See if any of the predecessors of the terminator block are value comparisons
622/// on the same value. If so, and if safe to do so, fold them together.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000623bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
Chris Lattner542f1492004-02-28 21:28:10 +0000624 BasicBlock *BB = TI->getParent();
625 Value *CV = isValueEqualityComparison(TI); // CondVal
626 assert(CV && "Not a comparison?");
627 bool Changed = false;
628
Chris Lattner82442432008-02-18 07:42:56 +0000629 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000630 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000631 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000632
Chris Lattner542f1492004-02-28 21:28:10 +0000633 // See if the predecessor is a comparison with the same value.
634 TerminatorInst *PTI = Pred->getTerminator();
635 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
636
637 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
638 // Figure out which 'cases' to copy from SI to PSI.
639 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
640 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
641
642 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
643 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
644
645 // Based on whether the default edge from PTI goes to BB or not, fill in
646 // PredCases and PredDefault with the new switch cases we would like to
647 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000648 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000649
650 if (PredDefault == BB) {
651 // If this is the default destination from PTI, only the edges in TI
652 // that don't occur in PTI, or that branch to BB will be activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000653 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000654 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
655 if (PredCases[i].second != BB)
656 PTIHandled.insert(PredCases[i].first);
657 else {
658 // The default destination is BB, we don't need explicit targets.
659 std::swap(PredCases[i], PredCases.back());
660 PredCases.pop_back();
661 --i; --e;
662 }
663
664 // Reconstruct the new switch statement we will be building.
665 if (PredDefault != BBDefault) {
666 PredDefault->removePredecessor(Pred);
667 PredDefault = BBDefault;
668 NewSuccessors.push_back(BBDefault);
669 }
670 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
671 if (!PTIHandled.count(BBCases[i].first) &&
672 BBCases[i].second != BBDefault) {
673 PredCases.push_back(BBCases[i]);
674 NewSuccessors.push_back(BBCases[i].second);
675 }
676
677 } else {
678 // If this is not the default destination from PSI, only the edges
679 // in SI that occur in PSI with a destination of BB will be
680 // activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000681 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000682 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
683 if (PredCases[i].second == BB) {
684 PTIHandled.insert(PredCases[i].first);
685 std::swap(PredCases[i], PredCases.back());
686 PredCases.pop_back();
687 --i; --e;
688 }
689
690 // Okay, now we know which constants were sent to BB from the
691 // predecessor. Figure out where they will all go now.
692 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
693 if (PTIHandled.count(BBCases[i].first)) {
694 // If this is one we are capable of getting...
695 PredCases.push_back(BBCases[i]);
696 NewSuccessors.push_back(BBCases[i].second);
697 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
698 }
699
700 // If there are any constants vectored to BB that TI doesn't handle,
701 // they must go to the default destination of TI.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000702 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
703 PTIHandled.begin(),
Chris Lattner542f1492004-02-28 21:28:10 +0000704 E = PTIHandled.end(); I != E; ++I) {
705 PredCases.push_back(std::make_pair(*I, BBDefault));
706 NewSuccessors.push_back(BBDefault);
707 }
708 }
709
710 // Okay, at this point, we know which new successor Pred will get. Make
711 // sure we update the number of entries in the PHI nodes for these
712 // successors.
713 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
714 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
715
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000716 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000717 if (CV->getType()->isPointerTy()) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000718 assert(TD && "Cannot switch on pointer without TargetData");
719 CV = new PtrToIntInst(CV, TD->getIntPtrType(CV->getContext()),
720 "magicptr", PTI);
721 }
722
Chris Lattner542f1492004-02-28 21:28:10 +0000723 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000724 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
725 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000726 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
727 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000728
Eli Friedman080efb82008-12-16 20:54:32 +0000729 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000730
Chris Lattner542f1492004-02-28 21:28:10 +0000731 // Okay, last check. If BB is still a successor of PSI, then we must
732 // have an infinite loop case. If so, add an infinitely looping block
733 // to handle the case to preserve the behavior of the code.
734 BasicBlock *InfLoopBlock = 0;
735 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
736 if (NewSI->getSuccessor(i) == BB) {
737 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000738 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000739 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +0000740 InfLoopBlock = BasicBlock::Create(BB->getContext(),
741 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +0000742 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000743 }
744 NewSI->setSuccessor(i, InfLoopBlock);
745 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000746
Chris Lattner542f1492004-02-28 21:28:10 +0000747 Changed = true;
748 }
749 }
750 return Changed;
751}
752
Dale Johannesenc1f10402009-06-15 20:59:27 +0000753// isSafeToHoistInvoke - If we would need to insert a select that uses the
754// value of this invoke (comments in HoistThenElseCodeToIf explain why we
755// would need to do this), we can't hoist the invoke, as there is nowhere
756// to put the select in this case.
757static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
758 Instruction *I1, Instruction *I2) {
759 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
760 PHINode *PN;
761 for (BasicBlock::iterator BBI = SI->begin();
762 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
763 Value *BB1V = PN->getIncomingValueForBlock(BB1);
764 Value *BB2V = PN->getIncomingValueForBlock(BB2);
765 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
766 return false;
767 }
768 }
769 }
770 return true;
771}
772
Chris Lattner6306d072005-08-03 17:59:45 +0000773/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000774/// BB2, hoist any common code in the two blocks up into the branch block. The
775/// caller of this function guarantees that BI's block dominates BB1 and BB2.
776static bool HoistThenElseCodeToIf(BranchInst *BI) {
777 // This does very trivial matching, with limited scanning, to find identical
778 // instructions in the two blocks. In particular, we don't want to get into
779 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
780 // such, we currently just scan for obviously identical instructions in an
781 // identical order.
782 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
783 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
784
Devang Patel65085cf2009-02-04 00:03:08 +0000785 BasicBlock::iterator BB1_Itr = BB1->begin();
786 BasicBlock::iterator BB2_Itr = BB2->begin();
787
788 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
789 while (isa<DbgInfoIntrinsic>(I1))
790 I1 = BB1_Itr++;
791 while (isa<DbgInfoIntrinsic>(I2))
792 I2 = BB2_Itr++;
Dale Johannesenc1f10402009-06-15 20:59:27 +0000793 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000794 !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +0000795 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000796 return false;
797
798 // If we get here, we can hoist at least one instruction.
799 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000800
801 do {
802 // If we are hoisting the terminator instruction, don't move one (making a
803 // broken BB), instead clone it, and remove BI.
804 if (isa<TerminatorInst>(I1))
805 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000806
Chris Lattner37dc9382004-11-30 00:29:14 +0000807 // For a normal instruction, we just move one to right before the branch,
808 // then replace all uses of the other with the first. Finally, we remove
809 // the now redundant second instruction.
810 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
811 if (!I2->use_empty())
812 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000813 I1->intersectOptionalDataWith(I2);
Chris Lattner37dc9382004-11-30 00:29:14 +0000814 BB2->getInstList().erase(I2);
Misha Brukmanfd939082005-04-21 23:48:37 +0000815
Devang Patel65085cf2009-02-04 00:03:08 +0000816 I1 = BB1_Itr++;
817 while (isa<DbgInfoIntrinsic>(I1))
818 I1 = BB1_Itr++;
819 I2 = BB2_Itr++;
820 while (isa<DbgInfoIntrinsic>(I2))
821 I2 = BB2_Itr++;
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000822 } while (I1->getOpcode() == I2->getOpcode() &&
823 I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +0000824
825 return true;
826
827HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000828 // It may not be possible to hoist an invoke.
829 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
830 return true;
831
Chris Lattner37dc9382004-11-30 00:29:14 +0000832 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +0000833 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +0000834 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +0000835 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000836 I1->replaceAllUsesWith(NT);
837 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000838 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000839 }
840
841 // Hoisting one of the terminators from our successor is a great thing.
842 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
843 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
844 // nodes, so we insert select instruction to compute the final result.
845 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
846 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
847 PHINode *PN;
848 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000849 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000850 Value *BB1V = PN->getIncomingValueForBlock(BB1);
851 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000852 if (BB1V == BB2V) continue;
853
854 // These values do not agree. Insert a select instruction before NT
855 // that determines the right value.
856 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
857 if (SI == 0)
858 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
859 BB1V->getName()+"."+BB2V->getName(), NT);
860 // Make the PHI node use the select for all incoming values for BB1/BB2
861 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
862 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
863 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000864 }
865 }
866
867 // Update any PHI nodes in our new successors.
868 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
869 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000870
Eli Friedman080efb82008-12-16 20:54:32 +0000871 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000872 return true;
873}
874
Evan Cheng4d09efd2008-06-07 08:52:29 +0000875/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
876/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
877/// (for now, restricted to a single instruction that's side effect free) from
878/// the BB1 into the branch block to speculatively execute it.
879static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
880 // Only speculatively execution a single instruction (not counting the
881 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000882 Instruction *HInst = NULL;
883 Instruction *Term = BB1->getTerminator();
884 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
885 BBI != BBE; ++BBI) {
886 Instruction *I = BBI;
887 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000888 if (isa<DbgInfoIntrinsic>(I)) continue;
889 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +0000890
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000891 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +0000892 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000893 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +0000894 }
895 if (!HInst)
896 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000897
Evan Cheng797d9512008-06-11 19:18:20 +0000898 // Be conservative for now. FP select instruction can often be expensive.
899 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000900 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +0000901 return false;
902
Evan Cheng4d09efd2008-06-07 08:52:29 +0000903 // If BB1 is actually on the false edge of the conditional branch, remember
904 // to swap the select operands later.
905 bool Invert = false;
906 if (BB1 != BI->getSuccessor(0)) {
907 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
908 Invert = true;
909 }
910
911 // Turn
912 // BB:
913 // %t1 = icmp
914 // br i1 %t1, label %BB1, label %BB2
915 // BB1:
916 // %t3 = add %t2, c
917 // br label BB2
918 // BB2:
919 // =>
920 // BB:
921 // %t1 = icmp
922 // %t4 = add %t2, c
923 // %t3 = select i1 %t1, %t2, %t3
Devang Patel06b1e672009-03-06 06:00:17 +0000924 switch (HInst->getOpcode()) {
Evan Cheng4d09efd2008-06-07 08:52:29 +0000925 default: return false; // Not safe / profitable to hoist.
926 case Instruction::Add:
927 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000928 // Not worth doing for vector ops.
Duncan Sands1df98592010-02-16 11:11:14 +0000929 if (HInst->getType()->isVectorTy())
Chris Lattner9dd3b612009-01-18 23:22:07 +0000930 return false;
931 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000932 case Instruction::And:
933 case Instruction::Or:
934 case Instruction::Xor:
935 case Instruction::Shl:
936 case Instruction::LShr:
937 case Instruction::AShr:
Chris Lattner9dd3b612009-01-18 23:22:07 +0000938 // Don't mess with vector operations.
Duncan Sands1df98592010-02-16 11:11:14 +0000939 if (HInst->getType()->isVectorTy())
Evan Chenge5334ea2008-06-25 07:50:12 +0000940 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000941 break; // These are all cheap and non-trapping instructions.
942 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000943
944 // If the instruction is obviously dead, don't try to predicate it.
Devang Patel06b1e672009-03-06 06:00:17 +0000945 if (HInst->use_empty()) {
946 HInst->eraseFromParent();
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000947 return true;
948 }
Evan Cheng4d09efd2008-06-07 08:52:29 +0000949
950 // Can we speculatively execute the instruction? And what is the value
951 // if the condition is false? Consider the phi uses, if the incoming value
952 // from the "if" block are all the same V, then V is the value of the
953 // select if the condition is false.
954 BasicBlock *BIParent = BI->getParent();
955 SmallVector<PHINode*, 4> PHIUses;
956 Value *FalseV = NULL;
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000957
958 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Devang Patel06b1e672009-03-06 06:00:17 +0000959 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
Evan Cheng4d09efd2008-06-07 08:52:29 +0000960 UI != E; ++UI) {
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000961 // Ignore any user that is not a PHI node in BB2. These can only occur in
962 // unreachable blocks, because they would not be dominated by the instr.
Gabor Greif20361b92010-07-22 11:43:44 +0000963 PHINode *PN = dyn_cast<PHINode>(*UI);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000964 if (!PN || PN->getParent() != BB2)
965 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000966 PHIUses.push_back(PN);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000967
Evan Cheng4d09efd2008-06-07 08:52:29 +0000968 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
969 if (!FalseV)
970 FalseV = PHIV;
971 else if (FalseV != PHIV)
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000972 return false; // Inconsistent value when condition is false.
Evan Cheng4d09efd2008-06-07 08:52:29 +0000973 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000974
975 assert(FalseV && "Must have at least one user, and it must be a PHI");
Evan Cheng4d09efd2008-06-07 08:52:29 +0000976
Evan Cheng502a4f52008-06-12 21:15:59 +0000977 // Do not hoist the instruction if any of its operands are defined but not
978 // used in this BB. The transformation will prevent the operand from
979 // being sunk into the use block.
Devang Patel06b1e672009-03-06 06:00:17 +0000980 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
981 i != e; ++i) {
Evan Cheng502a4f52008-06-12 21:15:59 +0000982 Instruction *OpI = dyn_cast<Instruction>(*i);
983 if (OpI && OpI->getParent() == BIParent &&
984 !OpI->isUsedInBasicBlock(BIParent))
985 return false;
986 }
987
Devang Patel3d0a9a32008-09-18 22:50:42 +0000988 // If we get here, we can hoist the instruction. Try to place it
Dale Johannesen990afed2009-03-13 01:05:24 +0000989 // before the icmp instruction preceding the conditional branch.
Devang Patel3d0a9a32008-09-18 22:50:42 +0000990 BasicBlock::iterator InsertPos = BI;
Dale Johannesen990afed2009-03-13 01:05:24 +0000991 if (InsertPos != BIParent->begin())
992 --InsertPos;
993 // Skip debug info between condition and branch.
994 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
Devang Patel3d0a9a32008-09-18 22:50:42 +0000995 --InsertPos;
Devang Patel20da1f02008-10-03 18:57:37 +0000996 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
Devang Patel3d0a9a32008-09-18 22:50:42 +0000997 SmallPtrSet<Instruction *, 4> BB1Insns;
998 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
999 BB1I != BB1E; ++BB1I)
1000 BB1Insns.insert(BB1I);
1001 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1002 UI != UE; ++UI) {
1003 Instruction *Use = cast<Instruction>(*UI);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001004 if (!BB1Insns.count(Use)) continue;
1005
1006 // If BrCond uses the instruction that place it just before
1007 // branch instruction.
1008 InsertPos = BI;
1009 break;
Devang Patel3d0a9a32008-09-18 22:50:42 +00001010 }
1011 } else
1012 InsertPos = BI;
Devang Patel06b1e672009-03-06 06:00:17 +00001013 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001014
1015 // Create a select whose true value is the speculatively executed value and
1016 // false value is the previously determined FalseV.
1017 SelectInst *SI;
1018 if (Invert)
Devang Patel06b1e672009-03-06 06:00:17 +00001019 SI = SelectInst::Create(BrCond, FalseV, HInst,
1020 FalseV->getName() + "." + HInst->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001021 else
Devang Patel06b1e672009-03-06 06:00:17 +00001022 SI = SelectInst::Create(BrCond, HInst, FalseV,
1023 HInst->getName() + "." + FalseV->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001024
1025 // Make the PHI node use the select for all incoming values for "then" and
1026 // "if" blocks.
1027 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1028 PHINode *PN = PHIUses[i];
1029 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001030 if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
Evan Cheng4d09efd2008-06-07 08:52:29 +00001031 PN->setIncomingValue(j, SI);
1032 }
1033
Evan Cheng502a4f52008-06-12 21:15:59 +00001034 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001035 return true;
1036}
1037
Chris Lattner2e42e362005-09-20 00:43:16 +00001038/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1039/// across this block.
1040static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1041 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001042 unsigned Size = 0;
1043
Devang Patel9200c892009-03-10 18:00:05 +00001044 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001045 if (isa<DbgInfoIntrinsic>(BBI))
1046 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001047 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001048 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001049
Dale Johannesen8483e542009-03-12 23:18:09 +00001050 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001051 // live outside of the current basic block.
1052 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1053 UI != E; ++UI) {
1054 Instruction *U = cast<Instruction>(*UI);
1055 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1056 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001057
1058 // Looks ok, continue checking.
1059 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001060
Chris Lattner2e42e362005-09-20 00:43:16 +00001061 return true;
1062}
1063
Chris Lattnereaba3a12005-09-19 23:49:37 +00001064/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1065/// that is defined in the same block as the branch and if any PHI entries are
1066/// constants, thread edges corresponding to that entry to be branches to their
1067/// ultimate destination.
1068static bool FoldCondBranchOnPHI(BranchInst *BI) {
1069 BasicBlock *BB = BI->getParent();
1070 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001071 // NOTE: we currently cannot transform this case if the PHI node is used
1072 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001073 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1074 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001075
1076 // Degenerate case of a single entry PHI.
1077 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001078 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001079 return true;
1080 }
1081
1082 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001083 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001084
1085 // Okay, this is a simple enough basic block. See if any phi values are
1086 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001087 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001088 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1089 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1090
1091 // Okay, we now know that all edges from PredBB should be revectored to
1092 // branch to RealDest.
1093 BasicBlock *PredBB = PN->getIncomingBlock(i);
1094 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1095
1096 if (RealDest == BB) continue; // Skip self loops.
1097
1098 // The dest block might have PHI nodes, other predecessors and other
1099 // difficult cases. Instead of being smart about this, just insert a new
1100 // block that jumps to the destination block, effectively splitting
1101 // the edge we are about to create.
1102 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1103 RealDest->getName()+".critedge",
1104 RealDest->getParent(), RealDest);
1105 BranchInst::Create(RealDest, EdgeBB);
1106 PHINode *PN;
1107 for (BasicBlock::iterator BBI = RealDest->begin();
1108 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1109 Value *V = PN->getIncomingValueForBlock(BB);
1110 PN->addIncoming(V, EdgeBB);
Chris Lattnereaba3a12005-09-19 23:49:37 +00001111 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001112
1113 // BB may have instructions that are being threaded over. Clone these
1114 // instructions into EdgeBB. We know that there will be no uses of the
1115 // cloned instructions outside of EdgeBB.
1116 BasicBlock::iterator InsertPt = EdgeBB->begin();
1117 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1118 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1119 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1120 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1121 continue;
1122 }
1123 // Clone the instruction.
1124 Instruction *N = BBI->clone();
1125 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1126
1127 // Update operands due to translation.
1128 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1129 i != e; ++i) {
1130 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1131 if (PI != TranslateMap.end())
1132 *i = PI->second;
1133 }
1134
1135 // Check for trivial simplification.
1136 if (Constant *C = ConstantFoldInstruction(N)) {
1137 TranslateMap[BBI] = C;
1138 delete N; // Constant folded away, don't need actual inst
1139 } else {
1140 // Insert the new instruction into its new home.
1141 EdgeBB->getInstList().insert(InsertPt, N);
1142 if (!BBI->use_empty())
1143 TranslateMap[BBI] = N;
1144 }
1145 }
1146
1147 // Loop over all of the edges from PredBB to BB, changing them to branch
1148 // to EdgeBB instead.
1149 TerminatorInst *PredBBTI = PredBB->getTerminator();
1150 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1151 if (PredBBTI->getSuccessor(i) == BB) {
1152 BB->removePredecessor(PredBB);
1153 PredBBTI->setSuccessor(i, EdgeBB);
1154 }
1155
1156 // Recurse, simplifying any other constants.
1157 return FoldCondBranchOnPHI(BI) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001158 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001159
1160 return false;
1161}
1162
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001163/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1164/// PHI node, see if we can eliminate it.
1165static bool FoldTwoEntryPHINode(PHINode *PN) {
1166 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1167 // statement", which has a very simple dominance structure. Basically, we
1168 // are trying to find the condition that is being branched on, which
1169 // subsequently causes this merge to happen. We really want control
1170 // dependence information for this check, but simplifycfg can't keep it up
1171 // to date, and this catches most of the cases we care about anyway.
1172 //
1173 BasicBlock *BB = PN->getParent();
1174 BasicBlock *IfTrue, *IfFalse;
1175 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1176 if (!IfCond) return false;
1177
Chris Lattner822a8792006-11-18 19:19:36 +00001178 // Okay, we found that we can merge this two-entry phi node into a select.
1179 // Doing so would require us to fold *all* two entry phi nodes in this block.
1180 // At some point this becomes non-profitable (particularly if the target
1181 // doesn't support cmov's). Only do this transformation if there are two or
1182 // fewer PHI nodes in this block.
1183 unsigned NumPhis = 0;
1184 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1185 if (NumPhis > 2)
1186 return false;
1187
David Greene89d6fd32010-01-05 01:26:52 +00001188 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001189 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001190
1191 // Loop over the PHI's seeing if we can promote them all to select
1192 // instructions. While we are at it, keep track of the instructions
1193 // that need to be moved to the dominating block.
1194 std::set<Instruction*> AggressiveInsts;
1195
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001196 BasicBlock::iterator AfterPHIIt = BB->begin();
1197 while (isa<PHINode>(AfterPHIIt)) {
1198 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1199 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1200 if (PN->getIncomingValue(0) != PN)
1201 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1202 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001203 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001204 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1205 &AggressiveInsts) ||
1206 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1207 &AggressiveInsts)) {
Chris Lattner055dc102005-09-23 07:23:18 +00001208 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001209 }
1210 }
1211
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001212 // If we all PHI nodes are promotable, check to make sure that all
1213 // instructions in the predecessor blocks can be promoted as well. If
1214 // not, we won't be able to get rid of the control flow, so it's not
1215 // worth promoting to select instructions.
1216 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1217 PN = cast<PHINode>(BB->begin());
1218 BasicBlock *Pred = PN->getIncomingBlock(0);
1219 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1220 IfBlock1 = Pred;
1221 DomBlock = *pred_begin(Pred);
1222 for (BasicBlock::iterator I = Pred->begin();
1223 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001224 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001225 // This is not an aggressive instruction that we can promote.
1226 // Because of this, we won't be able to get rid of the control
1227 // flow, so the xform is not worth it.
1228 return false;
1229 }
1230 }
1231
1232 Pred = PN->getIncomingBlock(1);
1233 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1234 IfBlock2 = Pred;
1235 DomBlock = *pred_begin(Pred);
1236 for (BasicBlock::iterator I = Pred->begin();
1237 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001238 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001239 // This is not an aggressive instruction that we can promote.
1240 // Because of this, we won't be able to get rid of the control
1241 // flow, so the xform is not worth it.
1242 return false;
1243 }
1244 }
1245
1246 // If we can still promote the PHI nodes after this gauntlet of tests,
1247 // do all of the PHI's now.
1248
1249 // Move all 'aggressive' instructions, which are defined in the
1250 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001251 if (IfBlock1)
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001252 DomBlock->getInstList().splice(DomBlock->getTerminator(),
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001253 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001254 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001255 if (IfBlock2)
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001256 DomBlock->getInstList().splice(DomBlock->getTerminator(),
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001257 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001258 IfBlock2->getTerminator());
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001259
1260 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1261 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001262 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1263 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001264
Gabor Greif051a9502008-04-06 20:25:17 +00001265 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001266 PN->replaceAllUsesWith(NV);
1267 NV->takeName(PN);
1268
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001269 BB->getInstList().erase(PN);
1270 }
1271 return true;
1272}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001273
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001274/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1275/// to two returning blocks, try to merge them together into one return,
1276/// introducing a select if the return values disagree.
1277static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1278 assert(BI->isConditional() && "Must be a conditional branch");
1279 BasicBlock *TrueSucc = BI->getSuccessor(0);
1280 BasicBlock *FalseSucc = BI->getSuccessor(1);
1281 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1282 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1283
1284 // Check to ensure both blocks are empty (just a return) or optionally empty
1285 // with PHI nodes. If there are other instructions, merging would cause extra
1286 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001287 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001288 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001289 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001290 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001291
1292 // Okay, we found a branch that is going to two return nodes. If
1293 // there is no return value for this function, just change the
1294 // branch into a return.
1295 if (FalseRet->getNumOperands() == 0) {
1296 TrueSucc->removePredecessor(BI->getParent());
1297 FalseSucc->removePredecessor(BI->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +00001298 ReturnInst::Create(BI->getContext(), 0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001299 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001300 return true;
1301 }
1302
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001303 // Otherwise, figure out what the true and false return values are
1304 // so we can insert a new select instruction.
1305 Value *TrueValue = TrueRet->getReturnValue();
1306 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001307
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001308 // Unwrap any PHI nodes in the return blocks.
1309 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1310 if (TVPN->getParent() == TrueSucc)
1311 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1312 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1313 if (FVPN->getParent() == FalseSucc)
1314 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1315
1316 // In order for this transformation to be safe, we must be able to
1317 // unconditionally execute both operands to the return. This is
1318 // normally the case, but we could have a potentially-trapping
1319 // constant expression that prevents this transformation from being
1320 // safe.
1321 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1322 if (TCV->canTrap())
1323 return false;
1324 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1325 if (FCV->canTrap())
1326 return false;
1327
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001328 // Okay, we collected all the mapped values and checked them for sanity, and
1329 // defined to really do this transformation. First, update the CFG.
1330 TrueSucc->removePredecessor(BI->getParent());
1331 FalseSucc->removePredecessor(BI->getParent());
1332
1333 // Insert select instructions where needed.
1334 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001335 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001336 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001337 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1338 } else if (isa<UndefValue>(TrueValue)) {
1339 TrueValue = FalseValue;
1340 } else {
1341 TrueValue = SelectInst::Create(BrCond, TrueValue,
1342 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001343 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001344 }
1345
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001346 Value *RI = !TrueValue ?
Owen Anderson1d0be152009-08-13 21:58:54 +00001347 ReturnInst::Create(BI->getContext(), BI) :
1348 ReturnInst::Create(BI->getContext(), TrueValue, BI);
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001349 (void) RI;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001350
David Greene89d6fd32010-01-05 01:26:52 +00001351 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001352 << "\n " << *BI << "NewRet = " << *RI
1353 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001354
Eli Friedman080efb82008-12-16 20:54:32 +00001355 EraseTerminatorInstAndDCECond(BI);
1356
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001357 return true;
1358}
1359
Chris Lattner1347e872008-07-13 21:12:01 +00001360/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1361/// and if a predecessor branches to us and one of our successors, fold the
1362/// setcc into the predecessor and use logical operations to pick the right
1363/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001364bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001365 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001366 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Owen Andersone84178a2010-07-14 19:52:16 +00001367 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1368 Cond->getParent() != BB || !Cond->hasOneUse())
1369 return false;
Chris Lattner093a4382008-07-13 22:23:11 +00001370
Chris Lattner1347e872008-07-13 21:12:01 +00001371 // Only allow this if the condition is a simple instruction that can be
1372 // executed unconditionally. It must be in the same block as the branch, and
1373 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001374 BasicBlock::iterator FrontIt = BB->front();
1375 // Ignore dbg intrinsics.
1376 while(isa<DbgInfoIntrinsic>(FrontIt))
1377 ++FrontIt;
Owen Andersone84178a2010-07-14 19:52:16 +00001378
1379 // Allow a single instruction to be hoisted in addition to the compare
1380 // that feeds the branch. We later ensure that any values that _it_ uses
1381 // were also live in the predecessor, so that we don't unnecessarily create
1382 // register pressure or inhibit out-of-order execution.
1383 Instruction *BonusInst = 0;
1384 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001385 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1386 FrontIt->isSafeToSpeculativelyExecute()) {
Owen Andersone84178a2010-07-14 19:52:16 +00001387 BonusInst = &*FrontIt;
1388 ++FrontIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001389 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001390
Owen Andersone84178a2010-07-14 19:52:16 +00001391 // Only a single bonus inst is allowed.
1392 if (&*FrontIt != Cond)
1393 return false;
1394
Chris Lattner1347e872008-07-13 21:12:01 +00001395 // Make sure the instruction after the condition is the cond branch.
1396 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001397 // Ingore dbg intrinsics.
1398 while(isa<DbgInfoIntrinsic>(CondIt))
1399 ++CondIt;
1400 if (&*CondIt != BI) {
1401 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001402 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001403 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001404
1405 // Cond is known to be a compare or binary operator. Check to make sure that
1406 // neither operand is a potentially-trapping constant expression.
1407 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1408 if (CE->canTrap())
1409 return false;
1410 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1411 if (CE->canTrap())
1412 return false;
1413
Chris Lattner1347e872008-07-13 21:12:01 +00001414
1415 // Finally, don't infinitely unroll conditional loops.
1416 BasicBlock *TrueDest = BI->getSuccessor(0);
1417 BasicBlock *FalseDest = BI->getSuccessor(1);
1418 if (TrueDest == BB || FalseDest == BB)
1419 return false;
1420
1421 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1422 BasicBlock *PredBlock = *PI;
1423 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001424
Chris Lattner093a4382008-07-13 22:23:11 +00001425 // Check that we have two conditional branches. If there is a PHI node in
1426 // the common successor, verify that the same value flows in from both
1427 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001428 if (PBI == 0 || PBI->isUnconditional() ||
1429 !SafeToMergeTerminators(BI, PBI))
1430 continue;
1431
Owen Andersone84178a2010-07-14 19:52:16 +00001432 // Ensure that any values used in the bonus instruction are also used
1433 // by the terminator of the predecessor. This means that those values
1434 // must already have been resolved, so we won't be inhibiting the
1435 // out-of-order core by speculating them earlier.
1436 if (BonusInst) {
1437 // Collect the values used by the bonus inst
1438 SmallPtrSet<Value*, 4> UsedValues;
1439 for (Instruction::op_iterator OI = BonusInst->op_begin(),
1440 OE = BonusInst->op_end(); OI != OE; ++OI) {
1441 Value* V = *OI;
1442 if (!isa<Constant>(V))
1443 UsedValues.insert(V);
1444 }
1445
1446 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1447 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1448
1449 // Walk up to four levels back up the use-def chain of the predecessor's
1450 // terminator to see if all those values were used. The choice of four
1451 // levels is arbitrary, to provide a compile-time-cost bound.
1452 while (!Worklist.empty()) {
1453 std::pair<Value*, unsigned> Pair = Worklist.back();
1454 Worklist.pop_back();
1455
1456 if (Pair.second >= 4) continue;
1457 UsedValues.erase(Pair.first);
1458 if (UsedValues.empty()) break;
1459
1460 if (Instruction* I = dyn_cast<Instruction>(Pair.first)) {
1461 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1462 OI != OE; ++OI)
1463 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1464 }
1465 }
1466
1467 if (!UsedValues.empty()) return false;
1468 }
1469
Chris Lattner36989092008-07-13 21:20:19 +00001470 Instruction::BinaryOps Opc;
1471 bool InvertPredCond = false;
1472
1473 if (PBI->getSuccessor(0) == TrueDest)
1474 Opc = Instruction::Or;
1475 else if (PBI->getSuccessor(1) == FalseDest)
1476 Opc = Instruction::And;
1477 else if (PBI->getSuccessor(0) == FalseDest)
1478 Opc = Instruction::And, InvertPredCond = true;
1479 else if (PBI->getSuccessor(1) == TrueDest)
1480 Opc = Instruction::Or, InvertPredCond = true;
1481 else
1482 continue;
1483
David Greene89d6fd32010-01-05 01:26:52 +00001484 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Chris Lattner6ff645b2009-01-19 23:03:13 +00001485
Chris Lattner36989092008-07-13 21:20:19 +00001486 // If we need to invert the condition in the pred block to match, do so now.
1487 if (InvertPredCond) {
Chris Lattner1347e872008-07-13 21:12:01 +00001488 Value *NewCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00001489 BinaryOperator::CreateNot(PBI->getCondition(),
Chris Lattner36989092008-07-13 21:20:19 +00001490 PBI->getCondition()->getName()+".not", PBI);
Chris Lattner1347e872008-07-13 21:12:01 +00001491 PBI->setCondition(NewCond);
1492 BasicBlock *OldTrue = PBI->getSuccessor(0);
1493 BasicBlock *OldFalse = PBI->getSuccessor(1);
1494 PBI->setSuccessor(0, OldFalse);
1495 PBI->setSuccessor(1, OldTrue);
1496 }
Chris Lattner70087f32008-07-13 21:15:11 +00001497
Owen Andersone84178a2010-07-14 19:52:16 +00001498 // If we have a bonus inst, clone it into the predecessor block.
1499 Instruction *NewBonus = 0;
1500 if (BonusInst) {
1501 NewBonus = BonusInst->clone();
1502 PredBlock->getInstList().insert(PBI, NewBonus);
1503 NewBonus->takeName(BonusInst);
1504 BonusInst->setName(BonusInst->getName()+".old");
1505 }
1506
Chris Lattner36989092008-07-13 21:20:19 +00001507 // Clone Cond into the predecessor basic block, and or/and the
1508 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00001509 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00001510 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00001511 PredBlock->getInstList().insert(PBI, New);
1512 New->takeName(Cond);
1513 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001514
Chris Lattner36989092008-07-13 21:20:19 +00001515 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1516 New, "or.cond", PBI);
1517 PBI->setCondition(NewCond);
1518 if (PBI->getSuccessor(0) == BB) {
1519 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1520 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001521 }
Chris Lattner36989092008-07-13 21:20:19 +00001522 if (PBI->getSuccessor(1) == BB) {
1523 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1524 PBI->setSuccessor(1, FalseDest);
1525 }
1526 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001527 }
1528 return false;
1529}
1530
Chris Lattner867661a2008-07-13 21:53:26 +00001531/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1532/// predecessor of another block, this function tries to simplify it. We know
1533/// that PBI and BI are both conditional branches, and BI is in one of the
1534/// successor blocks of PBI - PBI branches to BI.
1535static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1536 assert(PBI->isConditional() && BI->isConditional());
1537 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00001538
Chris Lattner867661a2008-07-13 21:53:26 +00001539 // If this block ends with a branch instruction, and if there is a
1540 // predecessor that ends on a branch of the same condition, make
1541 // this conditional branch redundant.
1542 if (PBI->getCondition() == BI->getCondition() &&
1543 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1544 // Okay, the outcome of this conditional branch is statically
1545 // knowable. If this block had a single pred, handle specially.
1546 if (BB->getSinglePredecessor()) {
1547 // Turn this into a branch on constant.
1548 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001549 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1550 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001551 return true; // Nuke the branch on constant.
1552 }
1553
1554 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1555 // in the constant and simplify the block result. Subsequent passes of
1556 // simplifycfg will thread the block.
1557 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001558 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Chris Lattner867661a2008-07-13 21:53:26 +00001559 BI->getCondition()->getName() + ".pr",
1560 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001561 // Okay, we're going to insert the PHI node. Since PBI is not the only
1562 // predecessor, compute the PHI'd conditional value for all of the preds.
1563 // Any predecessor where the condition is not computable we keep symbolic.
Gabor Greif62539832010-07-12 10:59:23 +00001564 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1565 BasicBlock *P = *PI;
1566 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00001567 PBI != BI && PBI->isConditional() &&
1568 PBI->getCondition() == BI->getCondition() &&
1569 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1570 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001571 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00001572 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001573 } else {
Gabor Greif62539832010-07-12 10:59:23 +00001574 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001575 }
Gabor Greif62539832010-07-12 10:59:23 +00001576 }
Chris Lattner867661a2008-07-13 21:53:26 +00001577
1578 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001579 return true;
1580 }
1581 }
1582
1583 // If this is a conditional branch in an empty block, and if any
1584 // predecessors is a conditional branch to one of our destinations,
1585 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001586 BasicBlock::iterator BBI = BB->begin();
1587 // Ignore dbg intrinsics.
1588 while (isa<DbgInfoIntrinsic>(BBI))
1589 ++BBI;
1590 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001591 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001592
1593
1594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1595 if (CE->canTrap())
1596 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001597
1598 int PBIOp, BIOp;
1599 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1600 PBIOp = BIOp = 0;
1601 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1602 PBIOp = 0, BIOp = 1;
1603 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1604 PBIOp = 1, BIOp = 0;
1605 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1606 PBIOp = BIOp = 1;
1607 else
1608 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001609
Chris Lattnerb8245122008-07-13 22:04:41 +00001610 // Check to make sure that the other destination of this branch
1611 // isn't BB itself. If so, this is an infinite loop that will
1612 // keep getting unwound.
1613 if (PBI->getSuccessor(PBIOp) == BB)
1614 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001615
Chris Lattnerb8245122008-07-13 22:04:41 +00001616 // Do not perform this transformation if it would require
1617 // insertion of a large number of select instructions. For targets
1618 // without predication/cmovs, this is a big pessimization.
1619 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001620
Chris Lattnerb8245122008-07-13 22:04:41 +00001621 unsigned NumPhis = 0;
1622 for (BasicBlock::iterator II = CommonDest->begin();
1623 isa<PHINode>(II); ++II, ++NumPhis)
1624 if (NumPhis > 2) // Disable this xform.
1625 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001626
Chris Lattnerb8245122008-07-13 22:04:41 +00001627 // Finally, if everything is ok, fold the branches to logical ops.
1628 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1629
David Greene89d6fd32010-01-05 01:26:52 +00001630 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00001631 << "AND: " << *BI->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001632
Chris Lattner093a4382008-07-13 22:23:11 +00001633
1634 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1635 // branch in it, where one edge (OtherDest) goes back to itself but the other
1636 // exits. We don't *know* that the program avoids the infinite loop
1637 // (even though that seems likely). If we do this xform naively, we'll end up
1638 // recursively unpeeling the loop. Since we know that (after the xform is
1639 // done) that the block *is* infinite if reached, we just make it an obviously
1640 // infinite loop with no cond branch.
1641 if (OtherDest == BB) {
1642 // Insert it at the end of the function, because it's either code,
1643 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001644 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1645 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00001646 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1647 OtherDest = InfLoopBlock;
1648 }
1649
David Greene89d6fd32010-01-05 01:26:52 +00001650 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001651
1652 // BI may have other predecessors. Because of this, we leave
1653 // it alone, but modify PBI.
1654
1655 // Make sure we get to CommonDest on True&True directions.
1656 Value *PBICond = PBI->getCondition();
1657 if (PBIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001658 PBICond = BinaryOperator::CreateNot(PBICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001659 PBICond->getName()+".not",
1660 PBI);
1661 Value *BICond = BI->getCondition();
1662 if (BIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001663 BICond = BinaryOperator::CreateNot(BICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001664 BICond->getName()+".not",
1665 PBI);
1666 // Merge the conditions.
1667 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1668
1669 // Modify PBI to branch on the new condition to the new dests.
1670 PBI->setCondition(Cond);
1671 PBI->setSuccessor(0, CommonDest);
1672 PBI->setSuccessor(1, OtherDest);
1673
1674 // OtherDest may have phi nodes. If so, add an entry from PBI's
1675 // block that are identical to the entries for BI's block.
1676 PHINode *PN;
1677 for (BasicBlock::iterator II = OtherDest->begin();
1678 (PN = dyn_cast<PHINode>(II)); ++II) {
1679 Value *V = PN->getIncomingValueForBlock(BB);
1680 PN->addIncoming(V, PBI->getParent());
1681 }
1682
1683 // We know that the CommonDest already had an edge from PBI to
1684 // it. If it has PHIs though, the PHIs may have different
1685 // entries for BB and PBI's BB. If so, insert a select to make
1686 // them agree.
1687 for (BasicBlock::iterator II = CommonDest->begin();
1688 (PN = dyn_cast<PHINode>(II)); ++II) {
1689 Value *BIV = PN->getIncomingValueForBlock(BB);
1690 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1691 Value *PBIV = PN->getIncomingValue(PBBIdx);
1692 if (BIV != PBIV) {
1693 // Insert a select in PBI to pick the right value.
1694 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1695 PBIV->getName()+".mux", PBI);
1696 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001697 }
1698 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001699
David Greene89d6fd32010-01-05 01:26:52 +00001700 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
1701 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001702
1703 // This basic block is probably dead. We know it has at least
1704 // one fewer predecessor.
1705 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001706}
1707
Frits van Bommel7ac40c32010-12-05 18:29:03 +00001708// SimplifyIndirectBrOnSelect - Replaces
1709// (indirectbr (select cond, blockaddress(@fn, BlockA),
1710// blockaddress(@fn, BlockB)))
1711// with
1712// (br cond, BlockA, BlockB).
1713static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
1714 // Check that both operands of the select are block addresses.
1715 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
1716 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
1717 if (!TBA || !FBA)
1718 return false;
1719
1720 // Extract the actual blocks.
1721 BasicBlock *TrueBB = TBA->getBasicBlock();
1722 BasicBlock *FalseBB = FBA->getBasicBlock();
1723
1724 // Remove any superfluous successor edges from the CFG.
1725 // First, figure out which successors to preserve.
1726 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
1727 // successor.
1728 BasicBlock *KeepEdge1 = TrueBB;
1729 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
1730
1731 // Then remove the rest.
1732 for (unsigned I = 0, E = IBI->getNumSuccessors(); I != E; ++I) {
1733 BasicBlock *Succ = IBI->getSuccessor(I);
1734 // Make sure only to keep exactly one copy of each edge.
1735 if (Succ == KeepEdge1)
1736 KeepEdge1 = 0;
1737 else if (Succ == KeepEdge2)
1738 KeepEdge2 = 0;
1739 else
1740 Succ->removePredecessor(IBI->getParent());
1741 }
1742
1743 // Insert an appropriate new terminator.
1744 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
1745 if (TrueBB == FalseBB)
1746 // We were only looking for one successor, and it was present.
1747 // Create an unconditional branch to it.
1748 BranchInst::Create(TrueBB, IBI);
1749 else
1750 // We found both of the successors we were looking for.
1751 // Create a conditional branch sharing the condition of the select.
1752 BranchInst::Create(TrueBB, FalseBB, SI->getCondition(), IBI);
1753 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
1754 // Neither of the selected blocks were successors, so this
1755 // indirectbr must be unreachable.
1756 new UnreachableInst(IBI->getContext(), IBI);
1757 } else {
1758 // One of the selected values was a successor, but the other wasn't.
1759 // Insert an unconditional branch to the one that was found;
1760 // the edge to the one that wasn't must be unreachable.
1761 if (KeepEdge1 == 0)
1762 // Only TrueBB was found.
1763 BranchInst::Create(TrueBB, IBI);
1764 else
1765 // Only FalseBB was found.
1766 BranchInst::Create(FalseBB, IBI);
1767 }
1768
1769 EraseTerminatorInstAndDCECond(IBI);
1770 return true;
1771}
1772
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00001773bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001774 bool Changed = false;
Duncan Sands5f284752010-10-24 12:23:30 +00001775 Function *Fn = BB->getParent();
Chris Lattner01d1ee32002-05-21 20:50:24 +00001776
Duncan Sands5f284752010-10-24 12:23:30 +00001777 assert(BB && Fn && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00001778 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00001779
Dan Gohmane2c6d132010-08-14 00:29:42 +00001780 // Remove basic blocks that have no predecessors (except the entry block)...
1781 // or that just have themself as a predecessor. These are unreachable.
Duncan Sands5f284752010-10-24 12:23:30 +00001782 if ((pred_begin(BB) == pred_end(BB) && BB != &Fn->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00001783 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00001784 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00001785 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00001786 return true;
1787 }
1788
Chris Lattner694e37f2003-08-17 19:41:53 +00001789 // Check to see if we can constant propagate this terminator instruction
1790 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001791 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00001792
Dan Gohman2c635662009-10-30 22:39:04 +00001793 // Check for and eliminate duplicate PHI nodes in this block.
1794 Changed |= EliminateDuplicatePHINodes(BB);
1795
Dan Gohman882d87d2008-03-11 21:53:06 +00001796 // If there is a trivial two-entry PHI node in this basic block, and we can
1797 // eliminate it, do so now.
1798 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1799 if (PN->getNumIncomingValues() == 2)
1800 Changed |= FoldTwoEntryPHINode(PN);
1801
Chris Lattner19831ec2004-02-16 06:35:48 +00001802 // If this is a returning block with only PHI nodes in it, fold the return
1803 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +00001804 //
1805 // If any predecessor is a conditional branch that just selects among
1806 // different return values, fold the replace the branch/return with a select
1807 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +00001808 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001809 if (BB->getFirstNonPHIOrDbg()->isTerminator()) {
Chris Lattner147af6b2004-04-02 18:13:43 +00001810 // Find predecessors that end with branches.
Chris Lattner82442432008-02-18 07:42:56 +00001811 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1812 SmallVector<BranchInst*, 8> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +00001813 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Gabor Greif58969352010-07-09 15:25:09 +00001814 BasicBlock *P = *PI;
1815 TerminatorInst *PTI = P->getTerminator();
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001816 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001817 if (BI->isUnconditional())
Gabor Greif58969352010-07-09 15:25:09 +00001818 UncondBranchPreds.push_back(P);
Chris Lattner147af6b2004-04-02 18:13:43 +00001819 else
1820 CondBranchPreds.push_back(BI);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001821 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001822 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001823
Chris Lattner19831ec2004-02-16 06:35:48 +00001824 // If we found some, do the transformation!
Bill Wendling1c855032009-03-03 19:25:16 +00001825 if (!UncondBranchPreds.empty()) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001826 while (!UncondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001827 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
David Greene89d6fd32010-01-05 01:26:52 +00001828 DEBUG(dbgs() << "FOLDING: " << *BB
Chris Lattnerbdff5482009-08-23 04:37:46 +00001829 << "INTO UNCOND BRANCH PRED: " << *Pred);
Chris Lattner19831ec2004-02-16 06:35:48 +00001830 Instruction *UncondBranch = Pred->getTerminator();
1831 // Clone the return and add it to the end of the predecessor.
Nick Lewycky67760642009-09-27 07:38:41 +00001832 Instruction *NewRet = RI->clone();
Chris Lattner19831ec2004-02-16 06:35:48 +00001833 Pred->getInstList().push_back(NewRet);
1834
1835 // If the return instruction returns a value, and if the value was a
1836 // PHI node in "BB", propagate the right value into the return.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001837 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
1838 i != e; ++i)
1839 if (PHINode *PN = dyn_cast<PHINode>(*i))
Chris Lattner19831ec2004-02-16 06:35:48 +00001840 if (PN->getParent() == BB)
Gabor Greiff7ea3632008-06-10 22:03:26 +00001841 *i = PN->getIncomingValueForBlock(Pred);
Chris Lattnerffba5822008-04-28 00:19:07 +00001842
Chris Lattner19831ec2004-02-16 06:35:48 +00001843 // Update any PHI nodes in the returning block to realize that we no
1844 // longer branch to them.
1845 BB->removePredecessor(Pred);
1846 Pred->getInstList().erase(UncondBranch);
1847 }
1848
1849 // If we eliminated all predecessors of the block, delete the block now.
1850 if (pred_begin(BB) == pred_end(BB))
1851 // We know there are no successors, so just nuke the block.
Duncan Sands5f284752010-10-24 12:23:30 +00001852 Fn->getBasicBlockList().erase(BB);
Chris Lattner19831ec2004-02-16 06:35:48 +00001853
Chris Lattner19831ec2004-02-16 06:35:48 +00001854 return true;
1855 }
Chris Lattner147af6b2004-04-02 18:13:43 +00001856
1857 // Check out all of the conditional branches going to this return
1858 // instruction. If any of them just select between returns, change the
1859 // branch itself into a select/return pair.
1860 while (!CondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001861 BranchInst *BI = CondBranchPreds.pop_back_val();
Chris Lattner147af6b2004-04-02 18:13:43 +00001862
1863 // Check to see if the non-BB successor is also a return block.
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001864 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
1865 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
1866 SimplifyCondBranchToTwoReturns(BI))
1867 return true;
Chris Lattner147af6b2004-04-02 18:13:43 +00001868 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001869 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001870 } else if (isa<UnwindInst>(BB->begin())) {
Chris Lattnere14ea082004-02-24 05:54:22 +00001871 // Check to see if the first instruction in this block is just an unwind.
1872 // If so, replace any invoke instructions which use this as an exception
Chris Lattner11f15db2009-10-13 18:13:05 +00001873 // destination with call instructions.
Chris Lattnere14ea082004-02-24 05:54:22 +00001874 //
Chris Lattner82442432008-02-18 07:42:56 +00001875 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnere14ea082004-02-24 05:54:22 +00001876 while (!Preds.empty()) {
1877 BasicBlock *Pred = Preds.back();
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001878 InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
1879 if (II && II->getUnwindDest() == BB) {
1880 // Insert a new branch instruction before the invoke, because this
1881 // is now a fall through.
1882 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
1883 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001884
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001885 // Insert the call now.
1886 SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
1887 CallInst *CI = CallInst::Create(II->getCalledValue(),
1888 Args.begin(), Args.end(),
1889 II->getName(), BI);
1890 CI->setCallingConv(II->getCallingConv());
1891 CI->setAttributes(II->getAttributes());
1892 // If the invoke produced a value, the Call now does instead.
1893 II->replaceAllUsesWith(CI);
1894 delete II;
1895 Changed = true;
1896 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001897
Chris Lattnere14ea082004-02-24 05:54:22 +00001898 Preds.pop_back();
1899 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001900
Duncan Sands5f284752010-10-24 12:23:30 +00001901 // If this block is now dead (and isn't the entry block), remove it.
1902 if (pred_begin(BB) == pred_end(BB) && BB != &Fn->getEntryBlock()) {
Chris Lattner8e509dd2004-02-24 16:09:21 +00001903 // We know there are no successors, so just nuke the block.
Duncan Sands5f284752010-10-24 12:23:30 +00001904 Fn->getBasicBlockList().erase(BB);
Chris Lattner8e509dd2004-02-24 16:09:21 +00001905 return true;
1906 }
1907
Chris Lattner623369a2005-02-24 06:17:52 +00001908 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1909 if (isValueEqualityComparison(SI)) {
1910 // If we only have one predecessor, and if it is a branch on this value,
1911 // see if that predecessor totally determines the outcome of this switch.
1912 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1913 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1914 return SimplifyCFG(BB) || 1;
1915
1916 // If the block only contains the switch, see if we can fold the block
1917 // away into any preds.
Zhou Sheng9a7c7432009-02-25 15:34:27 +00001918 BasicBlock::iterator BBI = BB->begin();
1919 // Ignore dbg intrinsics.
1920 while (isa<DbgInfoIntrinsic>(BBI))
1921 ++BBI;
1922 if (SI == &*BBI)
Chris Lattner623369a2005-02-24 06:17:52 +00001923 if (FoldValueComparisonIntoPredecessors(SI))
1924 return SimplifyCFG(BB) || 1;
1925 }
Chris Lattner542f1492004-02-28 21:28:10 +00001926 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001927 if (BI->isUnconditional()) {
Chris Lattnerdcb54ce2010-12-13 01:28:06 +00001928 // If the Terminator is the only non-phi instruction, simplify the block.
1929 Instruction *I = BB->getFirstNonPHIOrDbg();
1930 if (I->isTerminator() && BB != &Fn->getEntryBlock() &&
1931 TryToSimplifyUncondBranchFromEmptyBlock(BB))
1932 return true;
Chris Lattner7e663482005-08-03 00:11:16 +00001933
1934 } else { // Conditional branch
Reid Spencer3ed469c2006-11-02 20:25:50 +00001935 if (isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001936 // If we only have one predecessor, and if it is a branch on this value,
1937 // see if that predecessor totally determines the outcome of this
1938 // switch.
1939 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1940 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
Bill Wendlingc69b4a52010-03-14 10:40:28 +00001941 return SimplifyCFG(BB) | true;
Chris Lattner623369a2005-02-24 06:17:52 +00001942
Chris Lattnere67fa052004-05-01 23:35:43 +00001943 // This block must be empty, except for the setcond inst, if it exists.
Devang Patel556b20a2009-02-04 01:06:11 +00001944 // Ignore dbg intrinsics.
Chris Lattnere67fa052004-05-01 23:35:43 +00001945 BasicBlock::iterator I = BB->begin();
Devang Pateld0a203d2009-02-04 21:39:48 +00001946 // Ignore dbg intrinsics.
Devang Patel556b20a2009-02-04 01:06:11 +00001947 while (isa<DbgInfoIntrinsic>(I))
Devang Pateld0a203d2009-02-04 21:39:48 +00001948 ++I;
1949 if (&*I == BI) {
Chris Lattnere67fa052004-05-01 23:35:43 +00001950 if (FoldValueComparisonIntoPredecessors(BI))
1951 return SimplifyCFG(BB) | true;
Devang Pateld0a203d2009-02-04 21:39:48 +00001952 } else if (&*I == cast<Instruction>(BI->getCondition())){
1953 ++I;
1954 // Ignore dbg intrinsics.
1955 while (isa<DbgInfoIntrinsic>(I))
1956 ++I;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001957 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI))
1958 return SimplifyCFG(BB) | true;
Devang Pateld0a203d2009-02-04 21:39:48 +00001959 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001960 }
Devang Pateld0a203d2009-02-04 21:39:48 +00001961
Chris Lattnereaba3a12005-09-19 23:49:37 +00001962 // If this is a branch on a phi node in the current block, thread control
1963 // through this block if any PHI node entries are constants.
1964 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1965 if (PN->getParent() == BI->getParent())
1966 if (FoldCondBranchOnPHI(BI))
1967 return SimplifyCFG(BB) | true;
Chris Lattnere67fa052004-05-01 23:35:43 +00001968
1969 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1970 // branches to us and one of our successors, fold the setcc into the
1971 // predecessor and use logical operations to pick the right destination.
Chris Lattner1347e872008-07-13 21:12:01 +00001972 if (FoldBranchToCommonDest(BI))
Bill Wendlingc69b4a52010-03-14 10:40:28 +00001973 return SimplifyCFG(BB) | true;
Chris Lattnere67fa052004-05-01 23:35:43 +00001974
Chris Lattner867661a2008-07-13 21:53:26 +00001975
1976 // Scan predecessor blocks for conditional branches.
Chris Lattner2e42e362005-09-20 00:43:16 +00001977 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1978 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner867661a2008-07-13 21:53:26 +00001979 if (PBI != BI && PBI->isConditional())
1980 if (SimplifyCondBranchToCondBranch(PBI, BI))
1981 return SimplifyCFG(BB) | true;
Chris Lattnercd4b7092010-12-13 01:57:34 +00001982
1983
1984 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1985 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1986 // 'setne's and'ed together, collect them.
1987 Value *CompVal = 0;
1988 std::vector<ConstantInt*> Values;
1989 bool TrueWhenEqual = GatherValueComparisons(BI->getCondition(), CompVal,
1990 Values);
1991 if (CompVal) {
1992 // There might be duplicate constants in the list, which the switch
1993 // instruction can't handle, remove them now.
Chris Lattner6d4d21e2010-12-13 02:00:58 +00001994 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
Chris Lattnercd4b7092010-12-13 01:57:34 +00001995 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1996
1997 // Figure out which block is which destination.
1998 BasicBlock *DefaultBB = BI->getSuccessor(1);
1999 BasicBlock *EdgeBB = BI->getSuccessor(0);
2000 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
2001
2002 // Convert pointer to int before we switch.
2003 if (CompVal->getType()->isPointerTy()) {
2004 assert(TD && "Cannot switch on pointer without TargetData");
2005 CompVal = new PtrToIntInst(CompVal,
2006 TD->getIntPtrType(CompVal->getContext()),
2007 "magicptr", BI);
2008 }
2009
2010 // Create the new switch instruction now.
2011 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
2012 Values.size(), BI);
2013
2014 // Add all of the 'cases' to the switch instruction.
2015 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2016 New->addCase(Values[i], EdgeBB);
2017
2018 // We added edges from PI to the EdgeBB. As such, if there were any
2019 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2020 // the number of edges added.
2021 for (BasicBlock::iterator BBI = EdgeBB->begin();
2022 isa<PHINode>(BBI); ++BBI) {
2023 PHINode *PN = cast<PHINode>(BBI);
2024 Value *InVal = PN->getIncomingValueForBlock(BB);
2025 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2026 PN->addIncoming(InVal, BB);
2027 }
2028
2029 // Erase the old branch instruction.
2030 EraseTerminatorInstAndDCECond(BI);
2031 return true;
2032 }
Chris Lattnerd52c2612004-02-24 07:23:58 +00002033 }
Chris Lattner698f96f2004-10-18 04:07:22 +00002034 } else if (isa<UnreachableInst>(BB->getTerminator())) {
2035 // If there are any instructions immediately before the unreachable that can
2036 // be removed, do so.
2037 Instruction *Unreachable = BB->getTerminator();
2038 while (Unreachable != BB->begin()) {
2039 BasicBlock::iterator BBI = Unreachable;
2040 --BBI;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002041 // Do not delete instructions that can have side effects, like calls
2042 // (which may never return) and volatile loads and stores.
Dale Johannesen80b8a622009-03-12 17:42:45 +00002043 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002044
2045 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2046 if (SI->isVolatile())
2047 break;
2048
2049 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2050 if (LI->isVolatile())
2051 break;
2052
Chris Lattner698f96f2004-10-18 04:07:22 +00002053 // Delete this instruction
2054 BB->getInstList().erase(BBI);
2055 Changed = true;
2056 }
2057
2058 // If the unreachable instruction is the first in the block, take a gander
2059 // at all of the predecessors of this instruction, and simplify them.
2060 if (&BB->front() == Unreachable) {
Chris Lattner82442432008-02-18 07:42:56 +00002061 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner698f96f2004-10-18 04:07:22 +00002062 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2063 TerminatorInst *TI = Preds[i]->getTerminator();
2064
2065 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2066 if (BI->isUnconditional()) {
2067 if (BI->getSuccessor(0) == BB) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002068 new UnreachableInst(TI->getContext(), TI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002069 TI->eraseFromParent();
2070 Changed = true;
2071 }
2072 } else {
2073 if (BI->getSuccessor(0) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002074 BranchInst::Create(BI->getSuccessor(1), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002075 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002076 } else if (BI->getSuccessor(1) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002077 BranchInst::Create(BI->getSuccessor(0), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002078 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002079 Changed = true;
2080 }
2081 }
2082 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2083 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2084 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00002085 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00002086 SI->removeCase(i);
2087 --i; --e;
2088 Changed = true;
2089 }
2090 // If the default value is unreachable, figure out the most popular
2091 // destination and make it the default.
2092 if (SI->getSuccessor(0) == BB) {
2093 std::map<BasicBlock*, unsigned> Popularity;
2094 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2095 Popularity[SI->getSuccessor(i)]++;
2096
2097 // Find the most popular block.
2098 unsigned MaxPop = 0;
2099 BasicBlock *MaxBlock = 0;
2100 for (std::map<BasicBlock*, unsigned>::iterator
2101 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2102 if (I->second > MaxPop) {
2103 MaxPop = I->second;
2104 MaxBlock = I->first;
2105 }
2106 }
2107 if (MaxBlock) {
2108 // Make this the new default, allowing us to delete any explicit
2109 // edges to it.
2110 SI->setSuccessor(0, MaxBlock);
2111 Changed = true;
2112
Chris Lattner42eb7522005-05-20 22:19:54 +00002113 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2114 // it.
2115 if (isa<PHINode>(MaxBlock->begin()))
2116 for (unsigned i = 0; i != MaxPop-1; ++i)
2117 MaxBlock->removePredecessor(SI->getParent());
2118
Chris Lattner698f96f2004-10-18 04:07:22 +00002119 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2120 if (SI->getSuccessor(i) == MaxBlock) {
2121 SI->removeCase(i);
2122 --i; --e;
2123 }
2124 }
2125 }
2126 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2127 if (II->getUnwindDest() == BB) {
2128 // Convert the invoke to a call instruction. This would be a good
2129 // place to note that the call does not throw though.
Gabor Greif051a9502008-04-06 20:25:17 +00002130 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattner698f96f2004-10-18 04:07:22 +00002131 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00002132
Chris Lattner698f96f2004-10-18 04:07:22 +00002133 // Insert the call now...
Gabor Greifbd443142010-03-30 19:20:53 +00002134 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Gabor Greif051a9502008-04-06 20:25:17 +00002135 CallInst *CI = CallInst::Create(II->getCalledValue(),
2136 Args.begin(), Args.end(),
2137 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00002138 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00002139 CI->setAttributes(II->getAttributes());
Gabor Greifbd443142010-03-30 19:20:53 +00002140 // If the invoke produced a value, the call does now instead.
Chris Lattner698f96f2004-10-18 04:07:22 +00002141 II->replaceAllUsesWith(CI);
2142 delete II;
2143 Changed = true;
2144 }
2145 }
2146 }
2147
2148 // If this block is now dead, remove it.
Duncan Sands5f284752010-10-24 12:23:30 +00002149 if (pred_begin(BB) == pred_end(BB) && BB != &Fn->getEntryBlock()) {
Chris Lattner698f96f2004-10-18 04:07:22 +00002150 // We know there are no successors, so just nuke the block.
Duncan Sands5f284752010-10-24 12:23:30 +00002151 Fn->getBasicBlockList().erase(BB);
Chris Lattner698f96f2004-10-18 04:07:22 +00002152 return true;
2153 }
2154 }
Dan Gohman7a499432010-08-16 14:41:14 +00002155 } else if (IndirectBrInst *IBI =
2156 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
Dan Gohmane2c6d132010-08-14 00:29:42 +00002157 // Eliminate redundant destinations.
2158 SmallPtrSet<Value *, 8> Succs;
2159 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2160 BasicBlock *Dest = IBI->getDestination(i);
Dan Gohman7a499432010-08-16 14:41:14 +00002161 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
Dan Gohmane2c6d132010-08-14 00:29:42 +00002162 Dest->removePredecessor(BB);
2163 IBI->removeDestination(i);
2164 --i; --e;
2165 Changed = true;
2166 }
2167 }
2168
2169 if (IBI->getNumDestinations() == 0) {
2170 // If the indirectbr has no successors, change it to unreachable.
2171 new UnreachableInst(IBI->getContext(), IBI);
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002172 EraseTerminatorInstAndDCECond(IBI);
Dan Gohmane2c6d132010-08-14 00:29:42 +00002173 Changed = true;
2174 } else if (IBI->getNumDestinations() == 1) {
2175 // If the indirectbr has one successor, change it to a direct branch.
2176 BranchInst::Create(IBI->getDestination(0), IBI);
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002177 EraseTerminatorInstAndDCECond(IBI);
Dan Gohmane2c6d132010-08-14 00:29:42 +00002178 Changed = true;
Frits van Bommel7ac40c32010-12-05 18:29:03 +00002179 } else if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2180 if (SimplifyIndirectBrOnSelect(IBI, SI))
2181 return SimplifyCFG(BB) | true;
Dan Gohmane2c6d132010-08-14 00:29:42 +00002182 }
Chris Lattner19831ec2004-02-16 06:35:48 +00002183 }
2184
Chris Lattner01d1ee32002-05-21 20:50:24 +00002185 // Merge basic blocks into their predecessor if there is only one distinct
2186 // pred, and if there is only one distinct successor of the predecessor, and
2187 // if there are no PHI nodes.
2188 //
Owen Andersoncfa94192008-07-18 17:49:43 +00002189 if (MergeBlockIntoPredecessor(BB))
2190 return true;
2191
2192 // Otherwise, if this block only has a single predecessor, and if that block
2193 // is a conditional branch, see if we can hoist any code from this block up
2194 // into our predecessor.
Chris Lattner2355f942004-02-11 01:17:07 +00002195 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
Dan Gohmane2c6d132010-08-14 00:29:42 +00002196 BasicBlock *OnlyPred = 0;
2197 for (; PI != PE; ++PI) { // Search all predecessors, see if they are all same
2198 if (!OnlyPred)
2199 OnlyPred = *PI;
2200 else if (*PI != OnlyPred) {
Chris Lattner2355f942004-02-11 01:17:07 +00002201 OnlyPred = 0; // There are multiple different predecessors...
2202 break;
2203 }
Dan Gohmane2c6d132010-08-14 00:29:42 +00002204 }
Owen Andersoncfa94192008-07-18 17:49:43 +00002205
Chris Lattner9a2b72a2010-12-13 01:47:07 +00002206 if (OnlyPred) {
2207 BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator());
2208 if (BI && BI->isConditional()) {
2209 // Get the other block.
2210 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
2211 PI = pred_begin(OtherBB);
2212 ++PI;
2213
2214 if (PI == pred_end(OtherBB)) {
2215 // We have a conditional branch to two blocks that are only reachable
2216 // from the condbr. We know that the condbr dominates the two blocks,
2217 // so see if there is any identical code in the "then" and "else"
2218 // blocks. If so, we can hoist it up to the branching block.
2219 Changed |= HoistThenElseCodeToIf(BI);
2220 } else {
2221 BasicBlock* OnlySucc = NULL;
2222 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
2223 SI != SE; ++SI) {
2224 if (!OnlySucc)
2225 OnlySucc = *SI;
2226 else if (*SI != OnlySucc) {
2227 OnlySucc = 0; // There are multiple distinct successors!
2228 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +00002229 }
Chris Lattner76134372004-12-10 17:42:31 +00002230 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002231
Chris Lattner9a2b72a2010-12-13 01:47:07 +00002232 if (OnlySucc == OtherBB) {
2233 // If BB's only successor is the other successor of the predecessor,
2234 // i.e. a triangle, see if we can hoist any code from this block up
2235 // to the "if" block.
2236 Changed |= SpeculativelyExecuteBB(BI, BB);
Chris Lattner0d560082004-02-24 05:38:11 +00002237 }
2238 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +00002239 }
2240 }
2241
Chris Lattner694e37f2003-08-17 19:41:53 +00002242 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002243}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002244
2245/// SimplifyCFG - This function is used to do simplification of a CFG. For
2246/// example, it adjusts branches to branches to eliminate the extra hop, it
2247/// eliminates unreachable basic blocks, and does other "peephole" optimization
2248/// of the CFG. It returns true if a modification was made.
2249///
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002250bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
2251 return SimplifyCFGOpt(TD).run(BB);
2252}