blob: 3968d6e8d3bb10e745b95fb641e7e516bdca1fa9 [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 Lattner302ba6f2010-12-14 06:17:25 +000022#include "llvm/Analysis/InstructionSimplify.h"
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000023#include "llvm/Target/TargetData.h"
Chris Lattnereaba3a12005-09-19 23:49:37 +000024#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dan Gohman2c635662009-10-30 22:39:04 +000025#include "llvm/ADT/DenseMap.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000026#include "llvm/ADT/SmallVector.h"
Chris Lattnerc9951232007-04-02 01:44:59 +000027#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng502a4f52008-06-12 21:15:59 +000028#include "llvm/ADT/Statistic.h"
Chris Lattner6d4d21e2010-12-13 02:00:58 +000029#include "llvm/ADT/STLExtras.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000030#include "llvm/Support/CFG.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000031#include "llvm/Support/CommandLine.h"
Chris Lattnere27db742010-12-17 06:20:15 +000032#include "llvm/Support/ConstantRange.h"
Chris Lattner302ba6f2010-12-14 06:17:25 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000035#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000036#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000037#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000038using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000039
Evan Chengc3f507f2011-01-29 04:46:23 +000040static cl::opt<bool>
41DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
42 cl::desc("Duplicate return instructions into unconditional branches"));
43
Evan Cheng502a4f52008-06-12 21:15:59 +000044STATISTIC(NumSpeculations, "Number of speculative executed instructions");
45
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000046namespace {
47class SimplifyCFGOpt {
48 const TargetData *const TD;
49
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000050 Value *isValueEqualityComparison(TerminatorInst *TI);
51 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
52 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
53 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
54 BasicBlock *Pred);
55 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI);
56
Chris Lattner3d512132010-12-13 06:25:44 +000057 bool SimplifyReturn(ReturnInst *RI);
58 bool SimplifyUnwind(UnwindInst *UI);
59 bool SimplifyUnreachable(UnreachableInst *UI);
60 bool SimplifySwitch(SwitchInst *SI);
61 bool SimplifyIndirectBr(IndirectBrInst *IBI);
62 bool SimplifyUncondBranch(BranchInst *BI);
63 bool SimplifyCondBranch(BranchInst *BI);
64
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000065public:
66 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
67 bool run(BasicBlock *BB);
68};
69}
70
Chris Lattner2bdcb562005-08-03 00:19:45 +000071/// SafeToMergeTerminators - Return true if it is safe to merge these two
72/// terminator instructions together.
73///
74static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
75 if (SI1 == SI2) return false; // Can't merge with self!
76
77 // It is not safe to merge these two switch instructions if they have a common
78 // successor, and if that successor has a PHI node, and if *that* PHI node has
79 // conflicting incoming values from the two switch blocks.
80 BasicBlock *SI1BB = SI1->getParent();
81 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000082 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000083
84 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
85 if (SI1Succs.count(*I))
86 for (BasicBlock::iterator BBI = (*I)->begin();
87 isa<PHINode>(BBI); ++BBI) {
88 PHINode *PN = cast<PHINode>(BBI);
89 if (PN->getIncomingValueForBlock(SI1BB) !=
90 PN->getIncomingValueForBlock(SI2BB))
91 return false;
92 }
93
94 return true;
95}
96
97/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
98/// now be entries in it from the 'NewPred' block. The values that will be
99/// flowing into the PHI nodes will be the same as those coming in from
100/// ExistPred, an existing predecessor of Succ.
101static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
102 BasicBlock *ExistPred) {
Chris Lattner2bdcb562005-08-03 00:19:45 +0000103 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
104
Chris Lattner093a4382008-07-13 22:23:11 +0000105 PHINode *PN;
106 for (BasicBlock::iterator I = Succ->begin();
107 (PN = dyn_cast<PHINode>(I)); ++I)
108 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000109}
110
Chris Lattner7e663482005-08-03 00:11:16 +0000111
Chris Lattner73c50a62010-12-14 07:00:00 +0000112/// GetIfCondition - Given a basic block (BB) with two predecessors (and at
113/// least one PHI node in it), check to see if the merge at this block is due
Chris Lattner723c66d2004-02-11 03:36:04 +0000114/// to an "if condition". If so, return the boolean condition that determines
115/// which entry into BB will be taken. Also, return by references the block
116/// that will be entered from if the condition is true, and the block that will
117/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000118///
Chris Lattner995ba1b2010-12-14 07:15:21 +0000119/// This does no checking to see if the true/false blocks have large or unsavory
120/// instructions in them.
Chris Lattner73c50a62010-12-14 07:00:00 +0000121static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
122 BasicBlock *&IfFalse) {
123 PHINode *SomePHI = cast<PHINode>(BB->begin());
124 assert(SomePHI->getNumIncomingValues() == 2 &&
Chris Lattner723c66d2004-02-11 03:36:04 +0000125 "Function can only handle blocks with 2 predecessors!");
Chris Lattner73c50a62010-12-14 07:00:00 +0000126 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
127 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
Chris Lattner723c66d2004-02-11 03:36:04 +0000128
129 // We can only handle branches. Other control flow will be lowered to
130 // branches if possible anyway.
Chris Lattner995ba1b2010-12-14 07:15:21 +0000131 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
132 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
133 if (Pred1Br == 0 || Pred2Br == 0)
Chris Lattner723c66d2004-02-11 03:36:04 +0000134 return 0;
Chris Lattner723c66d2004-02-11 03:36:04 +0000135
136 // Eliminate code duplication by ensuring that Pred1Br is conditional if
137 // either are.
138 if (Pred2Br->isConditional()) {
139 // If both branches are conditional, we don't have an "if statement". In
140 // reality, we could transform this case, but since the condition will be
141 // required anyway, we stand no chance of eliminating it, so the xform is
142 // probably not profitable.
143 if (Pred1Br->isConditional())
144 return 0;
145
146 std::swap(Pred1, Pred2);
147 std::swap(Pred1Br, Pred2Br);
148 }
149
150 if (Pred1Br->isConditional()) {
Chris Lattner995ba1b2010-12-14 07:15:21 +0000151 // The only thing we have to watch out for here is to make sure that Pred2
152 // doesn't have incoming edges from other blocks. If it does, the condition
153 // doesn't dominate BB.
154 if (Pred2->getSinglePredecessor() == 0)
155 return 0;
156
Chris Lattner723c66d2004-02-11 03:36:04 +0000157 // If we found a conditional branch predecessor, make sure that it branches
158 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
159 if (Pred1Br->getSuccessor(0) == BB &&
160 Pred1Br->getSuccessor(1) == Pred2) {
161 IfTrue = Pred1;
162 IfFalse = Pred2;
163 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
164 Pred1Br->getSuccessor(1) == BB) {
165 IfTrue = Pred2;
166 IfFalse = Pred1;
167 } else {
168 // We know that one arm of the conditional goes to BB, so the other must
169 // go somewhere unrelated, and this must not be an "if statement".
170 return 0;
171 }
172
Chris Lattner723c66d2004-02-11 03:36:04 +0000173 return Pred1Br->getCondition();
174 }
175
176 // Ok, if we got here, both predecessors end with an unconditional branch to
177 // BB. Don't panic! If both blocks only have a single (identical)
178 // predecessor, and THAT is a conditional branch, then we're all ok!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000179 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
180 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
Chris Lattner723c66d2004-02-11 03:36:04 +0000181 return 0;
182
183 // Otherwise, if this is a conditional branch, then we can use it!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000184 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
185 if (BI == 0) return 0;
186
187 assert(BI->isConditional() && "Two successors but not conditional?");
188 if (BI->getSuccessor(0) == Pred1) {
189 IfTrue = Pred1;
190 IfFalse = Pred2;
191 } else {
192 IfTrue = Pred2;
193 IfFalse = Pred1;
Chris Lattner723c66d2004-02-11 03:36:04 +0000194 }
Chris Lattner995ba1b2010-12-14 07:15:21 +0000195 return BI->getCondition();
Chris Lattner723c66d2004-02-11 03:36:04 +0000196}
197
Bill Wendling5049fa62009-01-19 23:43:56 +0000198/// DominatesMergePoint - If we have a merge point of an "if condition" as
199/// accepted above, return true if the specified value dominates the block. We
200/// don't handle the true generality of domination here, just a special case
201/// which works well enough for us.
202///
203/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
204/// see if V (which must be an instruction) is cheap to compute and is
205/// non-trapping. If both are true, the instruction is inserted into the set
206/// and true is returned.
Chris Lattner9c078662004-10-14 05:13:36 +0000207static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Chris Lattner44da7ca2010-12-14 07:41:39 +0000208 SmallPtrSet<Instruction*, 4> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000209 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000210 if (!I) {
211 // Non-instructions all dominate instructions, but not all constantexprs
212 // can be executed unconditionally.
213 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
214 if (C->canTrap())
215 return false;
216 return true;
217 }
Chris Lattner570751c2004-04-09 22:50:22 +0000218 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000219
Chris Lattnerda895d62005-02-27 06:18:25 +0000220 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000221 // the bottom of this block.
222 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000223
Chris Lattner570751c2004-04-09 22:50:22 +0000224 // If this instruction is defined in a block that contains an unconditional
225 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner44da7ca2010-12-14 07:41:39 +0000226 // statement". If not, it definitely dominates the region.
227 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
228 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
229 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +0000230
Chris Lattner44da7ca2010-12-14 07:41:39 +0000231 // If we aren't allowing aggressive promotion anymore, then don't consider
232 // instructions in the 'if region'.
233 if (AggressiveInsts == 0) return false;
234
235 // Okay, it looks like the instruction IS in the "condition". Check to
236 // see if it's a cheap instruction to unconditionally compute, and if it
237 // only uses stuff defined outside of the condition. If so, hoist it out.
238 if (!I->isSafeToSpeculativelyExecute())
239 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000240
Chris Lattner44da7ca2010-12-14 07:41:39 +0000241 switch (I->getOpcode()) {
242 default: return false; // Cannot hoist this out safely.
243 case Instruction::Load:
244 // We have to check to make sure there are no instructions before the
245 // load in its basic block, as we are going to hoist the load out to its
246 // predecessor.
247 if (PBB->getFirstNonPHIOrDbg() != I)
248 return false;
249 break;
Benjamin Kramer9ae59e32011-02-24 23:26:09 +0000250 case Instruction::GetElementPtr: {
251 // GEPs are cheap if all indices are constant or if there's only one index.
252 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
253 if (!GEP->hasAllConstantIndices() && GEP->getNumIndices() > 1)
Benjamin Kramer9b61c552011-02-24 22:46:11 +0000254 return false;
255 break;
Benjamin Kramer9ae59e32011-02-24 23:26:09 +0000256 }
Chris Lattner44da7ca2010-12-14 07:41:39 +0000257 case Instruction::Add:
258 case Instruction::Sub:
259 case Instruction::And:
260 case Instruction::Or:
261 case Instruction::Xor:
262 case Instruction::Shl:
263 case Instruction::LShr:
264 case Instruction::AShr:
265 case Instruction::ICmp:
266 break; // These are all cheap and non-trapping instructions.
267 }
Chris Lattner570751c2004-04-09 22:50:22 +0000268
Chris Lattner44da7ca2010-12-14 07:41:39 +0000269 // Okay, we can only really hoist these out if their operands are not
270 // defined in the conditional region.
271 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
272 if (!DominatesMergePoint(*i, BB, 0))
273 return false;
274 // Okay, it's safe to do this! Remember this instruction.
275 AggressiveInsts->insert(I);
Chris Lattner723c66d2004-02-11 03:36:04 +0000276 return true;
277}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000278
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000279/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
280/// and PointerNullValue. Return NULL if value is not a constant int.
Chris Lattner28acc132010-12-13 03:30:12 +0000281static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000282 // Normal constant int.
283 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000284 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000285 return CI;
286
287 // This is some kind of pointer constant. Turn it into a pointer-sized
288 // ConstantInt if possible.
289 const IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
290
291 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
292 if (isa<ConstantPointerNull>(V))
293 return ConstantInt::get(PtrTy, 0);
294
295 // IntToPtr const int.
296 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
297 if (CE->getOpcode() == Instruction::IntToPtr)
298 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
299 // The constant is very likely to have the right type already.
300 if (CI->getType() == PtrTy)
301 return CI;
302 else
303 return cast<ConstantInt>
304 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
305 }
306 return 0;
307}
308
Chris Lattner0aa749b2010-12-13 04:26:26 +0000309/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
310/// collection of icmp eq/ne instructions that compare a value against a
311/// constant, return the value being compared, and stick the constant into the
312/// Values vector.
Chris Lattner28acc132010-12-13 03:30:12 +0000313static Value *
Chris Lattner0aa749b2010-12-13 04:26:26 +0000314GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000315 const TargetData *TD, bool isEQ, unsigned &UsedICmps) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000316 Instruction *I = dyn_cast<Instruction>(V);
317 if (I == 0) return 0;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000318
Chris Lattner7312a222010-12-13 04:50:38 +0000319 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000320 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Chris Lattnere27db742010-12-17 06:20:15 +0000321 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
322 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000323 UsedICmps++;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000324 Vals.push_back(C);
325 return I->getOperand(0);
326 }
Chris Lattnere27db742010-12-17 06:20:15 +0000327
328 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
329 // the set.
330 ConstantRange Span =
Chris Lattnera37029c2010-12-18 20:22:49 +0000331 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Chris Lattnere27db742010-12-17 06:20:15 +0000332
333 // If this is an and/!= check then we want to optimize "x ugt 2" into
334 // x != 0 && x != 1.
335 if (!isEQ)
336 Span = Span.inverse();
337
338 // If there are a ton of values, we don't want to make a ginormous switch.
Benjamin Kramer14c09872010-12-17 10:48:14 +0000339 if (Span.getSetSize().ugt(8) || Span.isEmptySet() ||
Chris Lattnere27db742010-12-17 06:20:15 +0000340 // We don't handle wrapped sets yet.
341 Span.isWrappedSet())
342 return 0;
343
344 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
345 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000346 UsedICmps++;
Chris Lattnere27db742010-12-17 06:20:15 +0000347 return I->getOperand(0);
348 }
Chris Lattner662269d2010-12-13 04:18:32 +0000349 return 0;
350 }
351
Chris Lattner7312a222010-12-13 04:50:38 +0000352 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000353 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Chris Lattner662269d2010-12-13 04:18:32 +0000354 return 0;
Chris Lattner662269d2010-12-13 04:18:32 +0000355
Chris Lattner7312a222010-12-13 04:50:38 +0000356 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000357 unsigned UsedICmpsBeforeLHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000358 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000359 isEQ, UsedICmps)) {
Chris Lattner7312a222010-12-13 04:50:38 +0000360 unsigned NumVals = Vals.size();
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000361 unsigned UsedICmpsBeforeRHS = UsedICmps;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000362 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000363 isEQ, UsedICmps)) {
Chris Lattner0aa749b2010-12-13 04:26:26 +0000364 if (LHS == RHS)
365 return LHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000366 Vals.resize(NumVals);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000367 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner0aa749b2010-12-13 04:26:26 +0000368 }
Chris Lattner7312a222010-12-13 04:50:38 +0000369
370 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
371 // set it and return success.
372 if (Extra == 0 || Extra == I->getOperand(1)) {
373 Extra = I->getOperand(1);
374 return LHS;
375 }
376
377 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000378 UsedICmps = UsedICmpsBeforeLHS;
Chris Lattner7312a222010-12-13 04:50:38 +0000379 return 0;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000380 }
Chris Lattner7312a222010-12-13 04:50:38 +0000381
382 // If the LHS can't be folded in, but Extra is available and RHS can, try to
383 // use LHS as Extra.
384 if (Extra == 0 || Extra == I->getOperand(0)) {
Chris Lattner92407e52010-12-13 07:41:29 +0000385 Value *OldExtra = Extra;
Chris Lattner7312a222010-12-13 04:50:38 +0000386 Extra = I->getOperand(0);
387 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
Benjamin Kramer33828bc2011-02-07 22:37:28 +0000388 isEQ, UsedICmps))
Chris Lattner7312a222010-12-13 04:50:38 +0000389 return RHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000390 assert(Vals.size() == NumValsBeforeLHS);
391 Extra = OldExtra;
Chris Lattner7312a222010-12-13 04:50:38 +0000392 }
393
Chris Lattner0d560082004-02-24 05:38:11 +0000394 return 0;
395}
Chris Lattner0aa749b2010-12-13 04:26:26 +0000396
Eli Friedman080efb82008-12-16 20:54:32 +0000397static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
398 Instruction* Cond = 0;
399 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
400 Cond = dyn_cast<Instruction>(SI->getCondition());
401 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
402 if (BI->isConditional())
403 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000404 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
405 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000406 }
407
408 TI->eraseFromParent();
409 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
410}
411
Chris Lattner9fd49552008-11-27 23:25:44 +0000412/// isValueEqualityComparison - Return true if the specified terminator checks
413/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000414Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
415 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000416 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
417 // Do not permit merging of large switch instructions into their
418 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000419 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
420 pred_end(SI->getParent())) <= 128)
421 CV = SI->getCondition();
422 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000423 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000424 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
425 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
426 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Chris Lattner28acc132010-12-13 03:30:12 +0000427 GetConstantInt(ICI->getOperand(1), TD))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000428 CV = ICI->getOperand(0);
429
430 // Unwrap any lossless ptrtoint cast.
431 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
432 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
433 CV = PTII->getOperand(0);
434 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000435}
436
Bill Wendling5049fa62009-01-19 23:43:56 +0000437/// GetValueEqualityComparisonCases - Given a value comparison instruction,
438/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000439BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000440GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000441 std::vector<std::pair<ConstantInt*,
442 BasicBlock*> > &Cases) {
443 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
444 Cases.reserve(SI->getNumCases());
445 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000446 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000447 return SI->getDefaultDest();
448 }
449
450 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000451 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Chris Lattner28acc132010-12-13 03:30:12 +0000452 Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000453 BI->getSuccessor(ICI->getPredicate() ==
454 ICmpInst::ICMP_NE)));
455 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000456}
457
458
Bill Wendling5049fa62009-01-19 23:43:56 +0000459/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
460/// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000461static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000462 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
463 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
464 if (Cases[i].second == BB) {
465 Cases.erase(Cases.begin()+i);
466 --i; --e;
467 }
468}
469
Bill Wendling5049fa62009-01-19 23:43:56 +0000470/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
471/// well.
Chris Lattner623369a2005-02-24 06:17:52 +0000472static bool
473ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
474 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
475 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
476
477 // Make V1 be smaller than V2.
478 if (V1->size() > V2->size())
479 std::swap(V1, V2);
480
481 if (V1->size() == 0) return false;
482 if (V1->size() == 1) {
483 // Just scan V2.
484 ConstantInt *TheVal = (*V1)[0].first;
485 for (unsigned i = 0, e = V2->size(); i != e; ++i)
486 if (TheVal == (*V2)[i].first)
487 return true;
488 }
489
490 // Otherwise, just sort both lists and compare element by element.
Chris Lattnerfca20f52010-12-13 03:24:30 +0000491 array_pod_sort(V1->begin(), V1->end());
492 array_pod_sort(V2->begin(), V2->end());
Chris Lattner623369a2005-02-24 06:17:52 +0000493 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
494 while (i1 != e1 && i2 != e2) {
495 if ((*V1)[i1].first == (*V2)[i2].first)
496 return true;
497 if ((*V1)[i1].first < (*V2)[i2].first)
498 ++i1;
499 else
500 ++i2;
501 }
502 return false;
503}
504
Bill Wendling5049fa62009-01-19 23:43:56 +0000505/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
506/// terminator instruction and its block is known to only have a single
507/// predecessor block, check to see if that predecessor is also a value
508/// comparison with the same value, and if that comparison determines the
509/// outcome of this comparison. If so, simplify TI. This does a very limited
510/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000511bool SimplifyCFGOpt::
512SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
513 BasicBlock *Pred) {
Chris Lattner623369a2005-02-24 06:17:52 +0000514 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
515 if (!PredVal) return false; // Not a value comparison in predecessor.
516
517 Value *ThisVal = isValueEqualityComparison(TI);
518 assert(ThisVal && "This isn't a value comparison!!");
519 if (ThisVal != PredVal) return false; // Different predicates.
520
521 // Find out information about when control will move from Pred to TI's block.
522 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
523 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
524 PredCases);
525 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000526
Chris Lattner623369a2005-02-24 06:17:52 +0000527 // Find information about how control leaves this block.
528 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
529 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
530 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
531
532 // If TI's block is the default block from Pred's comparison, potentially
533 // simplify TI based on this knowledge.
534 if (PredDef == TI->getParent()) {
535 // If we are here, we know that the value is none of those cases listed in
536 // PredCases. If there are any cases in ThisCases that are in PredCases, we
537 // can simplify TI.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000538 if (!ValuesOverlap(PredCases, ThisCases))
539 return false;
540
541 if (isa<BranchInst>(TI)) {
542 // Okay, one of the successors of this condbr is dead. Convert it to a
543 // uncond br.
544 assert(ThisCases.size() == 1 && "Branch can only have one case!");
545 // Insert the new branch.
546 Instruction *NI = BranchInst::Create(ThisDef, TI);
547 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000548
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000549 // Remove PHI node entries for the dead edge.
550 ThisCases[0].second->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000551
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000552 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
553 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000554
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000555 EraseTerminatorInstAndDCECond(TI);
556 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000557 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000558
559 SwitchInst *SI = cast<SwitchInst>(TI);
560 // Okay, TI has cases that are statically dead, prune them away.
561 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000562 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000563 DeadCases.insert(PredCases[i].first);
Chris Lattner623369a2005-02-24 06:17:52 +0000564
David Greene89d6fd32010-01-05 01:26:52 +0000565 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000566 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000567
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000568 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
569 if (DeadCases.count(SI->getCaseValue(i))) {
570 SI->getSuccessor(i)->removePredecessor(TI->getParent());
571 SI->removeCase(i);
572 }
573
574 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000575 return true;
576 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000577
578 // Otherwise, TI's block must correspond to some matched value. Find out
579 // which value (or set of values) this is.
580 ConstantInt *TIV = 0;
581 BasicBlock *TIBB = TI->getParent();
582 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
583 if (PredCases[i].second == TIBB) {
584 if (TIV != 0)
585 return false; // Cannot handle multiple values coming to this block.
586 TIV = PredCases[i].first;
587 }
588 assert(TIV && "No edge from pred to succ?");
589
590 // Okay, we found the one constant that our value can be if we get into TI's
591 // BB. Find out which successor will unconditionally be branched to.
592 BasicBlock *TheRealDest = 0;
593 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
594 if (ThisCases[i].first == TIV) {
595 TheRealDest = ThisCases[i].second;
596 break;
597 }
598
599 // If not handled by any explicit cases, it is handled by the default case.
600 if (TheRealDest == 0) TheRealDest = ThisDef;
601
602 // Remove PHI node entries for dead edges.
603 BasicBlock *CheckEdge = TheRealDest;
604 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
605 if (*SI != CheckEdge)
606 (*SI)->removePredecessor(TIBB);
607 else
608 CheckEdge = 0;
609
610 // Insert the new branch.
611 Instruction *NI = BranchInst::Create(TheRealDest, TI);
612 (void) NI;
613
614 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
615 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
616
617 EraseTerminatorInstAndDCECond(TI);
618 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000619}
620
Dale Johannesenc81f5442009-03-12 21:01:11 +0000621namespace {
622 /// ConstantIntOrdering - This class implements a stable ordering of constant
623 /// integers that does not depend on their address. This is important for
624 /// applications that sort ConstantInt's to ensure uniqueness.
625 struct ConstantIntOrdering {
626 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
627 return LHS->getValue().ult(RHS->getValue());
628 }
629 };
630}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000631
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000632static int ConstantIntSortPredicate(const void *P1, const void *P2) {
633 const ConstantInt *LHS = *(const ConstantInt**)P1;
634 const ConstantInt *RHS = *(const ConstantInt**)P2;
Chris Lattnerba3c8152010-12-15 04:52:41 +0000635 if (LHS->getValue().ult(RHS->getValue()))
636 return 1;
637 if (LHS->getValue() == RHS->getValue())
638 return 0;
639 return -1;
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000640}
641
Bill Wendling5049fa62009-01-19 23:43:56 +0000642/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
643/// equality comparison instruction (either a switch or a branch on "X == c").
644/// See if any of the predecessors of the terminator block are value comparisons
645/// on the same value. If so, and if safe to do so, fold them together.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000646bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
Chris Lattner542f1492004-02-28 21:28:10 +0000647 BasicBlock *BB = TI->getParent();
648 Value *CV = isValueEqualityComparison(TI); // CondVal
649 assert(CV && "Not a comparison?");
650 bool Changed = false;
651
Chris Lattner82442432008-02-18 07:42:56 +0000652 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000653 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000654 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000655
Chris Lattner542f1492004-02-28 21:28:10 +0000656 // See if the predecessor is a comparison with the same value.
657 TerminatorInst *PTI = Pred->getTerminator();
658 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
659
660 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
661 // Figure out which 'cases' to copy from SI to PSI.
662 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
663 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
664
665 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
666 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
667
668 // Based on whether the default edge from PTI goes to BB or not, fill in
669 // PredCases and PredDefault with the new switch cases we would like to
670 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000671 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000672
673 if (PredDefault == BB) {
674 // If this is the default destination from PTI, only the edges in TI
675 // that don't occur in PTI, or that branch to BB will be activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000676 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000677 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
678 if (PredCases[i].second != BB)
679 PTIHandled.insert(PredCases[i].first);
680 else {
681 // The default destination is BB, we don't need explicit targets.
682 std::swap(PredCases[i], PredCases.back());
683 PredCases.pop_back();
684 --i; --e;
685 }
686
687 // Reconstruct the new switch statement we will be building.
688 if (PredDefault != BBDefault) {
689 PredDefault->removePredecessor(Pred);
690 PredDefault = BBDefault;
691 NewSuccessors.push_back(BBDefault);
692 }
693 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
694 if (!PTIHandled.count(BBCases[i].first) &&
695 BBCases[i].second != BBDefault) {
696 PredCases.push_back(BBCases[i]);
697 NewSuccessors.push_back(BBCases[i].second);
698 }
699
700 } else {
701 // If this is not the default destination from PSI, only the edges
702 // in SI that occur in PSI with a destination of BB will be
703 // activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000704 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000705 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
706 if (PredCases[i].second == BB) {
707 PTIHandled.insert(PredCases[i].first);
708 std::swap(PredCases[i], PredCases.back());
709 PredCases.pop_back();
710 --i; --e;
711 }
712
713 // Okay, now we know which constants were sent to BB from the
714 // predecessor. Figure out where they will all go now.
715 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
716 if (PTIHandled.count(BBCases[i].first)) {
717 // If this is one we are capable of getting...
718 PredCases.push_back(BBCases[i]);
719 NewSuccessors.push_back(BBCases[i].second);
720 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
721 }
722
723 // If there are any constants vectored to BB that TI doesn't handle,
724 // they must go to the default destination of TI.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000725 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
726 PTIHandled.begin(),
Chris Lattner542f1492004-02-28 21:28:10 +0000727 E = PTIHandled.end(); I != E; ++I) {
728 PredCases.push_back(std::make_pair(*I, BBDefault));
729 NewSuccessors.push_back(BBDefault);
730 }
731 }
732
733 // Okay, at this point, we know which new successor Pred will get. Make
734 // sure we update the number of entries in the PHI nodes for these
735 // successors.
736 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
737 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
738
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000739 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000740 if (CV->getType()->isPointerTy()) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000741 assert(TD && "Cannot switch on pointer without TargetData");
742 CV = new PtrToIntInst(CV, TD->getIntPtrType(CV->getContext()),
743 "magicptr", PTI);
744 }
745
Chris Lattner542f1492004-02-28 21:28:10 +0000746 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000747 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
748 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000749 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
750 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000751
Eli Friedman080efb82008-12-16 20:54:32 +0000752 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000753
Chris Lattner542f1492004-02-28 21:28:10 +0000754 // Okay, last check. If BB is still a successor of PSI, then we must
755 // have an infinite loop case. If so, add an infinitely looping block
756 // to handle the case to preserve the behavior of the code.
757 BasicBlock *InfLoopBlock = 0;
758 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
759 if (NewSI->getSuccessor(i) == BB) {
760 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000761 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000762 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +0000763 InfLoopBlock = BasicBlock::Create(BB->getContext(),
764 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +0000765 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000766 }
767 NewSI->setSuccessor(i, InfLoopBlock);
768 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000769
Chris Lattner542f1492004-02-28 21:28:10 +0000770 Changed = true;
771 }
772 }
773 return Changed;
774}
775
Dale Johannesenc1f10402009-06-15 20:59:27 +0000776// isSafeToHoistInvoke - If we would need to insert a select that uses the
777// value of this invoke (comments in HoistThenElseCodeToIf explain why we
778// would need to do this), we can't hoist the invoke, as there is nowhere
779// to put the select in this case.
780static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
781 Instruction *I1, Instruction *I2) {
782 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
783 PHINode *PN;
784 for (BasicBlock::iterator BBI = SI->begin();
785 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
786 Value *BB1V = PN->getIncomingValueForBlock(BB1);
787 Value *BB2V = PN->getIncomingValueForBlock(BB2);
788 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
789 return false;
790 }
791 }
792 }
793 return true;
794}
795
Chris Lattner6306d072005-08-03 17:59:45 +0000796/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000797/// BB2, hoist any common code in the two blocks up into the branch block. The
798/// caller of this function guarantees that BI's block dominates BB1 and BB2.
799static bool HoistThenElseCodeToIf(BranchInst *BI) {
800 // This does very trivial matching, with limited scanning, to find identical
801 // instructions in the two blocks. In particular, we don't want to get into
802 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
803 // such, we currently just scan for obviously identical instructions in an
804 // identical order.
805 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
806 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
807
Devang Patel65085cf2009-02-04 00:03:08 +0000808 BasicBlock::iterator BB1_Itr = BB1->begin();
809 BasicBlock::iterator BB2_Itr = BB2->begin();
810
811 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
812 while (isa<DbgInfoIntrinsic>(I1))
813 I1 = BB1_Itr++;
814 while (isa<DbgInfoIntrinsic>(I2))
815 I2 = BB2_Itr++;
Dale Johannesenc1f10402009-06-15 20:59:27 +0000816 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000817 !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +0000818 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000819 return false;
820
821 // If we get here, we can hoist at least one instruction.
822 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000823
824 do {
825 // If we are hoisting the terminator instruction, don't move one (making a
826 // broken BB), instead clone it, and remove BI.
827 if (isa<TerminatorInst>(I1))
828 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000829
Chris Lattner37dc9382004-11-30 00:29:14 +0000830 // For a normal instruction, we just move one to right before the branch,
831 // then replace all uses of the other with the first. Finally, we remove
832 // the now redundant second instruction.
833 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
834 if (!I2->use_empty())
835 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000836 I1->intersectOptionalDataWith(I2);
Chris Lattner302ba6f2010-12-14 06:17:25 +0000837 I2->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000838
Devang Patel65085cf2009-02-04 00:03:08 +0000839 I1 = BB1_Itr++;
840 while (isa<DbgInfoIntrinsic>(I1))
841 I1 = BB1_Itr++;
842 I2 = BB2_Itr++;
843 while (isa<DbgInfoIntrinsic>(I2))
844 I2 = BB2_Itr++;
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000845 } while (I1->getOpcode() == I2->getOpcode() &&
846 I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +0000847
848 return true;
849
850HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000851 // It may not be possible to hoist an invoke.
852 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
853 return true;
854
Chris Lattner37dc9382004-11-30 00:29:14 +0000855 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +0000856 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +0000857 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +0000858 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000859 I1->replaceAllUsesWith(NT);
860 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000861 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000862 }
863
864 // Hoisting one of the terminators from our successor is a great thing.
865 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
866 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
867 // nodes, so we insert select instruction to compute the final result.
868 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
869 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
870 PHINode *PN;
871 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000872 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000873 Value *BB1V = PN->getIncomingValueForBlock(BB1);
874 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000875 if (BB1V == BB2V) continue;
876
877 // These values do not agree. Insert a select instruction before NT
878 // that determines the right value.
879 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
880 if (SI == 0)
881 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
882 BB1V->getName()+"."+BB2V->getName(), NT);
883 // Make the PHI node use the select for all incoming values for BB1/BB2
884 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
885 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
886 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000887 }
888 }
889
890 // Update any PHI nodes in our new successors.
891 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
892 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000893
Eli Friedman080efb82008-12-16 20:54:32 +0000894 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000895 return true;
896}
897
Evan Cheng4d09efd2008-06-07 08:52:29 +0000898/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
899/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
900/// (for now, restricted to a single instruction that's side effect free) from
901/// the BB1 into the branch block to speculatively execute it.
902static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
903 // Only speculatively execution a single instruction (not counting the
904 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000905 Instruction *HInst = NULL;
906 Instruction *Term = BB1->getTerminator();
907 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
908 BBI != BBE; ++BBI) {
909 Instruction *I = BBI;
910 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000911 if (isa<DbgInfoIntrinsic>(I)) continue;
912 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +0000913
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000914 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +0000915 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000916 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +0000917 }
918 if (!HInst)
919 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000920
Evan Cheng797d9512008-06-11 19:18:20 +0000921 // Be conservative for now. FP select instruction can often be expensive.
922 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000923 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +0000924 return false;
925
Evan Cheng4d09efd2008-06-07 08:52:29 +0000926 // If BB1 is actually on the false edge of the conditional branch, remember
927 // to swap the select operands later.
928 bool Invert = false;
929 if (BB1 != BI->getSuccessor(0)) {
930 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
931 Invert = true;
932 }
933
934 // Turn
935 // BB:
936 // %t1 = icmp
937 // br i1 %t1, label %BB1, label %BB2
938 // BB1:
939 // %t3 = add %t2, c
940 // br label BB2
941 // BB2:
942 // =>
943 // BB:
944 // %t1 = icmp
945 // %t4 = add %t2, c
946 // %t3 = select i1 %t1, %t2, %t3
Devang Patel06b1e672009-03-06 06:00:17 +0000947 switch (HInst->getOpcode()) {
Evan Cheng4d09efd2008-06-07 08:52:29 +0000948 default: return false; // Not safe / profitable to hoist.
949 case Instruction::Add:
950 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000951 // Not worth doing for vector ops.
Duncan Sands1df98592010-02-16 11:11:14 +0000952 if (HInst->getType()->isVectorTy())
Chris Lattner9dd3b612009-01-18 23:22:07 +0000953 return false;
954 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000955 case Instruction::And:
956 case Instruction::Or:
957 case Instruction::Xor:
958 case Instruction::Shl:
959 case Instruction::LShr:
960 case Instruction::AShr:
Chris Lattner9dd3b612009-01-18 23:22:07 +0000961 // Don't mess with vector operations.
Duncan Sands1df98592010-02-16 11:11:14 +0000962 if (HInst->getType()->isVectorTy())
Evan Chenge5334ea2008-06-25 07:50:12 +0000963 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000964 break; // These are all cheap and non-trapping instructions.
965 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000966
967 // If the instruction is obviously dead, don't try to predicate it.
Devang Patel06b1e672009-03-06 06:00:17 +0000968 if (HInst->use_empty()) {
969 HInst->eraseFromParent();
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000970 return true;
971 }
Evan Cheng4d09efd2008-06-07 08:52:29 +0000972
973 // Can we speculatively execute the instruction? And what is the value
974 // if the condition is false? Consider the phi uses, if the incoming value
975 // from the "if" block are all the same V, then V is the value of the
976 // select if the condition is false.
977 BasicBlock *BIParent = BI->getParent();
978 SmallVector<PHINode*, 4> PHIUses;
979 Value *FalseV = NULL;
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000980
981 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Devang Patel06b1e672009-03-06 06:00:17 +0000982 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
Evan Cheng4d09efd2008-06-07 08:52:29 +0000983 UI != E; ++UI) {
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000984 // Ignore any user that is not a PHI node in BB2. These can only occur in
985 // unreachable blocks, because they would not be dominated by the instr.
Gabor Greif20361b92010-07-22 11:43:44 +0000986 PHINode *PN = dyn_cast<PHINode>(*UI);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000987 if (!PN || PN->getParent() != BB2)
988 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000989 PHIUses.push_back(PN);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000990
Evan Cheng4d09efd2008-06-07 08:52:29 +0000991 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
992 if (!FalseV)
993 FalseV = PHIV;
994 else if (FalseV != PHIV)
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000995 return false; // Inconsistent value when condition is false.
Evan Cheng4d09efd2008-06-07 08:52:29 +0000996 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000997
998 assert(FalseV && "Must have at least one user, and it must be a PHI");
Evan Cheng4d09efd2008-06-07 08:52:29 +0000999
Evan Cheng502a4f52008-06-12 21:15:59 +00001000 // Do not hoist the instruction if any of its operands are defined but not
1001 // used in this BB. The transformation will prevent the operand from
1002 // being sunk into the use block.
Devang Patel06b1e672009-03-06 06:00:17 +00001003 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
1004 i != e; ++i) {
Evan Cheng502a4f52008-06-12 21:15:59 +00001005 Instruction *OpI = dyn_cast<Instruction>(*i);
1006 if (OpI && OpI->getParent() == BIParent &&
1007 !OpI->isUsedInBasicBlock(BIParent))
1008 return false;
1009 }
1010
Devang Patel3d0a9a32008-09-18 22:50:42 +00001011 // If we get here, we can hoist the instruction. Try to place it
Dale Johannesen990afed2009-03-13 01:05:24 +00001012 // before the icmp instruction preceding the conditional branch.
Devang Patel3d0a9a32008-09-18 22:50:42 +00001013 BasicBlock::iterator InsertPos = BI;
Dale Johannesen990afed2009-03-13 01:05:24 +00001014 if (InsertPos != BIParent->begin())
1015 --InsertPos;
1016 // Skip debug info between condition and branch.
1017 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
Devang Patel3d0a9a32008-09-18 22:50:42 +00001018 --InsertPos;
Devang Patel20da1f02008-10-03 18:57:37 +00001019 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
Devang Patel3d0a9a32008-09-18 22:50:42 +00001020 SmallPtrSet<Instruction *, 4> BB1Insns;
1021 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
1022 BB1I != BB1E; ++BB1I)
1023 BB1Insns.insert(BB1I);
1024 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1025 UI != UE; ++UI) {
1026 Instruction *Use = cast<Instruction>(*UI);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001027 if (!BB1Insns.count(Use)) continue;
1028
1029 // If BrCond uses the instruction that place it just before
1030 // branch instruction.
1031 InsertPos = BI;
1032 break;
Devang Patel3d0a9a32008-09-18 22:50:42 +00001033 }
1034 } else
1035 InsertPos = BI;
Devang Patel06b1e672009-03-06 06:00:17 +00001036 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001037
1038 // Create a select whose true value is the speculatively executed value and
1039 // false value is the previously determined FalseV.
1040 SelectInst *SI;
1041 if (Invert)
Devang Patel06b1e672009-03-06 06:00:17 +00001042 SI = SelectInst::Create(BrCond, FalseV, HInst,
1043 FalseV->getName() + "." + HInst->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001044 else
Devang Patel06b1e672009-03-06 06:00:17 +00001045 SI = SelectInst::Create(BrCond, HInst, FalseV,
1046 HInst->getName() + "." + FalseV->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001047
1048 // Make the PHI node use the select for all incoming values for "then" and
1049 // "if" blocks.
1050 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1051 PHINode *PN = PHIUses[i];
1052 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001053 if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
Evan Cheng4d09efd2008-06-07 08:52:29 +00001054 PN->setIncomingValue(j, SI);
1055 }
1056
Evan Cheng502a4f52008-06-12 21:15:59 +00001057 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001058 return true;
1059}
1060
Chris Lattner2e42e362005-09-20 00:43:16 +00001061/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1062/// across this block.
1063static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1064 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001065 unsigned Size = 0;
1066
Devang Patel9200c892009-03-10 18:00:05 +00001067 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001068 if (isa<DbgInfoIntrinsic>(BBI))
1069 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001070 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001071 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001072
Dale Johannesen8483e542009-03-12 23:18:09 +00001073 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001074 // live outside of the current basic block.
1075 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1076 UI != E; ++UI) {
1077 Instruction *U = cast<Instruction>(*UI);
1078 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1079 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001080
1081 // Looks ok, continue checking.
1082 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001083
Chris Lattner2e42e362005-09-20 00:43:16 +00001084 return true;
1085}
1086
Chris Lattnereaba3a12005-09-19 23:49:37 +00001087/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1088/// that is defined in the same block as the branch and if any PHI entries are
1089/// constants, thread edges corresponding to that entry to be branches to their
1090/// ultimate destination.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001091static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001092 BasicBlock *BB = BI->getParent();
1093 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001094 // NOTE: we currently cannot transform this case if the PHI node is used
1095 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001096 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1097 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001098
1099 // Degenerate case of a single entry PHI.
1100 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001101 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001102 return true;
1103 }
1104
1105 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001106 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001107
1108 // Okay, this is a simple enough basic block. See if any phi values are
1109 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001110 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001111 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1112 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1113
1114 // Okay, we now know that all edges from PredBB should be revectored to
1115 // branch to RealDest.
1116 BasicBlock *PredBB = PN->getIncomingBlock(i);
1117 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1118
1119 if (RealDest == BB) continue; // Skip self loops.
1120
1121 // The dest block might have PHI nodes, other predecessors and other
1122 // difficult cases. Instead of being smart about this, just insert a new
1123 // block that jumps to the destination block, effectively splitting
1124 // the edge we are about to create.
1125 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1126 RealDest->getName()+".critedge",
1127 RealDest->getParent(), RealDest);
1128 BranchInst::Create(RealDest, EdgeBB);
Chris Lattner6de0a282010-12-14 07:09:42 +00001129
1130 // Update PHI nodes.
1131 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001132
1133 // BB may have instructions that are being threaded over. Clone these
1134 // instructions into EdgeBB. We know that there will be no uses of the
1135 // cloned instructions outside of EdgeBB.
1136 BasicBlock::iterator InsertPt = EdgeBB->begin();
1137 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1138 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1139 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1140 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1141 continue;
1142 }
1143 // Clone the instruction.
1144 Instruction *N = BBI->clone();
1145 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1146
1147 // Update operands due to translation.
1148 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1149 i != e; ++i) {
1150 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1151 if (PI != TranslateMap.end())
1152 *i = PI->second;
1153 }
1154
1155 // Check for trivial simplification.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001156 if (Value *V = SimplifyInstruction(N, TD)) {
1157 TranslateMap[BBI] = V;
1158 delete N; // Instruction folded away, don't need actual inst
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001159 } else {
1160 // Insert the new instruction into its new home.
1161 EdgeBB->getInstList().insert(InsertPt, N);
1162 if (!BBI->use_empty())
1163 TranslateMap[BBI] = N;
1164 }
1165 }
1166
1167 // Loop over all of the edges from PredBB to BB, changing them to branch
1168 // to EdgeBB instead.
1169 TerminatorInst *PredBBTI = PredBB->getTerminator();
1170 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1171 if (PredBBTI->getSuccessor(i) == BB) {
1172 BB->removePredecessor(PredBB);
1173 PredBBTI->setSuccessor(i, EdgeBB);
1174 }
1175
1176 // Recurse, simplifying any other constants.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001177 return FoldCondBranchOnPHI(BI, TD) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001178 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001179
1180 return false;
1181}
1182
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001183/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1184/// PHI node, see if we can eliminate it.
Chris Lattner73c50a62010-12-14 07:00:00 +00001185static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001186 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1187 // statement", which has a very simple dominance structure. Basically, we
1188 // are trying to find the condition that is being branched on, which
1189 // subsequently causes this merge to happen. We really want control
1190 // dependence information for this check, but simplifycfg can't keep it up
1191 // to date, and this catches most of the cases we care about anyway.
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001192 BasicBlock *BB = PN->getParent();
1193 BasicBlock *IfTrue, *IfFalse;
1194 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner60d410d2010-12-14 08:01:53 +00001195 if (!IfCond ||
1196 // Don't bother if the branch will be constant folded trivially.
1197 isa<ConstantInt>(IfCond))
1198 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001199
Chris Lattner822a8792006-11-18 19:19:36 +00001200 // Okay, we found that we can merge this two-entry phi node into a select.
1201 // Doing so would require us to fold *all* two entry phi nodes in this block.
1202 // At some point this becomes non-profitable (particularly if the target
1203 // doesn't support cmov's). Only do this transformation if there are two or
1204 // fewer PHI nodes in this block.
1205 unsigned NumPhis = 0;
1206 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1207 if (NumPhis > 2)
1208 return false;
1209
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001210 // Loop over the PHI's seeing if we can promote them all to select
1211 // instructions. While we are at it, keep track of the instructions
1212 // that need to be moved to the dominating block.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001213 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001214
Chris Lattner3aff13b2010-12-14 08:46:09 +00001215 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1216 PHINode *PN = cast<PHINode>(II++);
Chris Lattner07ff3532010-12-14 07:20:29 +00001217 if (Value *V = SimplifyInstruction(PN, TD)) {
1218 PN->replaceAllUsesWith(V);
Chris Lattner3aff13b2010-12-14 08:46:09 +00001219 PN->eraseFromParent();
Chris Lattner07ff3532010-12-14 07:20:29 +00001220 continue;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001221 }
Chris Lattner07ff3532010-12-14 07:20:29 +00001222
1223 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts) ||
1224 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts))
1225 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001226 }
1227
Chris Lattner44da7ca2010-12-14 07:41:39 +00001228 // If we folded the the first phi, PN dangles at this point. Refresh it. If
1229 // we ran out of PHIs then we simplified them all.
1230 PN = dyn_cast<PHINode>(BB->begin());
1231 if (PN == 0) return true;
1232
Chris Lattner3aff13b2010-12-14 08:46:09 +00001233 // Don't fold i1 branches on PHIs which contain binary operators. These can
1234 // often be turned into switches and other things.
1235 if (PN->getType()->isIntegerTy(1) &&
1236 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1237 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1238 isa<BinaryOperator>(IfCond)))
1239 return false;
1240
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001241 // If we all PHI nodes are promotable, check to make sure that all
1242 // instructions in the predecessor blocks can be promoted as well. If
1243 // not, we won't be able to get rid of the control flow, so it's not
1244 // worth promoting to select instructions.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001245 BasicBlock *DomBlock = 0;
1246 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1247 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1248 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1249 IfBlock1 = 0;
1250 } else {
1251 DomBlock = *pred_begin(IfBlock1);
1252 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001253 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001254 // This is not an aggressive instruction that we can promote.
1255 // Because of this, we won't be able to get rid of the control
1256 // flow, so the xform is not worth it.
1257 return false;
1258 }
1259 }
1260
Chris Lattner44da7ca2010-12-14 07:41:39 +00001261 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1262 IfBlock2 = 0;
1263 } else {
1264 DomBlock = *pred_begin(IfBlock2);
1265 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001266 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001267 // This is not an aggressive instruction that we can promote.
1268 // Because of this, we won't be able to get rid of the control
1269 // flow, so the xform is not worth it.
1270 return false;
1271 }
1272 }
Chris Lattnere0b18e52010-12-14 07:23:10 +00001273
1274 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner44da7ca2010-12-14 07:41:39 +00001275 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001276
1277 // If we can still promote the PHI nodes after this gauntlet of tests,
1278 // do all of the PHI's now.
Chris Lattner3aff13b2010-12-14 08:46:09 +00001279 Instruction *InsertPt = DomBlock->getTerminator();
1280
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001281 // Move all 'aggressive' instructions, which are defined in the
1282 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001283 if (IfBlock1)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001284 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001285 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001286 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001287 if (IfBlock2)
Chris Lattner3aff13b2010-12-14 08:46:09 +00001288 DomBlock->getInstList().splice(InsertPt,
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001289 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001290 IfBlock2->getTerminator());
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001291
1292 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1293 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001294 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1295 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001296
Chris Lattner3aff13b2010-12-14 08:46:09 +00001297 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", InsertPt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001298 PN->replaceAllUsesWith(NV);
1299 NV->takeName(PN);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001300 PN->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001301 }
Chris Lattner60d410d2010-12-14 08:01:53 +00001302
1303 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1304 // has been flattened. Change DomBlock to jump directly to our new block to
1305 // avoid other simplifycfg's kicking in on the diamond.
1306 TerminatorInst *OldTI = DomBlock->getTerminator();
1307 BranchInst::Create(BB, OldTI);
1308 OldTI->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001309 return true;
1310}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001311
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001312/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1313/// to two returning blocks, try to merge them together into one return,
1314/// introducing a select if the return values disagree.
1315static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1316 assert(BI->isConditional() && "Must be a conditional branch");
1317 BasicBlock *TrueSucc = BI->getSuccessor(0);
1318 BasicBlock *FalseSucc = BI->getSuccessor(1);
1319 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1320 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1321
1322 // Check to ensure both blocks are empty (just a return) or optionally empty
1323 // with PHI nodes. If there are other instructions, merging would cause extra
1324 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001325 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001326 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001327 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001328 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001329
1330 // Okay, we found a branch that is going to two return nodes. If
1331 // there is no return value for this function, just change the
1332 // branch into a return.
1333 if (FalseRet->getNumOperands() == 0) {
1334 TrueSucc->removePredecessor(BI->getParent());
1335 FalseSucc->removePredecessor(BI->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +00001336 ReturnInst::Create(BI->getContext(), 0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001337 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001338 return true;
1339 }
1340
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001341 // Otherwise, figure out what the true and false return values are
1342 // so we can insert a new select instruction.
1343 Value *TrueValue = TrueRet->getReturnValue();
1344 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001345
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001346 // Unwrap any PHI nodes in the return blocks.
1347 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1348 if (TVPN->getParent() == TrueSucc)
1349 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1350 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1351 if (FVPN->getParent() == FalseSucc)
1352 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1353
1354 // In order for this transformation to be safe, we must be able to
1355 // unconditionally execute both operands to the return. This is
1356 // normally the case, but we could have a potentially-trapping
1357 // constant expression that prevents this transformation from being
1358 // safe.
1359 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1360 if (TCV->canTrap())
1361 return false;
1362 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1363 if (FCV->canTrap())
1364 return false;
1365
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001366 // Okay, we collected all the mapped values and checked them for sanity, and
1367 // defined to really do this transformation. First, update the CFG.
1368 TrueSucc->removePredecessor(BI->getParent());
1369 FalseSucc->removePredecessor(BI->getParent());
1370
1371 // Insert select instructions where needed.
1372 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001373 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001374 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001375 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1376 } else if (isa<UndefValue>(TrueValue)) {
1377 TrueValue = FalseValue;
1378 } else {
1379 TrueValue = SelectInst::Create(BrCond, TrueValue,
1380 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001381 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001382 }
1383
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001384 Value *RI = !TrueValue ?
Owen Anderson1d0be152009-08-13 21:58:54 +00001385 ReturnInst::Create(BI->getContext(), BI) :
1386 ReturnInst::Create(BI->getContext(), TrueValue, BI);
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001387 (void) RI;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001388
David Greene89d6fd32010-01-05 01:26:52 +00001389 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001390 << "\n " << *BI << "NewRet = " << *RI
1391 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001392
Eli Friedman080efb82008-12-16 20:54:32 +00001393 EraseTerminatorInstAndDCECond(BI);
1394
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001395 return true;
1396}
1397
Chris Lattner1347e872008-07-13 21:12:01 +00001398/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1399/// and if a predecessor branches to us and one of our successors, fold the
1400/// setcc into the predecessor and use logical operations to pick the right
1401/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001402bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001403 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001404 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Owen Andersone84178a2010-07-14 19:52:16 +00001405 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1406 Cond->getParent() != BB || !Cond->hasOneUse())
1407 return false;
Chris Lattner093a4382008-07-13 22:23:11 +00001408
Chris Lattner1347e872008-07-13 21:12:01 +00001409 // Only allow this if the condition is a simple instruction that can be
1410 // executed unconditionally. It must be in the same block as the branch, and
1411 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001412 BasicBlock::iterator FrontIt = BB->front();
1413 // Ignore dbg intrinsics.
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001414 while (isa<DbgInfoIntrinsic>(FrontIt))
Devang Pateld0a203d2009-02-04 21:39:48 +00001415 ++FrontIt;
Owen Andersone84178a2010-07-14 19:52:16 +00001416
1417 // Allow a single instruction to be hoisted in addition to the compare
1418 // that feeds the branch. We later ensure that any values that _it_ uses
1419 // were also live in the predecessor, so that we don't unnecessarily create
1420 // register pressure or inhibit out-of-order execution.
1421 Instruction *BonusInst = 0;
1422 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001423 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1424 FrontIt->isSafeToSpeculativelyExecute()) {
Owen Andersone84178a2010-07-14 19:52:16 +00001425 BonusInst = &*FrontIt;
1426 ++FrontIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001427 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001428
Owen Andersone84178a2010-07-14 19:52:16 +00001429 // Only a single bonus inst is allowed.
1430 if (&*FrontIt != Cond)
1431 return false;
1432
Chris Lattner1347e872008-07-13 21:12:01 +00001433 // Make sure the instruction after the condition is the cond branch.
1434 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001435 // Ingore dbg intrinsics.
1436 while(isa<DbgInfoIntrinsic>(CondIt))
1437 ++CondIt;
1438 if (&*CondIt != BI) {
1439 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001440 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001441 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001442
1443 // Cond is known to be a compare or binary operator. Check to make sure that
1444 // neither operand is a potentially-trapping constant expression.
1445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1446 if (CE->canTrap())
1447 return false;
1448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1449 if (CE->canTrap())
1450 return false;
1451
Chris Lattner1347e872008-07-13 21:12:01 +00001452
1453 // Finally, don't infinitely unroll conditional loops.
1454 BasicBlock *TrueDest = BI->getSuccessor(0);
1455 BasicBlock *FalseDest = BI->getSuccessor(1);
1456 if (TrueDest == BB || FalseDest == BB)
1457 return false;
1458
1459 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1460 BasicBlock *PredBlock = *PI;
1461 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001462
Chris Lattner093a4382008-07-13 22:23:11 +00001463 // Check that we have two conditional branches. If there is a PHI node in
1464 // the common successor, verify that the same value flows in from both
1465 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001466 if (PBI == 0 || PBI->isUnconditional() ||
1467 !SafeToMergeTerminators(BI, PBI))
1468 continue;
1469
Owen Andersone84178a2010-07-14 19:52:16 +00001470 // Ensure that any values used in the bonus instruction are also used
1471 // by the terminator of the predecessor. This means that those values
1472 // must already have been resolved, so we won't be inhibiting the
1473 // out-of-order core by speculating them earlier.
1474 if (BonusInst) {
1475 // Collect the values used by the bonus inst
1476 SmallPtrSet<Value*, 4> UsedValues;
1477 for (Instruction::op_iterator OI = BonusInst->op_begin(),
1478 OE = BonusInst->op_end(); OI != OE; ++OI) {
1479 Value* V = *OI;
1480 if (!isa<Constant>(V))
1481 UsedValues.insert(V);
1482 }
1483
1484 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1485 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1486
1487 // Walk up to four levels back up the use-def chain of the predecessor's
1488 // terminator to see if all those values were used. The choice of four
1489 // levels is arbitrary, to provide a compile-time-cost bound.
1490 while (!Worklist.empty()) {
1491 std::pair<Value*, unsigned> Pair = Worklist.back();
1492 Worklist.pop_back();
1493
1494 if (Pair.second >= 4) continue;
1495 UsedValues.erase(Pair.first);
1496 if (UsedValues.empty()) break;
1497
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001498 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001499 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1500 OI != OE; ++OI)
1501 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1502 }
1503 }
1504
1505 if (!UsedValues.empty()) return false;
1506 }
1507
Chris Lattner36989092008-07-13 21:20:19 +00001508 Instruction::BinaryOps Opc;
1509 bool InvertPredCond = false;
1510
1511 if (PBI->getSuccessor(0) == TrueDest)
1512 Opc = Instruction::Or;
1513 else if (PBI->getSuccessor(1) == FalseDest)
1514 Opc = Instruction::And;
1515 else if (PBI->getSuccessor(0) == FalseDest)
1516 Opc = Instruction::And, InvertPredCond = true;
1517 else if (PBI->getSuccessor(1) == TrueDest)
1518 Opc = Instruction::Or, InvertPredCond = true;
1519 else
1520 continue;
1521
David Greene89d6fd32010-01-05 01:26:52 +00001522 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Chris Lattner6ff645b2009-01-19 23:03:13 +00001523
Chris Lattner36989092008-07-13 21:20:19 +00001524 // If we need to invert the condition in the pred block to match, do so now.
1525 if (InvertPredCond) {
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001526 Value *NewCond = PBI->getCondition();
1527
1528 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1529 CmpInst *CI = cast<CmpInst>(NewCond);
1530 CI->setPredicate(CI->getInversePredicate());
1531 } else {
1532 NewCond = BinaryOperator::CreateNot(NewCond,
Chris Lattner36989092008-07-13 21:20:19 +00001533 PBI->getCondition()->getName()+".not", PBI);
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001534 }
1535
Chris Lattner1347e872008-07-13 21:12:01 +00001536 PBI->setCondition(NewCond);
1537 BasicBlock *OldTrue = PBI->getSuccessor(0);
1538 BasicBlock *OldFalse = PBI->getSuccessor(1);
1539 PBI->setSuccessor(0, OldFalse);
1540 PBI->setSuccessor(1, OldTrue);
1541 }
Chris Lattner70087f32008-07-13 21:15:11 +00001542
Owen Andersone84178a2010-07-14 19:52:16 +00001543 // If we have a bonus inst, clone it into the predecessor block.
1544 Instruction *NewBonus = 0;
1545 if (BonusInst) {
1546 NewBonus = BonusInst->clone();
1547 PredBlock->getInstList().insert(PBI, NewBonus);
1548 NewBonus->takeName(BonusInst);
1549 BonusInst->setName(BonusInst->getName()+".old");
1550 }
1551
Chris Lattner36989092008-07-13 21:20:19 +00001552 // Clone Cond into the predecessor basic block, and or/and the
1553 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00001554 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00001555 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00001556 PredBlock->getInstList().insert(PBI, New);
1557 New->takeName(Cond);
1558 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001559
Chris Lattner36989092008-07-13 21:20:19 +00001560 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1561 New, "or.cond", PBI);
1562 PBI->setCondition(NewCond);
1563 if (PBI->getSuccessor(0) == BB) {
1564 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1565 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001566 }
Chris Lattner36989092008-07-13 21:20:19 +00001567 if (PBI->getSuccessor(1) == BB) {
1568 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1569 PBI->setSuccessor(1, FalseDest);
1570 }
Chris Lattner117f8cf2010-12-14 05:57:30 +00001571 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001572 }
1573 return false;
1574}
1575
Chris Lattner867661a2008-07-13 21:53:26 +00001576/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1577/// predecessor of another block, this function tries to simplify it. We know
1578/// that PBI and BI are both conditional branches, and BI is in one of the
1579/// successor blocks of PBI - PBI branches to BI.
1580static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1581 assert(PBI->isConditional() && BI->isConditional());
1582 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00001583
Chris Lattner867661a2008-07-13 21:53:26 +00001584 // If this block ends with a branch instruction, and if there is a
1585 // predecessor that ends on a branch of the same condition, make
1586 // this conditional branch redundant.
1587 if (PBI->getCondition() == BI->getCondition() &&
1588 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1589 // Okay, the outcome of this conditional branch is statically
1590 // knowable. If this block had a single pred, handle specially.
1591 if (BB->getSinglePredecessor()) {
1592 // Turn this into a branch on constant.
1593 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001594 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1595 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001596 return true; // Nuke the branch on constant.
1597 }
1598
1599 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1600 // in the constant and simplify the block result. Subsequent passes of
1601 // simplifycfg will thread the block.
1602 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001603 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Chris Lattner867661a2008-07-13 21:53:26 +00001604 BI->getCondition()->getName() + ".pr",
1605 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001606 // Okay, we're going to insert the PHI node. Since PBI is not the only
1607 // predecessor, compute the PHI'd conditional value for all of the preds.
1608 // Any predecessor where the condition is not computable we keep symbolic.
Gabor Greif62539832010-07-12 10:59:23 +00001609 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1610 BasicBlock *P = *PI;
1611 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00001612 PBI != BI && PBI->isConditional() &&
1613 PBI->getCondition() == BI->getCondition() &&
1614 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1615 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001616 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00001617 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001618 } else {
Gabor Greif62539832010-07-12 10:59:23 +00001619 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001620 }
Gabor Greif62539832010-07-12 10:59:23 +00001621 }
Chris Lattner867661a2008-07-13 21:53:26 +00001622
1623 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001624 return true;
1625 }
1626 }
1627
1628 // If this is a conditional branch in an empty block, and if any
1629 // predecessors is a conditional branch to one of our destinations,
1630 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001631 BasicBlock::iterator BBI = BB->begin();
1632 // Ignore dbg intrinsics.
1633 while (isa<DbgInfoIntrinsic>(BBI))
1634 ++BBI;
1635 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001636 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001637
1638
1639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1640 if (CE->canTrap())
1641 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001642
1643 int PBIOp, BIOp;
1644 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1645 PBIOp = BIOp = 0;
1646 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1647 PBIOp = 0, BIOp = 1;
1648 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1649 PBIOp = 1, BIOp = 0;
1650 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1651 PBIOp = BIOp = 1;
1652 else
1653 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001654
Chris Lattnerb8245122008-07-13 22:04:41 +00001655 // Check to make sure that the other destination of this branch
1656 // isn't BB itself. If so, this is an infinite loop that will
1657 // keep getting unwound.
1658 if (PBI->getSuccessor(PBIOp) == BB)
1659 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001660
Chris Lattnerb8245122008-07-13 22:04:41 +00001661 // Do not perform this transformation if it would require
1662 // insertion of a large number of select instructions. For targets
1663 // without predication/cmovs, this is a big pessimization.
1664 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001665
Chris Lattnerb8245122008-07-13 22:04:41 +00001666 unsigned NumPhis = 0;
1667 for (BasicBlock::iterator II = CommonDest->begin();
1668 isa<PHINode>(II); ++II, ++NumPhis)
1669 if (NumPhis > 2) // Disable this xform.
1670 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001671
Chris Lattnerb8245122008-07-13 22:04:41 +00001672 // Finally, if everything is ok, fold the branches to logical ops.
1673 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1674
David Greene89d6fd32010-01-05 01:26:52 +00001675 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00001676 << "AND: " << *BI->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001677
Chris Lattner093a4382008-07-13 22:23:11 +00001678
1679 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1680 // branch in it, where one edge (OtherDest) goes back to itself but the other
1681 // exits. We don't *know* that the program avoids the infinite loop
1682 // (even though that seems likely). If we do this xform naively, we'll end up
1683 // recursively unpeeling the loop. Since we know that (after the xform is
1684 // done) that the block *is* infinite if reached, we just make it an obviously
1685 // infinite loop with no cond branch.
1686 if (OtherDest == BB) {
1687 // Insert it at the end of the function, because it's either code,
1688 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001689 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1690 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00001691 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1692 OtherDest = InfLoopBlock;
1693 }
1694
David Greene89d6fd32010-01-05 01:26:52 +00001695 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001696
1697 // BI may have other predecessors. Because of this, we leave
1698 // it alone, but modify PBI.
1699
1700 // Make sure we get to CommonDest on True&True directions.
1701 Value *PBICond = PBI->getCondition();
1702 if (PBIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001703 PBICond = BinaryOperator::CreateNot(PBICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001704 PBICond->getName()+".not",
1705 PBI);
1706 Value *BICond = BI->getCondition();
1707 if (BIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001708 BICond = BinaryOperator::CreateNot(BICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001709 BICond->getName()+".not",
1710 PBI);
1711 // Merge the conditions.
1712 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1713
1714 // Modify PBI to branch on the new condition to the new dests.
1715 PBI->setCondition(Cond);
1716 PBI->setSuccessor(0, CommonDest);
1717 PBI->setSuccessor(1, OtherDest);
1718
1719 // OtherDest may have phi nodes. If so, add an entry from PBI's
1720 // block that are identical to the entries for BI's block.
Chris Lattner6de0a282010-12-14 07:09:42 +00001721 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Chris Lattnerb8245122008-07-13 22:04:41 +00001722
1723 // We know that the CommonDest already had an edge from PBI to
1724 // it. If it has PHIs though, the PHIs may have different
1725 // entries for BB and PBI's BB. If so, insert a select to make
1726 // them agree.
Chris Lattner6de0a282010-12-14 07:09:42 +00001727 PHINode *PN;
Chris Lattnerb8245122008-07-13 22:04:41 +00001728 for (BasicBlock::iterator II = CommonDest->begin();
1729 (PN = dyn_cast<PHINode>(II)); ++II) {
1730 Value *BIV = PN->getIncomingValueForBlock(BB);
1731 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1732 Value *PBIV = PN->getIncomingValue(PBBIdx);
1733 if (BIV != PBIV) {
1734 // Insert a select in PBI to pick the right value.
1735 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1736 PBIV->getName()+".mux", PBI);
1737 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001738 }
1739 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001740
David Greene89d6fd32010-01-05 01:26:52 +00001741 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
1742 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001743
1744 // This basic block is probably dead. We know it has at least
1745 // one fewer predecessor.
1746 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001747}
1748
Frits van Bommel65fdded2011-01-11 12:52:11 +00001749// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
1750// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
1751// Takes care of updating the successors and removing the old terminator.
1752// Also makes sure not to introduce new successors by assuming that edges to
1753// non-successor TrueBBs and FalseBBs aren't reachable.
1754static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
1755 BasicBlock *TrueBB, BasicBlock *FalseBB){
1756 // Remove any superfluous successor edges from the CFG.
1757 // First, figure out which successors to preserve.
1758 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
1759 // successor.
1760 BasicBlock *KeepEdge1 = TrueBB;
1761 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
1762
1763 // Then remove the rest.
1764 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
1765 BasicBlock *Succ = OldTerm->getSuccessor(I);
1766 // Make sure only to keep exactly one copy of each edge.
1767 if (Succ == KeepEdge1)
1768 KeepEdge1 = 0;
1769 else if (Succ == KeepEdge2)
1770 KeepEdge2 = 0;
1771 else
1772 Succ->removePredecessor(OldTerm->getParent());
1773 }
1774
1775 // Insert an appropriate new terminator.
1776 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
1777 if (TrueBB == FalseBB)
1778 // We were only looking for one successor, and it was present.
1779 // Create an unconditional branch to it.
1780 BranchInst::Create(TrueBB, OldTerm);
1781 else
1782 // We found both of the successors we were looking for.
1783 // Create a conditional branch sharing the condition of the select.
1784 BranchInst::Create(TrueBB, FalseBB, Cond, OldTerm);
1785 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
1786 // Neither of the selected blocks were successors, so this
1787 // terminator must be unreachable.
1788 new UnreachableInst(OldTerm->getContext(), OldTerm);
1789 } else {
1790 // One of the selected values was a successor, but the other wasn't.
1791 // Insert an unconditional branch to the one that was found;
1792 // the edge to the one that wasn't must be unreachable.
1793 if (KeepEdge1 == 0)
1794 // Only TrueBB was found.
1795 BranchInst::Create(TrueBB, OldTerm);
1796 else
1797 // Only FalseBB was found.
1798 BranchInst::Create(FalseBB, OldTerm);
1799 }
1800
1801 EraseTerminatorInstAndDCECond(OldTerm);
1802 return true;
1803}
1804
Frits van Bommel7ac40c32010-12-05 18:29:03 +00001805// SimplifyIndirectBrOnSelect - Replaces
1806// (indirectbr (select cond, blockaddress(@fn, BlockA),
1807// blockaddress(@fn, BlockB)))
1808// with
1809// (br cond, BlockA, BlockB).
1810static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
1811 // Check that both operands of the select are block addresses.
1812 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
1813 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
1814 if (!TBA || !FBA)
1815 return false;
1816
1817 // Extract the actual blocks.
1818 BasicBlock *TrueBB = TBA->getBasicBlock();
1819 BasicBlock *FalseBB = FBA->getBasicBlock();
1820
Frits van Bommel65fdded2011-01-11 12:52:11 +00001821 // Perform the actual simplification.
1822 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB);
Frits van Bommel7ac40c32010-12-05 18:29:03 +00001823}
1824
Chris Lattner61c77442010-12-13 03:18:54 +00001825/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
1826/// instruction (a seteq/setne with a constant) as the only instruction in a
1827/// block that ends with an uncond branch. We are looking for a very specific
1828/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
1829/// this case, we merge the first two "or's of icmp" into a switch, but then the
1830/// default value goes to an uncond block with a seteq in it, we get something
1831/// like:
1832///
1833/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
1834/// DEFAULT:
1835/// %tmp = icmp eq i8 %A, 92
1836/// br label %end
1837/// end:
1838/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
1839///
1840/// We prefer to split the edge to 'end' so that there is a true/false entry to
1841/// the PHI, merging the third icmp into the switch.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001842static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
1843 const TargetData *TD) {
Chris Lattner61c77442010-12-13 03:18:54 +00001844 BasicBlock *BB = ICI->getParent();
1845 // If the block has any PHIs in it or the icmp has multiple uses, it is too
1846 // complex.
1847 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
1848
1849 Value *V = ICI->getOperand(0);
1850 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
1851
1852 // The pattern we're looking for is where our only predecessor is a switch on
1853 // 'V' and this block is the default case for the switch. In this case we can
1854 // fold the compared value into the switch to simplify things.
1855 BasicBlock *Pred = BB->getSinglePredecessor();
1856 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
1857
1858 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
1859 if (SI->getCondition() != V)
1860 return false;
1861
1862 // If BB is reachable on a non-default case, then we simply know the value of
1863 // V in this block. Substitute it and constant fold the icmp instruction
1864 // away.
1865 if (SI->getDefaultDest() != BB) {
1866 ConstantInt *VVal = SI->findCaseDest(BB);
1867 assert(VVal && "Should have a unique destination value");
1868 ICI->setOperand(0, VVal);
1869
Chris Lattner302ba6f2010-12-14 06:17:25 +00001870 if (Value *V = SimplifyInstruction(ICI, TD)) {
1871 ICI->replaceAllUsesWith(V);
Chris Lattner61c77442010-12-13 03:18:54 +00001872 ICI->eraseFromParent();
1873 }
1874 // BB is now empty, so it is likely to simplify away.
1875 return SimplifyCFG(BB) | true;
1876 }
1877
Chris Lattnerabf70672010-12-13 03:43:57 +00001878 // Ok, the block is reachable from the default dest. If the constant we're
1879 // comparing exists in one of the other edges, then we can constant fold ICI
1880 // and zap it.
1881 if (SI->findCaseValue(Cst) != 0) {
1882 Value *V;
1883 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1884 V = ConstantInt::getFalse(BB->getContext());
1885 else
1886 V = ConstantInt::getTrue(BB->getContext());
1887
1888 ICI->replaceAllUsesWith(V);
1889 ICI->eraseFromParent();
1890 // BB is now empty, so it is likely to simplify away.
1891 return SimplifyCFG(BB) | true;
1892 }
1893
Chris Lattner61c77442010-12-13 03:18:54 +00001894 // The use of the icmp has to be in the 'end' block, by the only PHI node in
1895 // the block.
1896 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
1897 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
1898 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
1899 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
1900 return false;
1901
1902 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
1903 // true in the PHI.
1904 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
1905 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
1906
1907 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1908 std::swap(DefaultCst, NewCst);
1909
1910 // Replace ICI (which is used by the PHI for the default value) with true or
1911 // false depending on if it is EQ or NE.
1912 ICI->replaceAllUsesWith(DefaultCst);
1913 ICI->eraseFromParent();
1914
1915 // Okay, the switch goes to this block on a default value. Add an edge from
1916 // the switch to the merge point on the compared value.
1917 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
1918 BB->getParent(), BB);
1919 SI->addCase(Cst, NewBB);
1920
1921 // NewBB branches to the phi block, add the uncond branch and the phi entry.
1922 BranchInst::Create(SuccBlock, NewBB);
1923 PHIUse->addIncoming(NewCst, NewBB);
1924 return true;
1925}
1926
Chris Lattner97fdb892010-12-13 05:03:41 +00001927/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
1928/// Check to see if it is branching on an or/and chain of icmp instructions, and
1929/// fold it into a switch instruction if so.
1930static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD) {
1931 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1932 if (Cond == 0) return false;
1933
1934
1935 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1936 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1937 // 'setne's and'ed together, collect them.
1938 Value *CompVal = 0;
1939 std::vector<ConstantInt*> Values;
1940 bool TrueWhenEqual = true;
1941 Value *ExtraCase = 0;
Benjamin Kramer33828bc2011-02-07 22:37:28 +00001942 unsigned UsedICmps = 0;
Chris Lattner97fdb892010-12-13 05:03:41 +00001943
1944 if (Cond->getOpcode() == Instruction::Or) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00001945 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true,
1946 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00001947 } else if (Cond->getOpcode() == Instruction::And) {
Benjamin Kramer33828bc2011-02-07 22:37:28 +00001948 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false,
1949 UsedICmps);
Chris Lattner97fdb892010-12-13 05:03:41 +00001950 TrueWhenEqual = false;
1951 }
1952
1953 // If we didn't have a multiply compared value, fail.
1954 if (CompVal == 0) return false;
1955
Benjamin Kramer33828bc2011-02-07 22:37:28 +00001956 // Avoid turning single icmps into a switch.
1957 if (UsedICmps <= 1)
1958 return false;
1959
Chris Lattner97fdb892010-12-13 05:03:41 +00001960 // There might be duplicate constants in the list, which the switch
1961 // instruction can't handle, remove them now.
1962 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
1963 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1964
1965 // If Extra was used, we require at least two switch values to do the
1966 // transformation. A switch with one value is just an cond branch.
1967 if (ExtraCase && Values.size() < 2) return false;
1968
1969 // Figure out which block is which destination.
1970 BasicBlock *DefaultBB = BI->getSuccessor(1);
1971 BasicBlock *EdgeBB = BI->getSuccessor(0);
1972 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1973
1974 BasicBlock *BB = BI->getParent();
1975
Chris Lattner302ba6f2010-12-14 06:17:25 +00001976 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner117f8cf2010-12-14 05:57:30 +00001977 << " cases into SWITCH. BB is:\n" << *BB);
1978
Chris Lattner97fdb892010-12-13 05:03:41 +00001979 // If there are any extra values that couldn't be folded into the switch
1980 // then we evaluate them with an explicit branch first. Split the block
1981 // right before the condbr to handle it.
1982 if (ExtraCase) {
1983 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
1984 // Remove the uncond branch added to the old block.
1985 TerminatorInst *OldTI = BB->getTerminator();
1986
Chris Lattner117f8cf2010-12-14 05:57:30 +00001987 if (TrueWhenEqual)
1988 BranchInst::Create(EdgeBB, NewBB, ExtraCase, OldTI);
1989 else
1990 BranchInst::Create(NewBB, EdgeBB, ExtraCase, OldTI);
1991
Chris Lattner97fdb892010-12-13 05:03:41 +00001992 OldTI->eraseFromParent();
Chris Lattner97bd89e2010-12-13 05:34:18 +00001993
1994 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
1995 // for the edge we just added.
Chris Lattner6de0a282010-12-14 07:09:42 +00001996 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001997
1998 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
1999 << "\nEXTRABB = " << *BB);
Chris Lattner97fdb892010-12-13 05:03:41 +00002000 BB = NewBB;
2001 }
2002
2003 // Convert pointer to int before we switch.
2004 if (CompVal->getType()->isPointerTy()) {
2005 assert(TD && "Cannot switch on pointer without TargetData");
2006 CompVal = new PtrToIntInst(CompVal,
2007 TD->getIntPtrType(CompVal->getContext()),
2008 "magicptr", BI);
2009 }
2010
2011 // Create the new switch instruction now.
Chris Lattner3d512132010-12-13 06:25:44 +00002012 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB, Values.size(), BI);
Chris Lattner97fdb892010-12-13 05:03:41 +00002013
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);
Chris Lattner117f8cf2010-12-14 05:57:30 +00002031
Chris Lattner302ba6f2010-12-14 06:17:25 +00002032 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattner97fdb892010-12-13 05:03:41 +00002033 return true;
2034}
2035
Chris Lattner3d512132010-12-13 06:25:44 +00002036bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI) {
2037 BasicBlock *BB = RI->getParent();
2038 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2039
2040 // Find predecessors that end with branches.
2041 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2042 SmallVector<BranchInst*, 8> CondBranchPreds;
2043 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2044 BasicBlock *P = *PI;
2045 TerminatorInst *PTI = P->getTerminator();
2046 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2047 if (BI->isUnconditional())
2048 UncondBranchPreds.push_back(P);
2049 else
2050 CondBranchPreds.push_back(BI);
2051 }
2052 }
2053
2054 // If we found some, do the transformation!
Evan Chengc3f507f2011-01-29 04:46:23 +00002055 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner3d512132010-12-13 06:25:44 +00002056 while (!UncondBranchPreds.empty()) {
2057 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2058 DEBUG(dbgs() << "FOLDING: " << *BB
2059 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengc3f507f2011-01-29 04:46:23 +00002060 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner3d512132010-12-13 06:25:44 +00002061 }
2062
2063 // If we eliminated all predecessors of the block, delete the block now.
2064 if (pred_begin(BB) == pred_end(BB))
2065 // We know there are no successors, so just nuke the block.
2066 BB->eraseFromParent();
2067
2068 return true;
2069 }
2070
2071 // Check out all of the conditional branches going to this return
2072 // instruction. If any of them just select between returns, change the
2073 // branch itself into a select/return pair.
2074 while (!CondBranchPreds.empty()) {
2075 BranchInst *BI = CondBranchPreds.pop_back_val();
2076
2077 // Check to see if the non-BB successor is also a return block.
2078 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2079 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2080 SimplifyCondBranchToTwoReturns(BI))
2081 return true;
2082 }
2083 return false;
2084}
2085
2086bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI) {
2087 // Check to see if the first instruction in this block is just an unwind.
2088 // If so, replace any invoke instructions which use this as an exception
2089 // destination with call instructions.
2090 BasicBlock *BB = UI->getParent();
2091 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2092
2093 bool Changed = false;
2094 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2095 while (!Preds.empty()) {
2096 BasicBlock *Pred = Preds.back();
2097 InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
2098 if (II && II->getUnwindDest() == BB) {
2099 // Insert a new branch instruction before the invoke, because this
2100 // is now a fall through.
2101 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2102 Pred->getInstList().remove(II); // Take out of symbol table
2103
2104 // Insert the call now.
2105 SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
2106 CallInst *CI = CallInst::Create(II->getCalledValue(),
2107 Args.begin(), Args.end(),
2108 II->getName(), BI);
2109 CI->setCallingConv(II->getCallingConv());
2110 CI->setAttributes(II->getAttributes());
2111 // If the invoke produced a value, the Call now does instead.
2112 II->replaceAllUsesWith(CI);
2113 delete II;
2114 Changed = true;
2115 }
2116
2117 Preds.pop_back();
2118 }
2119
2120 // If this block is now dead (and isn't the entry block), remove it.
2121 if (pred_begin(BB) == pred_end(BB) &&
2122 BB != &BB->getParent()->getEntryBlock()) {
2123 // We know there are no successors, so just nuke the block.
2124 BB->eraseFromParent();
2125 return true;
2126 }
2127
2128 return Changed;
2129}
2130
2131bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2132 BasicBlock *BB = UI->getParent();
2133
2134 bool Changed = false;
2135
2136 // If there are any instructions immediately before the unreachable that can
2137 // be removed, do so.
2138 while (UI != BB->begin()) {
2139 BasicBlock::iterator BBI = UI;
2140 --BBI;
2141 // Do not delete instructions that can have side effects, like calls
2142 // (which may never return) and volatile loads and stores.
2143 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2144
2145 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2146 if (SI->isVolatile())
2147 break;
2148
2149 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2150 if (LI->isVolatile())
2151 break;
2152
2153 // Delete this instruction
Chris Lattner302ba6f2010-12-14 06:17:25 +00002154 BBI->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002155 Changed = true;
2156 }
2157
2158 // If the unreachable instruction is the first in the block, take a gander
2159 // at all of the predecessors of this instruction, and simplify them.
2160 if (&BB->front() != UI) return Changed;
2161
2162 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2163 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2164 TerminatorInst *TI = Preds[i]->getTerminator();
2165
2166 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2167 if (BI->isUnconditional()) {
2168 if (BI->getSuccessor(0) == BB) {
2169 new UnreachableInst(TI->getContext(), TI);
2170 TI->eraseFromParent();
2171 Changed = true;
2172 }
2173 } else {
2174 if (BI->getSuccessor(0) == BB) {
2175 BranchInst::Create(BI->getSuccessor(1), BI);
2176 EraseTerminatorInstAndDCECond(BI);
2177 } else if (BI->getSuccessor(1) == BB) {
2178 BranchInst::Create(BI->getSuccessor(0), BI);
2179 EraseTerminatorInstAndDCECond(BI);
2180 Changed = true;
2181 }
2182 }
2183 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2184 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2185 if (SI->getSuccessor(i) == BB) {
2186 BB->removePredecessor(SI->getParent());
2187 SI->removeCase(i);
2188 --i; --e;
2189 Changed = true;
2190 }
2191 // If the default value is unreachable, figure out the most popular
2192 // destination and make it the default.
2193 if (SI->getSuccessor(0) == BB) {
2194 std::map<BasicBlock*, unsigned> Popularity;
2195 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2196 Popularity[SI->getSuccessor(i)]++;
2197
2198 // Find the most popular block.
2199 unsigned MaxPop = 0;
2200 BasicBlock *MaxBlock = 0;
2201 for (std::map<BasicBlock*, unsigned>::iterator
2202 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2203 if (I->second > MaxPop) {
2204 MaxPop = I->second;
2205 MaxBlock = I->first;
2206 }
2207 }
2208 if (MaxBlock) {
2209 // Make this the new default, allowing us to delete any explicit
2210 // edges to it.
2211 SI->setSuccessor(0, MaxBlock);
2212 Changed = true;
2213
2214 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2215 // it.
2216 if (isa<PHINode>(MaxBlock->begin()))
2217 for (unsigned i = 0; i != MaxPop-1; ++i)
2218 MaxBlock->removePredecessor(SI->getParent());
2219
2220 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2221 if (SI->getSuccessor(i) == MaxBlock) {
2222 SI->removeCase(i);
2223 --i; --e;
2224 }
2225 }
2226 }
2227 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2228 if (II->getUnwindDest() == BB) {
2229 // Convert the invoke to a call instruction. This would be a good
2230 // place to note that the call does not throw though.
2231 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2232 II->removeFromParent(); // Take out of symbol table
2233
2234 // Insert the call now...
2235 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
2236 CallInst *CI = CallInst::Create(II->getCalledValue(),
2237 Args.begin(), Args.end(),
2238 II->getName(), BI);
2239 CI->setCallingConv(II->getCallingConv());
2240 CI->setAttributes(II->getAttributes());
2241 // If the invoke produced a value, the call does now instead.
2242 II->replaceAllUsesWith(CI);
2243 delete II;
2244 Changed = true;
2245 }
2246 }
2247 }
2248
2249 // If this block is now dead, remove it.
2250 if (pred_begin(BB) == pred_end(BB) &&
2251 BB != &BB->getParent()->getEntryBlock()) {
2252 // We know there are no successors, so just nuke the block.
2253 BB->eraseFromParent();
2254 return true;
2255 }
2256
2257 return Changed;
2258}
2259
Benjamin Kramer56442df2011-02-02 15:56:22 +00002260/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
2261/// integer range comparison into a sub, an icmp and a branch.
2262static bool TurnSwitchRangeIntoICmp(SwitchInst *SI) {
2263 assert(SI->getNumCases() > 2 && "Degenerate switch?");
Benjamin Kramer56442df2011-02-02 15:56:22 +00002264
Benjamin Kramer042b27f2011-02-03 22:51:41 +00002265 // Make sure all cases point to the same destination and gather the values.
2266 SmallVector<ConstantInt *, 16> Cases;
2267 Cases.push_back(SI->getCaseValue(1));
2268 for (unsigned I = 2, E = SI->getNumCases(); I != E; ++I) {
2269 if (SI->getSuccessor(I-1) != SI->getSuccessor(I))
2270 return false;
2271 Cases.push_back(SI->getCaseValue(I));
2272 }
2273 assert(Cases.size() == SI->getNumCases()-1 && "Not all cases gathered");
2274
2275 // Sort the case values, then check if they form a range we can transform.
2276 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
2277 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
2278 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
2279 return false;
2280 }
2281
2282 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Benjamin Kramer56442df2011-02-02 15:56:22 +00002283 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases()-1);
2284
Benjamin Kramer33828bc2011-02-07 22:37:28 +00002285 Value *Sub = SI->getCondition();
2286 if (!Offset->isNullValue())
2287 Sub = BinaryOperator::CreateAdd(Sub, Offset, Sub->getName()+".off", SI);
Benjamin Kramer56442df2011-02-02 15:56:22 +00002288 Value *Cmp = new ICmpInst(SI, ICmpInst::ICMP_ULT, Sub, NumCases, "switch");
2289 BranchInst::Create(SI->getSuccessor(1), SI->getDefaultDest(), Cmp, SI);
2290
2291 // Prune obsolete incoming values off the successor's PHI nodes.
2292 for (BasicBlock::iterator BBI = SI->getSuccessor(1)->begin();
2293 isa<PHINode>(BBI); ++BBI) {
2294 for (unsigned I = 0, E = SI->getNumCases()-2; I != E; ++I)
2295 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
2296 }
2297 SI->eraseFromParent();
2298
2299 return true;
2300}
Chris Lattner3d512132010-12-13 06:25:44 +00002301
2302bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI) {
2303 // If this switch is too complex to want to look at, ignore it.
2304 if (!isValueEqualityComparison(SI))
2305 return false;
2306
2307 BasicBlock *BB = SI->getParent();
2308
2309 // If we only have one predecessor, and if it is a branch on this value,
2310 // see if that predecessor totally determines the outcome of this switch.
2311 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2312 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
Chris Lattner021c9d32010-12-13 06:36:51 +00002313 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002314
2315 // If the block only contains the switch, see if we can fold the block
2316 // away into any preds.
2317 BasicBlock::iterator BBI = BB->begin();
2318 // Ignore dbg intrinsics.
2319 while (isa<DbgInfoIntrinsic>(BBI))
2320 ++BBI;
2321 if (SI == &*BBI)
2322 if (FoldValueComparisonIntoPredecessors(SI))
Chris Lattner021c9d32010-12-13 06:36:51 +00002323 return SimplifyCFG(BB) | true;
Benjamin Kramer56442df2011-02-02 15:56:22 +00002324
2325 // Try to transform the switch into an icmp and a branch.
2326 if (TurnSwitchRangeIntoICmp(SI))
2327 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002328
2329 return false;
2330}
2331
2332bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
2333 BasicBlock *BB = IBI->getParent();
2334 bool Changed = false;
2335
2336 // Eliminate redundant destinations.
2337 SmallPtrSet<Value *, 8> Succs;
2338 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2339 BasicBlock *Dest = IBI->getDestination(i);
2340 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
2341 Dest->removePredecessor(BB);
2342 IBI->removeDestination(i);
2343 --i; --e;
2344 Changed = true;
2345 }
2346 }
2347
2348 if (IBI->getNumDestinations() == 0) {
2349 // If the indirectbr has no successors, change it to unreachable.
2350 new UnreachableInst(IBI->getContext(), IBI);
2351 EraseTerminatorInstAndDCECond(IBI);
2352 return true;
2353 }
2354
2355 if (IBI->getNumDestinations() == 1) {
2356 // If the indirectbr has one successor, change it to a direct branch.
2357 BranchInst::Create(IBI->getDestination(0), IBI);
2358 EraseTerminatorInstAndDCECond(IBI);
2359 return true;
2360 }
2361
2362 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2363 if (SimplifyIndirectBrOnSelect(IBI, SI))
2364 return SimplifyCFG(BB) | true;
2365 }
2366 return Changed;
2367}
2368
2369bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI) {
2370 BasicBlock *BB = BI->getParent();
2371
2372 // If the Terminator is the only non-phi instruction, simplify the block.
2373 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
2374 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
2375 TryToSimplifyUncondBranchFromEmptyBlock(BB))
2376 return true;
2377
2378 // If the only instruction in the block is a seteq/setne comparison
2379 // against a constant, try to simplify the block.
2380 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
2381 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
2382 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
2383 ;
Chris Lattner302ba6f2010-12-14 06:17:25 +00002384 if (I->isTerminator() && TryToSimplifyUncondBranchWithICmpInIt(ICI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002385 return true;
2386 }
2387
2388 return false;
2389}
2390
2391
2392bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI) {
2393 BasicBlock *BB = BI->getParent();
2394
2395 // Conditional branch
2396 if (isValueEqualityComparison(BI)) {
2397 // If we only have one predecessor, and if it is a branch on this value,
2398 // see if that predecessor totally determines the outcome of this
2399 // switch.
2400 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2401 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
2402 return SimplifyCFG(BB) | true;
2403
2404 // This block must be empty, except for the setcond inst, if it exists.
2405 // Ignore dbg intrinsics.
2406 BasicBlock::iterator I = BB->begin();
2407 // Ignore dbg intrinsics.
2408 while (isa<DbgInfoIntrinsic>(I))
2409 ++I;
2410 if (&*I == BI) {
2411 if (FoldValueComparisonIntoPredecessors(BI))
2412 return SimplifyCFG(BB) | true;
2413 } else if (&*I == cast<Instruction>(BI->getCondition())){
2414 ++I;
2415 // Ignore dbg intrinsics.
2416 while (isa<DbgInfoIntrinsic>(I))
2417 ++I;
2418 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI))
2419 return SimplifyCFG(BB) | true;
2420 }
2421 }
2422
2423 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
2424 if (SimplifyBranchOnICmpChain(BI, TD))
2425 return true;
2426
2427 // We have a conditional branch to two blocks that are only reachable
2428 // from BI. We know that the condbr dominates the two blocks, so see if
2429 // there is any identical code in the "then" and "else" blocks. If so, we
2430 // can hoist it up to the branching block.
2431 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
2432 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2433 if (HoistThenElseCodeToIf(BI))
2434 return SimplifyCFG(BB) | true;
2435 } else {
2436 // If Successor #1 has multiple preds, we may be able to conditionally
2437 // execute Successor #0 if it branches to successor #1.
2438 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
2439 if (Succ0TI->getNumSuccessors() == 1 &&
2440 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
2441 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
2442 return SimplifyCFG(BB) | true;
2443 }
2444 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2445 // If Successor #0 has multiple preds, we may be able to conditionally
2446 // execute Successor #1 if it branches to successor #0.
2447 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
2448 if (Succ1TI->getNumSuccessors() == 1 &&
2449 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
2450 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
2451 return SimplifyCFG(BB) | true;
2452 }
2453
2454 // If this is a branch on a phi node in the current block, thread control
2455 // through this block if any PHI node entries are constants.
2456 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
2457 if (PN->getParent() == BI->getParent())
Chris Lattner302ba6f2010-12-14 06:17:25 +00002458 if (FoldCondBranchOnPHI(BI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002459 return SimplifyCFG(BB) | true;
2460
2461 // If this basic block is ONLY a setcc and a branch, and if a predecessor
2462 // branches to us and one of our successors, fold the setcc into the
2463 // predecessor and use logical operations to pick the right destination.
2464 if (FoldBranchToCommonDest(BI))
Owen Anderson2d9220e2010-12-13 23:49:28 +00002465 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002466
2467 // Scan predecessor blocks for conditional branches.
2468 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2469 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2470 if (PBI != BI && PBI->isConditional())
2471 if (SimplifyCondBranchToCondBranch(PBI, BI))
2472 return SimplifyCFG(BB) | true;
2473
2474 return false;
2475}
2476
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002477bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00002478 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002479
Chris Lattner302ba6f2010-12-14 06:17:25 +00002480 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00002481 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00002482
Dan Gohmane2c6d132010-08-14 00:29:42 +00002483 // Remove basic blocks that have no predecessors (except the entry block)...
2484 // or that just have themself as a predecessor. These are unreachable.
Chris Lattner302ba6f2010-12-14 06:17:25 +00002485 if ((pred_begin(BB) == pred_end(BB) &&
2486 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00002487 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00002488 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00002489 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00002490 return true;
2491 }
2492
Chris Lattner694e37f2003-08-17 19:41:53 +00002493 // Check to see if we can constant propagate this terminator instruction
2494 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00002495 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00002496
Dan Gohman2c635662009-10-30 22:39:04 +00002497 // Check for and eliminate duplicate PHI nodes in this block.
2498 Changed |= EliminateDuplicatePHINodes(BB);
2499
Chris Lattnerddb97a22010-12-13 05:10:48 +00002500 // Merge basic blocks into their predecessor if there is only one distinct
2501 // pred, and if there is only one distinct successor of the predecessor, and
2502 // if there are no PHI nodes.
2503 //
2504 if (MergeBlockIntoPredecessor(BB))
2505 return true;
2506
Dan Gohman882d87d2008-03-11 21:53:06 +00002507 // If there is a trivial two-entry PHI node in this basic block, and we can
2508 // eliminate it, do so now.
2509 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
2510 if (PN->getNumIncomingValues() == 2)
Chris Lattner73c50a62010-12-14 07:00:00 +00002511 Changed |= FoldTwoEntryPHINode(PN, TD);
Dan Gohman882d87d2008-03-11 21:53:06 +00002512
Chris Lattner3d512132010-12-13 06:25:44 +00002513 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner021c9d32010-12-13 06:36:51 +00002514 if (BI->isUnconditional()) {
2515 if (SimplifyUncondBranch(BI)) return true;
2516 } else {
Chris Lattner117f8cf2010-12-14 05:57:30 +00002517 if (SimplifyCondBranch(BI)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00002518 }
2519 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
2520 if (SimplifyReturn(RI)) return true;
2521 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2522 if (SimplifySwitch(SI)) return true;
2523 } else if (UnreachableInst *UI =
2524 dyn_cast<UnreachableInst>(BB->getTerminator())) {
2525 if (SimplifyUnreachable(UI)) return true;
2526 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
2527 if (SimplifyUnwind(UI)) return true;
2528 } else if (IndirectBrInst *IBI =
2529 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
2530 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattner19831ec2004-02-16 06:35:48 +00002531 }
2532
Chris Lattner694e37f2003-08-17 19:41:53 +00002533 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002534}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002535
2536/// SimplifyCFG - This function is used to do simplification of a CFG. For
2537/// example, it adjusts branches to branches to eliminate the extra hop, it
2538/// eliminates unreachable basic blocks, and does other "peephole" optimization
2539/// of the CFG. It returns true if a modification was made.
2540///
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002541bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
2542 return SimplifyCFGOpt(TD).run(BB);
2543}