blob: 1fbbb42b60e9893ec5e99b07bf5494e8ec2cd134 [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"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000033#include <algorithm>
Chris Lattnerd52c2612004-02-24 07:23:58 +000034#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000035#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000036using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000037
Evan Cheng502a4f52008-06-12 21:15:59 +000038STATISTIC(NumSpeculations, "Number of speculative executed instructions");
39
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000040namespace {
41class SimplifyCFGOpt {
42 const TargetData *const TD;
43
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000044 Value *isValueEqualityComparison(TerminatorInst *TI);
45 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
46 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases);
47 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
48 BasicBlock *Pred);
49 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI);
50
Chris Lattner3d512132010-12-13 06:25:44 +000051 bool SimplifyReturn(ReturnInst *RI);
52 bool SimplifyUnwind(UnwindInst *UI);
53 bool SimplifyUnreachable(UnreachableInst *UI);
54 bool SimplifySwitch(SwitchInst *SI);
55 bool SimplifyIndirectBr(IndirectBrInst *IBI);
56 bool SimplifyUncondBranch(BranchInst *BI);
57 bool SimplifyCondBranch(BranchInst *BI);
58
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +000059public:
60 explicit SimplifyCFGOpt(const TargetData *td) : TD(td) {}
61 bool run(BasicBlock *BB);
62};
63}
64
Chris Lattner2bdcb562005-08-03 00:19:45 +000065/// SafeToMergeTerminators - Return true if it is safe to merge these two
66/// terminator instructions together.
67///
68static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
69 if (SI1 == SI2) return false; // Can't merge with self!
70
71 // It is not safe to merge these two switch instructions if they have a common
72 // successor, and if that successor has a PHI node, and if *that* PHI node has
73 // conflicting incoming values from the two switch blocks.
74 BasicBlock *SI1BB = SI1->getParent();
75 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000076 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000077
78 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
79 if (SI1Succs.count(*I))
80 for (BasicBlock::iterator BBI = (*I)->begin();
81 isa<PHINode>(BBI); ++BBI) {
82 PHINode *PN = cast<PHINode>(BBI);
83 if (PN->getIncomingValueForBlock(SI1BB) !=
84 PN->getIncomingValueForBlock(SI2BB))
85 return false;
86 }
87
88 return true;
89}
90
91/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
92/// now be entries in it from the 'NewPred' block. The values that will be
93/// flowing into the PHI nodes will be the same as those coming in from
94/// ExistPred, an existing predecessor of Succ.
95static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
96 BasicBlock *ExistPred) {
Chris Lattner2bdcb562005-08-03 00:19:45 +000097 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
98
Chris Lattner093a4382008-07-13 22:23:11 +000099 PHINode *PN;
100 for (BasicBlock::iterator I = Succ->begin();
101 (PN = dyn_cast<PHINode>(I)); ++I)
102 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +0000103}
104
Chris Lattner7e663482005-08-03 00:11:16 +0000105
Chris Lattner73c50a62010-12-14 07:00:00 +0000106/// GetIfCondition - Given a basic block (BB) with two predecessors (and at
107/// least one PHI node in it), check to see if the merge at this block is due
Chris Lattner723c66d2004-02-11 03:36:04 +0000108/// to an "if condition". If so, return the boolean condition that determines
109/// which entry into BB will be taken. Also, return by references the block
110/// that will be entered from if the condition is true, and the block that will
111/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000112///
Chris Lattner995ba1b2010-12-14 07:15:21 +0000113/// This does no checking to see if the true/false blocks have large or unsavory
114/// instructions in them.
Chris Lattner73c50a62010-12-14 07:00:00 +0000115static Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
116 BasicBlock *&IfFalse) {
117 PHINode *SomePHI = cast<PHINode>(BB->begin());
118 assert(SomePHI->getNumIncomingValues() == 2 &&
Chris Lattner723c66d2004-02-11 03:36:04 +0000119 "Function can only handle blocks with 2 predecessors!");
Chris Lattner73c50a62010-12-14 07:00:00 +0000120 BasicBlock *Pred1 = SomePHI->getIncomingBlock(0);
121 BasicBlock *Pred2 = SomePHI->getIncomingBlock(1);
Chris Lattner723c66d2004-02-11 03:36:04 +0000122
123 // We can only handle branches. Other control flow will be lowered to
124 // branches if possible anyway.
Chris Lattner995ba1b2010-12-14 07:15:21 +0000125 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
126 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
127 if (Pred1Br == 0 || Pred2Br == 0)
Chris Lattner723c66d2004-02-11 03:36:04 +0000128 return 0;
Chris Lattner723c66d2004-02-11 03:36:04 +0000129
130 // Eliminate code duplication by ensuring that Pred1Br is conditional if
131 // either are.
132 if (Pred2Br->isConditional()) {
133 // If both branches are conditional, we don't have an "if statement". In
134 // reality, we could transform this case, but since the condition will be
135 // required anyway, we stand no chance of eliminating it, so the xform is
136 // probably not profitable.
137 if (Pred1Br->isConditional())
138 return 0;
139
140 std::swap(Pred1, Pred2);
141 std::swap(Pred1Br, Pred2Br);
142 }
143
144 if (Pred1Br->isConditional()) {
Chris Lattner995ba1b2010-12-14 07:15:21 +0000145 // The only thing we have to watch out for here is to make sure that Pred2
146 // doesn't have incoming edges from other blocks. If it does, the condition
147 // doesn't dominate BB.
148 if (Pred2->getSinglePredecessor() == 0)
149 return 0;
150
Chris Lattner723c66d2004-02-11 03:36:04 +0000151 // If we found a conditional branch predecessor, make sure that it branches
152 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
153 if (Pred1Br->getSuccessor(0) == BB &&
154 Pred1Br->getSuccessor(1) == Pred2) {
155 IfTrue = Pred1;
156 IfFalse = Pred2;
157 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
158 Pred1Br->getSuccessor(1) == BB) {
159 IfTrue = Pred2;
160 IfFalse = Pred1;
161 } else {
162 // We know that one arm of the conditional goes to BB, so the other must
163 // go somewhere unrelated, and this must not be an "if statement".
164 return 0;
165 }
166
Chris Lattner723c66d2004-02-11 03:36:04 +0000167 return Pred1Br->getCondition();
168 }
169
170 // Ok, if we got here, both predecessors end with an unconditional branch to
171 // BB. Don't panic! If both blocks only have a single (identical)
172 // predecessor, and THAT is a conditional branch, then we're all ok!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000173 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
174 if (CommonPred == 0 || CommonPred != Pred2->getSinglePredecessor())
Chris Lattner723c66d2004-02-11 03:36:04 +0000175 return 0;
176
177 // Otherwise, if this is a conditional branch, then we can use it!
Chris Lattner995ba1b2010-12-14 07:15:21 +0000178 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
179 if (BI == 0) return 0;
180
181 assert(BI->isConditional() && "Two successors but not conditional?");
182 if (BI->getSuccessor(0) == Pred1) {
183 IfTrue = Pred1;
184 IfFalse = Pred2;
185 } else {
186 IfTrue = Pred2;
187 IfFalse = Pred1;
Chris Lattner723c66d2004-02-11 03:36:04 +0000188 }
Chris Lattner995ba1b2010-12-14 07:15:21 +0000189 return BI->getCondition();
Chris Lattner723c66d2004-02-11 03:36:04 +0000190}
191
Bill Wendling5049fa62009-01-19 23:43:56 +0000192/// DominatesMergePoint - If we have a merge point of an "if condition" as
193/// accepted above, return true if the specified value dominates the block. We
194/// don't handle the true generality of domination here, just a special case
195/// which works well enough for us.
196///
197/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
198/// see if V (which must be an instruction) is cheap to compute and is
199/// non-trapping. If both are true, the instruction is inserted into the set
200/// and true is returned.
Chris Lattner9c078662004-10-14 05:13:36 +0000201static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Chris Lattner44da7ca2010-12-14 07:41:39 +0000202 SmallPtrSet<Instruction*, 4> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000203 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000204 if (!I) {
205 // Non-instructions all dominate instructions, but not all constantexprs
206 // can be executed unconditionally.
207 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
208 if (C->canTrap())
209 return false;
210 return true;
211 }
Chris Lattner570751c2004-04-09 22:50:22 +0000212 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000213
Chris Lattnerda895d62005-02-27 06:18:25 +0000214 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000215 // the bottom of this block.
216 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000217
Chris Lattner570751c2004-04-09 22:50:22 +0000218 // If this instruction is defined in a block that contains an unconditional
219 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner44da7ca2010-12-14 07:41:39 +0000220 // statement". If not, it definitely dominates the region.
221 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
222 if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
223 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +0000224
Chris Lattner44da7ca2010-12-14 07:41:39 +0000225 // If we aren't allowing aggressive promotion anymore, then don't consider
226 // instructions in the 'if region'.
227 if (AggressiveInsts == 0) return false;
228
229 // Okay, it looks like the instruction IS in the "condition". Check to
230 // see if it's a cheap instruction to unconditionally compute, and if it
231 // only uses stuff defined outside of the condition. If so, hoist it out.
232 if (!I->isSafeToSpeculativelyExecute())
233 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000234
Chris Lattner44da7ca2010-12-14 07:41:39 +0000235 switch (I->getOpcode()) {
236 default: return false; // Cannot hoist this out safely.
237 case Instruction::Load:
238 // We have to check to make sure there are no instructions before the
239 // load in its basic block, as we are going to hoist the load out to its
240 // predecessor.
241 if (PBB->getFirstNonPHIOrDbg() != I)
242 return false;
243 break;
244 case Instruction::Add:
245 case Instruction::Sub:
246 case Instruction::And:
247 case Instruction::Or:
248 case Instruction::Xor:
249 case Instruction::Shl:
250 case Instruction::LShr:
251 case Instruction::AShr:
252 case Instruction::ICmp:
253 break; // These are all cheap and non-trapping instructions.
254 }
Chris Lattner570751c2004-04-09 22:50:22 +0000255
Chris Lattner44da7ca2010-12-14 07:41:39 +0000256 // Okay, we can only really hoist these out if their operands are not
257 // defined in the conditional region.
258 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
259 if (!DominatesMergePoint(*i, BB, 0))
260 return false;
261 // Okay, it's safe to do this! Remember this instruction.
262 AggressiveInsts->insert(I);
Chris Lattner723c66d2004-02-11 03:36:04 +0000263 return true;
264}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000265
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000266/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
267/// and PointerNullValue. Return NULL if value is not a constant int.
Chris Lattner28acc132010-12-13 03:30:12 +0000268static ConstantInt *GetConstantInt(Value *V, const TargetData *TD) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000269 // Normal constant int.
270 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Duncan Sands1df98592010-02-16 11:11:14 +0000271 if (CI || !TD || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000272 return CI;
273
274 // This is some kind of pointer constant. Turn it into a pointer-sized
275 // ConstantInt if possible.
276 const IntegerType *PtrTy = TD->getIntPtrType(V->getContext());
277
278 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
279 if (isa<ConstantPointerNull>(V))
280 return ConstantInt::get(PtrTy, 0);
281
282 // IntToPtr const int.
283 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
284 if (CE->getOpcode() == Instruction::IntToPtr)
285 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
286 // The constant is very likely to have the right type already.
287 if (CI->getType() == PtrTy)
288 return CI;
289 else
290 return cast<ConstantInt>
291 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
292 }
293 return 0;
294}
295
Chris Lattner0aa749b2010-12-13 04:26:26 +0000296/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
297/// collection of icmp eq/ne instructions that compare a value against a
298/// constant, return the value being compared, and stick the constant into the
299/// Values vector.
Chris Lattner28acc132010-12-13 03:30:12 +0000300static Value *
Chris Lattner0aa749b2010-12-13 04:26:26 +0000301GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
302 const TargetData *TD, bool isEQ) {
303 Instruction *I = dyn_cast<Instruction>(V);
304 if (I == 0) return 0;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000305
Chris Lattner7312a222010-12-13 04:50:38 +0000306 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000307 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
308 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE))
309 if (ConstantInt *C = GetConstantInt(I->getOperand(1), TD)) {
310 Vals.push_back(C);
311 return I->getOperand(0);
312 }
Chris Lattner662269d2010-12-13 04:18:32 +0000313 return 0;
314 }
315
Chris Lattner7312a222010-12-13 04:50:38 +0000316 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner0aa749b2010-12-13 04:26:26 +0000317 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Chris Lattner662269d2010-12-13 04:18:32 +0000318 return 0;
Chris Lattner662269d2010-12-13 04:18:32 +0000319
Chris Lattner7312a222010-12-13 04:50:38 +0000320 unsigned NumValsBeforeLHS = Vals.size();
Chris Lattner0aa749b2010-12-13 04:26:26 +0000321 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, TD,
322 isEQ)) {
Chris Lattner7312a222010-12-13 04:50:38 +0000323 unsigned NumVals = Vals.size();
Chris Lattner0aa749b2010-12-13 04:26:26 +0000324 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
325 isEQ)) {
326 if (LHS == RHS)
327 return LHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000328 Vals.resize(NumVals);
Chris Lattner0aa749b2010-12-13 04:26:26 +0000329 }
Chris Lattner7312a222010-12-13 04:50:38 +0000330
331 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
332 // set it and return success.
333 if (Extra == 0 || Extra == I->getOperand(1)) {
334 Extra = I->getOperand(1);
335 return LHS;
336 }
337
338 Vals.resize(NumValsBeforeLHS);
339 return 0;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000340 }
Chris Lattner7312a222010-12-13 04:50:38 +0000341
342 // If the LHS can't be folded in, but Extra is available and RHS can, try to
343 // use LHS as Extra.
344 if (Extra == 0 || Extra == I->getOperand(0)) {
Chris Lattner92407e52010-12-13 07:41:29 +0000345 Value *OldExtra = Extra;
Chris Lattner7312a222010-12-13 04:50:38 +0000346 Extra = I->getOperand(0);
347 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, TD,
348 isEQ))
349 return RHS;
Chris Lattner92407e52010-12-13 07:41:29 +0000350 assert(Vals.size() == NumValsBeforeLHS);
351 Extra = OldExtra;
Chris Lattner7312a222010-12-13 04:50:38 +0000352 }
353
Chris Lattner0d560082004-02-24 05:38:11 +0000354 return 0;
355}
Chris Lattner0aa749b2010-12-13 04:26:26 +0000356
Eli Friedman080efb82008-12-16 20:54:32 +0000357static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
358 Instruction* Cond = 0;
359 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
360 Cond = dyn_cast<Instruction>(SI->getCondition());
361 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
362 if (BI->isConditional())
363 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel7ac40c32010-12-05 18:29:03 +0000364 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
365 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedman080efb82008-12-16 20:54:32 +0000366 }
367
368 TI->eraseFromParent();
369 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
370}
371
Chris Lattner9fd49552008-11-27 23:25:44 +0000372/// isValueEqualityComparison - Return true if the specified terminator checks
373/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000374Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
375 Value *CV = 0;
Chris Lattner4bebf082004-03-16 19:45:22 +0000376 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
377 // Do not permit merging of large switch instructions into their
378 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000379 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
380 pred_end(SI->getParent())) <= 128)
381 CV = SI->getCondition();
382 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattner542f1492004-02-28 21:28:10 +0000383 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000384 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
385 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
386 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
Chris Lattner28acc132010-12-13 03:30:12 +0000387 GetConstantInt(ICI->getOperand(1), TD))
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000388 CV = ICI->getOperand(0);
389
390 // Unwrap any lossless ptrtoint cast.
391 if (TD && CV && CV->getType() == TD->getIntPtrType(CV->getContext()))
392 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV))
393 CV = PTII->getOperand(0);
394 return CV;
Chris Lattner542f1492004-02-28 21:28:10 +0000395}
396
Bill Wendling5049fa62009-01-19 23:43:56 +0000397/// GetValueEqualityComparisonCases - Given a value comparison instruction,
398/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000399BasicBlock *SimplifyCFGOpt::
Misha Brukmanfd939082005-04-21 23:48:37 +0000400GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000401 std::vector<std::pair<ConstantInt*,
402 BasicBlock*> > &Cases) {
403 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
404 Cases.reserve(SI->getNumCases());
405 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000406 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000407 return SI->getDefaultDest();
408 }
409
410 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000411 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Chris Lattner28acc132010-12-13 03:30:12 +0000412 Cases.push_back(std::make_pair(GetConstantInt(ICI->getOperand(1), TD),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000413 BI->getSuccessor(ICI->getPredicate() ==
414 ICmpInst::ICMP_NE)));
415 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000416}
417
418
Bill Wendling5049fa62009-01-19 23:43:56 +0000419/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
420/// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000421static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000422 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
423 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
424 if (Cases[i].second == BB) {
425 Cases.erase(Cases.begin()+i);
426 --i; --e;
427 }
428}
429
Bill Wendling5049fa62009-01-19 23:43:56 +0000430/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
431/// well.
Chris Lattner623369a2005-02-24 06:17:52 +0000432static bool
433ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
434 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
435 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
436
437 // Make V1 be smaller than V2.
438 if (V1->size() > V2->size())
439 std::swap(V1, V2);
440
441 if (V1->size() == 0) return false;
442 if (V1->size() == 1) {
443 // Just scan V2.
444 ConstantInt *TheVal = (*V1)[0].first;
445 for (unsigned i = 0, e = V2->size(); i != e; ++i)
446 if (TheVal == (*V2)[i].first)
447 return true;
448 }
449
450 // Otherwise, just sort both lists and compare element by element.
Chris Lattnerfca20f52010-12-13 03:24:30 +0000451 array_pod_sort(V1->begin(), V1->end());
452 array_pod_sort(V2->begin(), V2->end());
Chris Lattner623369a2005-02-24 06:17:52 +0000453 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
454 while (i1 != e1 && i2 != e2) {
455 if ((*V1)[i1].first == (*V2)[i2].first)
456 return true;
457 if ((*V1)[i1].first < (*V2)[i2].first)
458 ++i1;
459 else
460 ++i2;
461 }
462 return false;
463}
464
Bill Wendling5049fa62009-01-19 23:43:56 +0000465/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
466/// terminator instruction and its block is known to only have a single
467/// predecessor block, check to see if that predecessor is also a value
468/// comparison with the same value, and if that comparison determines the
469/// outcome of this comparison. If so, simplify TI. This does a very limited
470/// form of jump threading.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000471bool SimplifyCFGOpt::
472SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
473 BasicBlock *Pred) {
Chris Lattner623369a2005-02-24 06:17:52 +0000474 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
475 if (!PredVal) return false; // Not a value comparison in predecessor.
476
477 Value *ThisVal = isValueEqualityComparison(TI);
478 assert(ThisVal && "This isn't a value comparison!!");
479 if (ThisVal != PredVal) return false; // Different predicates.
480
481 // Find out information about when control will move from Pred to TI's block.
482 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
483 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
484 PredCases);
485 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000486
Chris Lattner623369a2005-02-24 06:17:52 +0000487 // Find information about how control leaves this block.
488 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
489 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
490 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
491
492 // If TI's block is the default block from Pred's comparison, potentially
493 // simplify TI based on this knowledge.
494 if (PredDef == TI->getParent()) {
495 // If we are here, we know that the value is none of those cases listed in
496 // PredCases. If there are any cases in ThisCases that are in PredCases, we
497 // can simplify TI.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000498 if (!ValuesOverlap(PredCases, ThisCases))
499 return false;
500
501 if (isa<BranchInst>(TI)) {
502 // Okay, one of the successors of this condbr is dead. Convert it to a
503 // uncond br.
504 assert(ThisCases.size() == 1 && "Branch can only have one case!");
505 // Insert the new branch.
506 Instruction *NI = BranchInst::Create(ThisDef, TI);
507 (void) NI;
Chris Lattner623369a2005-02-24 06:17:52 +0000508
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000509 // Remove PHI node entries for the dead edge.
510 ThisCases[0].second->removePredecessor(TI->getParent());
Chris Lattner623369a2005-02-24 06:17:52 +0000511
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000512 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
513 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000514
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000515 EraseTerminatorInstAndDCECond(TI);
516 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000517 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000518
519 SwitchInst *SI = cast<SwitchInst>(TI);
520 // Okay, TI has cases that are statically dead, prune them away.
521 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000522 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000523 DeadCases.insert(PredCases[i].first);
Chris Lattner623369a2005-02-24 06:17:52 +0000524
David Greene89d6fd32010-01-05 01:26:52 +0000525 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000526 << "Through successor TI: " << *TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000527
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000528 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
529 if (DeadCases.count(SI->getCaseValue(i))) {
530 SI->getSuccessor(i)->removePredecessor(TI->getParent());
531 SI->removeCase(i);
532 }
533
534 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner623369a2005-02-24 06:17:52 +0000535 return true;
536 }
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000537
538 // Otherwise, TI's block must correspond to some matched value. Find out
539 // which value (or set of values) this is.
540 ConstantInt *TIV = 0;
541 BasicBlock *TIBB = TI->getParent();
542 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
543 if (PredCases[i].second == TIBB) {
544 if (TIV != 0)
545 return false; // Cannot handle multiple values coming to this block.
546 TIV = PredCases[i].first;
547 }
548 assert(TIV && "No edge from pred to succ?");
549
550 // Okay, we found the one constant that our value can be if we get into TI's
551 // BB. Find out which successor will unconditionally be branched to.
552 BasicBlock *TheRealDest = 0;
553 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
554 if (ThisCases[i].first == TIV) {
555 TheRealDest = ThisCases[i].second;
556 break;
557 }
558
559 // If not handled by any explicit cases, it is handled by the default case.
560 if (TheRealDest == 0) TheRealDest = ThisDef;
561
562 // Remove PHI node entries for dead edges.
563 BasicBlock *CheckEdge = TheRealDest;
564 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
565 if (*SI != CheckEdge)
566 (*SI)->removePredecessor(TIBB);
567 else
568 CheckEdge = 0;
569
570 // Insert the new branch.
571 Instruction *NI = BranchInst::Create(TheRealDest, TI);
572 (void) NI;
573
574 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
575 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
576
577 EraseTerminatorInstAndDCECond(TI);
578 return true;
Chris Lattner623369a2005-02-24 06:17:52 +0000579}
580
Dale Johannesenc81f5442009-03-12 21:01:11 +0000581namespace {
582 /// ConstantIntOrdering - This class implements a stable ordering of constant
583 /// integers that does not depend on their address. This is important for
584 /// applications that sort ConstantInt's to ensure uniqueness.
585 struct ConstantIntOrdering {
586 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
587 return LHS->getValue().ult(RHS->getValue());
588 }
589 };
590}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000591
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000592static int ConstantIntSortPredicate(const void *P1, const void *P2) {
593 const ConstantInt *LHS = *(const ConstantInt**)P1;
594 const ConstantInt *RHS = *(const ConstantInt**)P2;
Benjamin Kramercf8b3252010-12-13 18:20:38 +0000595 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner6d4d21e2010-12-13 02:00:58 +0000596}
597
Bill Wendling5049fa62009-01-19 23:43:56 +0000598/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
599/// equality comparison instruction (either a switch or a branch on "X == c").
600/// See if any of the predecessors of the terminator block are value comparisons
601/// on the same value. If so, and if safe to do so, fold them together.
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000602bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
Chris Lattner542f1492004-02-28 21:28:10 +0000603 BasicBlock *BB = TI->getParent();
604 Value *CV = isValueEqualityComparison(TI); // CondVal
605 assert(CV && "Not a comparison?");
606 bool Changed = false;
607
Chris Lattner82442432008-02-18 07:42:56 +0000608 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000609 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000610 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000611
Chris Lattner542f1492004-02-28 21:28:10 +0000612 // See if the predecessor is a comparison with the same value.
613 TerminatorInst *PTI = Pred->getTerminator();
614 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
615
616 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
617 // Figure out which 'cases' to copy from SI to PSI.
618 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
619 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
620
621 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
622 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
623
624 // Based on whether the default edge from PTI goes to BB or not, fill in
625 // PredCases and PredDefault with the new switch cases we would like to
626 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000627 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000628
629 if (PredDefault == BB) {
630 // If this is the default destination from PTI, only the edges in TI
631 // that don't occur in PTI, or that branch to BB will be activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000632 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000633 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
634 if (PredCases[i].second != BB)
635 PTIHandled.insert(PredCases[i].first);
636 else {
637 // The default destination is BB, we don't need explicit targets.
638 std::swap(PredCases[i], PredCases.back());
639 PredCases.pop_back();
640 --i; --e;
641 }
642
643 // Reconstruct the new switch statement we will be building.
644 if (PredDefault != BBDefault) {
645 PredDefault->removePredecessor(Pred);
646 PredDefault = BBDefault;
647 NewSuccessors.push_back(BBDefault);
648 }
649 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
650 if (!PTIHandled.count(BBCases[i].first) &&
651 BBCases[i].second != BBDefault) {
652 PredCases.push_back(BBCases[i]);
653 NewSuccessors.push_back(BBCases[i].second);
654 }
655
656 } else {
657 // If this is not the default destination from PSI, only the edges
658 // in SI that occur in PSI with a destination of BB will be
659 // activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000660 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000661 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
662 if (PredCases[i].second == BB) {
663 PTIHandled.insert(PredCases[i].first);
664 std::swap(PredCases[i], PredCases.back());
665 PredCases.pop_back();
666 --i; --e;
667 }
668
669 // Okay, now we know which constants were sent to BB from the
670 // predecessor. Figure out where they will all go now.
671 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
672 if (PTIHandled.count(BBCases[i].first)) {
673 // If this is one we are capable of getting...
674 PredCases.push_back(BBCases[i]);
675 NewSuccessors.push_back(BBCases[i].second);
676 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
677 }
678
679 // If there are any constants vectored to BB that TI doesn't handle,
680 // they must go to the default destination of TI.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000681 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
682 PTIHandled.begin(),
Chris Lattner542f1492004-02-28 21:28:10 +0000683 E = PTIHandled.end(); I != E; ++I) {
684 PredCases.push_back(std::make_pair(*I, BBDefault));
685 NewSuccessors.push_back(BBDefault);
686 }
687 }
688
689 // Okay, at this point, we know which new successor Pred will get. Make
690 // sure we update the number of entries in the PHI nodes for these
691 // successors.
692 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
693 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
694
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000695 // Convert pointer to int before we switch.
Duncan Sands1df98592010-02-16 11:11:14 +0000696 if (CV->getType()->isPointerTy()) {
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +0000697 assert(TD && "Cannot switch on pointer without TargetData");
698 CV = new PtrToIntInst(CV, TD->getIntPtrType(CV->getContext()),
699 "magicptr", PTI);
700 }
701
Chris Lattner542f1492004-02-28 21:28:10 +0000702 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000703 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
704 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000705 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
706 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000707
Eli Friedman080efb82008-12-16 20:54:32 +0000708 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000709
Chris Lattner542f1492004-02-28 21:28:10 +0000710 // Okay, last check. If BB is still a successor of PSI, then we must
711 // have an infinite loop case. If so, add an infinitely looping block
712 // to handle the case to preserve the behavior of the code.
713 BasicBlock *InfLoopBlock = 0;
714 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
715 if (NewSI->getSuccessor(i) == BB) {
716 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000717 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000718 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +0000719 InfLoopBlock = BasicBlock::Create(BB->getContext(),
720 "infloop", BB->getParent());
Gabor Greif051a9502008-04-06 20:25:17 +0000721 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000722 }
723 NewSI->setSuccessor(i, InfLoopBlock);
724 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000725
Chris Lattner542f1492004-02-28 21:28:10 +0000726 Changed = true;
727 }
728 }
729 return Changed;
730}
731
Dale Johannesenc1f10402009-06-15 20:59:27 +0000732// isSafeToHoistInvoke - If we would need to insert a select that uses the
733// value of this invoke (comments in HoistThenElseCodeToIf explain why we
734// would need to do this), we can't hoist the invoke, as there is nowhere
735// to put the select in this case.
736static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
737 Instruction *I1, Instruction *I2) {
738 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
739 PHINode *PN;
740 for (BasicBlock::iterator BBI = SI->begin();
741 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
742 Value *BB1V = PN->getIncomingValueForBlock(BB1);
743 Value *BB2V = PN->getIncomingValueForBlock(BB2);
744 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
745 return false;
746 }
747 }
748 }
749 return true;
750}
751
Chris Lattner6306d072005-08-03 17:59:45 +0000752/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000753/// BB2, hoist any common code in the two blocks up into the branch block. The
754/// caller of this function guarantees that BI's block dominates BB1 and BB2.
755static bool HoistThenElseCodeToIf(BranchInst *BI) {
756 // This does very trivial matching, with limited scanning, to find identical
757 // instructions in the two blocks. In particular, we don't want to get into
758 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
759 // such, we currently just scan for obviously identical instructions in an
760 // identical order.
761 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
762 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
763
Devang Patel65085cf2009-02-04 00:03:08 +0000764 BasicBlock::iterator BB1_Itr = BB1->begin();
765 BasicBlock::iterator BB2_Itr = BB2->begin();
766
767 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
768 while (isa<DbgInfoIntrinsic>(I1))
769 I1 = BB1_Itr++;
770 while (isa<DbgInfoIntrinsic>(I2))
771 I2 = BB2_Itr++;
Dale Johannesenc1f10402009-06-15 20:59:27 +0000772 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000773 !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesenc1f10402009-06-15 20:59:27 +0000774 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000775 return false;
776
777 // If we get here, we can hoist at least one instruction.
778 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000779
780 do {
781 // If we are hoisting the terminator instruction, don't move one (making a
782 // broken BB), instead clone it, and remove BI.
783 if (isa<TerminatorInst>(I1))
784 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000785
Chris Lattner37dc9382004-11-30 00:29:14 +0000786 // For a normal instruction, we just move one to right before the branch,
787 // then replace all uses of the other with the first. Finally, we remove
788 // the now redundant second instruction.
789 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
790 if (!I2->use_empty())
791 I2->replaceAllUsesWith(I1);
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000792 I1->intersectOptionalDataWith(I2);
Chris Lattner302ba6f2010-12-14 06:17:25 +0000793 I2->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000794
Devang Patel65085cf2009-02-04 00:03:08 +0000795 I1 = BB1_Itr++;
796 while (isa<DbgInfoIntrinsic>(I1))
797 I1 = BB1_Itr++;
798 I2 = BB2_Itr++;
799 while (isa<DbgInfoIntrinsic>(I2))
800 I2 = BB2_Itr++;
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000801 } while (I1->getOpcode() == I2->getOpcode() &&
802 I1->isIdenticalToWhenDefined(I2));
Chris Lattner37dc9382004-11-30 00:29:14 +0000803
804 return true;
805
806HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000807 // It may not be possible to hoist an invoke.
808 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
809 return true;
810
Chris Lattner37dc9382004-11-30 00:29:14 +0000811 // Okay, it is safe to hoist the terminator.
Nick Lewycky67760642009-09-27 07:38:41 +0000812 Instruction *NT = I1->clone();
Chris Lattner37dc9382004-11-30 00:29:14 +0000813 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerf0127052010-01-05 13:12:22 +0000814 if (!NT->getType()->isVoidTy()) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000815 I1->replaceAllUsesWith(NT);
816 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000817 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000818 }
819
820 // Hoisting one of the terminators from our successor is a great thing.
821 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
822 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
823 // nodes, so we insert select instruction to compute the final result.
824 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
825 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
826 PHINode *PN;
827 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000828 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000829 Value *BB1V = PN->getIncomingValueForBlock(BB1);
830 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000831 if (BB1V == BB2V) continue;
832
833 // These values do not agree. Insert a select instruction before NT
834 // that determines the right value.
835 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
836 if (SI == 0)
837 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
838 BB1V->getName()+"."+BB2V->getName(), NT);
839 // Make the PHI node use the select for all incoming values for BB1/BB2
840 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
841 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
842 PN->setIncomingValue(i, SI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000843 }
844 }
845
846 // Update any PHI nodes in our new successors.
847 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
848 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000849
Eli Friedman080efb82008-12-16 20:54:32 +0000850 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000851 return true;
852}
853
Evan Cheng4d09efd2008-06-07 08:52:29 +0000854/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
855/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
856/// (for now, restricted to a single instruction that's side effect free) from
857/// the BB1 into the branch block to speculatively execute it.
858static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
859 // Only speculatively execution a single instruction (not counting the
860 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000861 Instruction *HInst = NULL;
862 Instruction *Term = BB1->getTerminator();
863 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
864 BBI != BBE; ++BBI) {
865 Instruction *I = BBI;
866 // Skip debug info.
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000867 if (isa<DbgInfoIntrinsic>(I)) continue;
868 if (I == Term) break;
Devang Patel06b1e672009-03-06 06:00:17 +0000869
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000870 if (HInst)
Devang Patel06b1e672009-03-06 06:00:17 +0000871 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000872 HInst = I;
Devang Patel06b1e672009-03-06 06:00:17 +0000873 }
874 if (!HInst)
875 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000876
Evan Cheng797d9512008-06-11 19:18:20 +0000877 // Be conservative for now. FP select instruction can often be expensive.
878 Value *BrCond = BI->getCondition();
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000879 if (isa<FCmpInst>(BrCond))
Evan Cheng797d9512008-06-11 19:18:20 +0000880 return false;
881
Evan Cheng4d09efd2008-06-07 08:52:29 +0000882 // If BB1 is actually on the false edge of the conditional branch, remember
883 // to swap the select operands later.
884 bool Invert = false;
885 if (BB1 != BI->getSuccessor(0)) {
886 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
887 Invert = true;
888 }
889
890 // Turn
891 // BB:
892 // %t1 = icmp
893 // br i1 %t1, label %BB1, label %BB2
894 // BB1:
895 // %t3 = add %t2, c
896 // br label BB2
897 // BB2:
898 // =>
899 // BB:
900 // %t1 = icmp
901 // %t4 = add %t2, c
902 // %t3 = select i1 %t1, %t2, %t3
Devang Patel06b1e672009-03-06 06:00:17 +0000903 switch (HInst->getOpcode()) {
Evan Cheng4d09efd2008-06-07 08:52:29 +0000904 default: return false; // Not safe / profitable to hoist.
905 case Instruction::Add:
906 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000907 // Not worth doing for vector ops.
Duncan Sands1df98592010-02-16 11:11:14 +0000908 if (HInst->getType()->isVectorTy())
Chris Lattner9dd3b612009-01-18 23:22:07 +0000909 return false;
910 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000911 case Instruction::And:
912 case Instruction::Or:
913 case Instruction::Xor:
914 case Instruction::Shl:
915 case Instruction::LShr:
916 case Instruction::AShr:
Chris Lattner9dd3b612009-01-18 23:22:07 +0000917 // Don't mess with vector operations.
Duncan Sands1df98592010-02-16 11:11:14 +0000918 if (HInst->getType()->isVectorTy())
Evan Chenge5334ea2008-06-25 07:50:12 +0000919 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000920 break; // These are all cheap and non-trapping instructions.
921 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000922
923 // If the instruction is obviously dead, don't try to predicate it.
Devang Patel06b1e672009-03-06 06:00:17 +0000924 if (HInst->use_empty()) {
925 HInst->eraseFromParent();
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000926 return true;
927 }
Evan Cheng4d09efd2008-06-07 08:52:29 +0000928
929 // Can we speculatively execute the instruction? And what is the value
930 // if the condition is false? Consider the phi uses, if the incoming value
931 // from the "if" block are all the same V, then V is the value of the
932 // select if the condition is false.
933 BasicBlock *BIParent = BI->getParent();
934 SmallVector<PHINode*, 4> PHIUses;
935 Value *FalseV = NULL;
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000936
937 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Devang Patel06b1e672009-03-06 06:00:17 +0000938 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
Evan Cheng4d09efd2008-06-07 08:52:29 +0000939 UI != E; ++UI) {
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000940 // Ignore any user that is not a PHI node in BB2. These can only occur in
941 // unreachable blocks, because they would not be dominated by the instr.
Gabor Greif20361b92010-07-22 11:43:44 +0000942 PHINode *PN = dyn_cast<PHINode>(*UI);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000943 if (!PN || PN->getParent() != BB2)
944 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +0000945 PHIUses.push_back(PN);
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000946
Evan Cheng4d09efd2008-06-07 08:52:29 +0000947 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
948 if (!FalseV)
949 FalseV = PHIV;
950 else if (FalseV != PHIV)
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000951 return false; // Inconsistent value when condition is false.
Evan Cheng4d09efd2008-06-07 08:52:29 +0000952 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +0000953
954 assert(FalseV && "Must have at least one user, and it must be a PHI");
Evan Cheng4d09efd2008-06-07 08:52:29 +0000955
Evan Cheng502a4f52008-06-12 21:15:59 +0000956 // Do not hoist the instruction if any of its operands are defined but not
957 // used in this BB. The transformation will prevent the operand from
958 // being sunk into the use block.
Devang Patel06b1e672009-03-06 06:00:17 +0000959 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
960 i != e; ++i) {
Evan Cheng502a4f52008-06-12 21:15:59 +0000961 Instruction *OpI = dyn_cast<Instruction>(*i);
962 if (OpI && OpI->getParent() == BIParent &&
963 !OpI->isUsedInBasicBlock(BIParent))
964 return false;
965 }
966
Devang Patel3d0a9a32008-09-18 22:50:42 +0000967 // If we get here, we can hoist the instruction. Try to place it
Dale Johannesen990afed2009-03-13 01:05:24 +0000968 // before the icmp instruction preceding the conditional branch.
Devang Patel3d0a9a32008-09-18 22:50:42 +0000969 BasicBlock::iterator InsertPos = BI;
Dale Johannesen990afed2009-03-13 01:05:24 +0000970 if (InsertPos != BIParent->begin())
971 --InsertPos;
972 // Skip debug info between condition and branch.
973 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
Devang Patel3d0a9a32008-09-18 22:50:42 +0000974 --InsertPos;
Devang Patel20da1f02008-10-03 18:57:37 +0000975 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
Devang Patel3d0a9a32008-09-18 22:50:42 +0000976 SmallPtrSet<Instruction *, 4> BB1Insns;
977 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
978 BB1I != BB1E; ++BB1I)
979 BB1Insns.insert(BB1I);
980 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
981 UI != UE; ++UI) {
982 Instruction *Use = cast<Instruction>(*UI);
Chris Lattner9a2b72a2010-12-13 01:47:07 +0000983 if (!BB1Insns.count(Use)) continue;
984
985 // If BrCond uses the instruction that place it just before
986 // branch instruction.
987 InsertPos = BI;
988 break;
Devang Patel3d0a9a32008-09-18 22:50:42 +0000989 }
990 } else
991 InsertPos = BI;
Devang Patel06b1e672009-03-06 06:00:17 +0000992 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
Evan Cheng4d09efd2008-06-07 08:52:29 +0000993
994 // Create a select whose true value is the speculatively executed value and
995 // false value is the previously determined FalseV.
996 SelectInst *SI;
997 if (Invert)
Devang Patel06b1e672009-03-06 06:00:17 +0000998 SI = SelectInst::Create(BrCond, FalseV, HInst,
999 FalseV->getName() + "." + HInst->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001000 else
Devang Patel06b1e672009-03-06 06:00:17 +00001001 SI = SelectInst::Create(BrCond, HInst, FalseV,
1002 HInst->getName() + "." + FalseV->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001003
1004 // Make the PHI node use the select for all incoming values for "then" and
1005 // "if" blocks.
1006 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1007 PHINode *PN = PHIUses[i];
1008 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001009 if (PN->getIncomingBlock(j) == BB1 || PN->getIncomingBlock(j) == BIParent)
Evan Cheng4d09efd2008-06-07 08:52:29 +00001010 PN->setIncomingValue(j, SI);
1011 }
1012
Evan Cheng502a4f52008-06-12 21:15:59 +00001013 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001014 return true;
1015}
1016
Chris Lattner2e42e362005-09-20 00:43:16 +00001017/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1018/// across this block.
1019static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1020 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001021 unsigned Size = 0;
1022
Devang Patel9200c892009-03-10 18:00:05 +00001023 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001024 if (isa<DbgInfoIntrinsic>(BBI))
1025 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001026 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001027 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001028
Dale Johannesen8483e542009-03-12 23:18:09 +00001029 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001030 // live outside of the current basic block.
1031 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1032 UI != E; ++UI) {
1033 Instruction *U = cast<Instruction>(*UI);
1034 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1035 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001036
1037 // Looks ok, continue checking.
1038 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001039
Chris Lattner2e42e362005-09-20 00:43:16 +00001040 return true;
1041}
1042
Chris Lattnereaba3a12005-09-19 23:49:37 +00001043/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1044/// that is defined in the same block as the branch and if any PHI entries are
1045/// constants, thread edges corresponding to that entry to be branches to their
1046/// ultimate destination.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001047static bool FoldCondBranchOnPHI(BranchInst *BI, const TargetData *TD) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001048 BasicBlock *BB = BI->getParent();
1049 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001050 // NOTE: we currently cannot transform this case if the PHI node is used
1051 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001052 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1053 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001054
1055 // Degenerate case of a single entry PHI.
1056 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001057 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001058 return true;
1059 }
1060
1061 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001062 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001063
1064 // Okay, this is a simple enough basic block. See if any phi values are
1065 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001066 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001067 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
1068 if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
1069
1070 // Okay, we now know that all edges from PredBB should be revectored to
1071 // branch to RealDest.
1072 BasicBlock *PredBB = PN->getIncomingBlock(i);
1073 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
1074
1075 if (RealDest == BB) continue; // Skip self loops.
1076
1077 // The dest block might have PHI nodes, other predecessors and other
1078 // difficult cases. Instead of being smart about this, just insert a new
1079 // block that jumps to the destination block, effectively splitting
1080 // the edge we are about to create.
1081 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1082 RealDest->getName()+".critedge",
1083 RealDest->getParent(), RealDest);
1084 BranchInst::Create(RealDest, EdgeBB);
Chris Lattner6de0a282010-12-14 07:09:42 +00001085
1086 // Update PHI nodes.
1087 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001088
1089 // BB may have instructions that are being threaded over. Clone these
1090 // instructions into EdgeBB. We know that there will be no uses of the
1091 // cloned instructions outside of EdgeBB.
1092 BasicBlock::iterator InsertPt = EdgeBB->begin();
1093 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1094 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1095 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1096 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1097 continue;
1098 }
1099 // Clone the instruction.
1100 Instruction *N = BBI->clone();
1101 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1102
1103 // Update operands due to translation.
1104 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1105 i != e; ++i) {
1106 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1107 if (PI != TranslateMap.end())
1108 *i = PI->second;
1109 }
1110
1111 // Check for trivial simplification.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001112 if (Value *V = SimplifyInstruction(N, TD)) {
1113 TranslateMap[BBI] = V;
1114 delete N; // Instruction folded away, don't need actual inst
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001115 } else {
1116 // Insert the new instruction into its new home.
1117 EdgeBB->getInstList().insert(InsertPt, N);
1118 if (!BBI->use_empty())
1119 TranslateMap[BBI] = N;
1120 }
1121 }
1122
1123 // Loop over all of the edges from PredBB to BB, changing them to branch
1124 // to EdgeBB instead.
1125 TerminatorInst *PredBBTI = PredBB->getTerminator();
1126 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1127 if (PredBBTI->getSuccessor(i) == BB) {
1128 BB->removePredecessor(PredBB);
1129 PredBBTI->setSuccessor(i, EdgeBB);
1130 }
1131
1132 // Recurse, simplifying any other constants.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001133 return FoldCondBranchOnPHI(BI, TD) | true;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001134 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001135
1136 return false;
1137}
1138
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001139/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1140/// PHI node, see if we can eliminate it.
Chris Lattner73c50a62010-12-14 07:00:00 +00001141static bool FoldTwoEntryPHINode(PHINode *PN, const TargetData *TD) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001142 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1143 // statement", which has a very simple dominance structure. Basically, we
1144 // are trying to find the condition that is being branched on, which
1145 // subsequently causes this merge to happen. We really want control
1146 // dependence information for this check, but simplifycfg can't keep it up
1147 // to date, and this catches most of the cases we care about anyway.
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001148 BasicBlock *BB = PN->getParent();
1149 BasicBlock *IfTrue, *IfFalse;
1150 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner60d410d2010-12-14 08:01:53 +00001151 if (!IfCond ||
1152 // Don't bother if the branch will be constant folded trivially.
1153 isa<ConstantInt>(IfCond))
1154 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001155
Chris Lattner822a8792006-11-18 19:19:36 +00001156 // Okay, we found that we can merge this two-entry phi node into a select.
1157 // Doing so would require us to fold *all* two entry phi nodes in this block.
1158 // At some point this becomes non-profitable (particularly if the target
1159 // doesn't support cmov's). Only do this transformation if there are two or
1160 // fewer PHI nodes in this block.
1161 unsigned NumPhis = 0;
1162 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1163 if (NumPhis > 2)
1164 return false;
1165
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001166 // Loop over the PHI's seeing if we can promote them all to select
1167 // instructions. While we are at it, keep track of the instructions
1168 // that need to be moved to the dominating block.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001169 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001170
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001171 BasicBlock::iterator AfterPHIIt = BB->begin();
1172 while (isa<PHINode>(AfterPHIIt)) {
1173 PHINode *PN = cast<PHINode>(AfterPHIIt++);
Chris Lattner07ff3532010-12-14 07:20:29 +00001174 if (Value *V = SimplifyInstruction(PN, TD)) {
1175 PN->replaceAllUsesWith(V);
1176 continue;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001177 }
Chris Lattner07ff3532010-12-14 07:20:29 +00001178
1179 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts) ||
1180 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts))
1181 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001182 }
1183
Chris Lattner44da7ca2010-12-14 07:41:39 +00001184 // If we folded the the first phi, PN dangles at this point. Refresh it. If
1185 // we ran out of PHIs then we simplified them all.
1186 PN = dyn_cast<PHINode>(BB->begin());
1187 if (PN == 0) return true;
1188
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001189 // If we all PHI nodes are promotable, check to make sure that all
1190 // instructions in the predecessor blocks can be promoted as well. If
1191 // not, we won't be able to get rid of the control flow, so it's not
1192 // worth promoting to select instructions.
Chris Lattner44da7ca2010-12-14 07:41:39 +00001193 BasicBlock *DomBlock = 0;
1194 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1195 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1196 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
1197 IfBlock1 = 0;
1198 } else {
1199 DomBlock = *pred_begin(IfBlock1);
1200 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001201 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001202 // This is not an aggressive instruction that we can promote.
1203 // Because of this, we won't be able to get rid of the control
1204 // flow, so the xform is not worth it.
1205 return false;
1206 }
1207 }
1208
Chris Lattner44da7ca2010-12-14 07:41:39 +00001209 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
1210 IfBlock2 = 0;
1211 } else {
1212 DomBlock = *pred_begin(IfBlock2);
1213 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001214 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001215 // This is not an aggressive instruction that we can promote.
1216 // Because of this, we won't be able to get rid of the control
1217 // flow, so the xform is not worth it.
1218 return false;
1219 }
1220 }
Chris Lattnere0b18e52010-12-14 07:23:10 +00001221
1222 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner44da7ca2010-12-14 07:41:39 +00001223 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001224
1225 // If we can still promote the PHI nodes after this gauntlet of tests,
1226 // do all of the PHI's now.
1227
1228 // Move all 'aggressive' instructions, which are defined in the
1229 // conditional parts of the if's up to the dominating block.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001230 if (IfBlock1)
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001231 DomBlock->getInstList().splice(DomBlock->getTerminator(),
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001232 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001233 IfBlock1->getTerminator());
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001234 if (IfBlock2)
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001235 DomBlock->getInstList().splice(DomBlock->getTerminator(),
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001236 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001237 IfBlock2->getTerminator());
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001238
1239 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1240 // Change the PHI node into a select instruction.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001241 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1242 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001243
Chris Lattner071edc82010-12-14 07:53:03 +00001244 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001245 PN->replaceAllUsesWith(NV);
1246 NV->takeName(PN);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001247 PN->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001248 }
Chris Lattner60d410d2010-12-14 08:01:53 +00001249
1250 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1251 // has been flattened. Change DomBlock to jump directly to our new block to
1252 // avoid other simplifycfg's kicking in on the diamond.
1253 TerminatorInst *OldTI = DomBlock->getTerminator();
1254 BranchInst::Create(BB, OldTI);
1255 OldTI->eraseFromParent();
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001256 return true;
1257}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001258
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001259/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1260/// to two returning blocks, try to merge them together into one return,
1261/// introducing a select if the return values disagree.
1262static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1263 assert(BI->isConditional() && "Must be a conditional branch");
1264 BasicBlock *TrueSucc = BI->getSuccessor(0);
1265 BasicBlock *FalseSucc = BI->getSuccessor(1);
1266 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1267 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1268
1269 // Check to ensure both blocks are empty (just a return) or optionally empty
1270 // with PHI nodes. If there are other instructions, merging would cause extra
1271 // computation on one path or the other.
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001272 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001273 return false;
Chris Lattner9a2b72a2010-12-13 01:47:07 +00001274 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel2cc86a12009-02-05 00:30:42 +00001275 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001276
1277 // Okay, we found a branch that is going to two return nodes. If
1278 // there is no return value for this function, just change the
1279 // branch into a return.
1280 if (FalseRet->getNumOperands() == 0) {
1281 TrueSucc->removePredecessor(BI->getParent());
1282 FalseSucc->removePredecessor(BI->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +00001283 ReturnInst::Create(BI->getContext(), 0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001284 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001285 return true;
1286 }
1287
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001288 // Otherwise, figure out what the true and false return values are
1289 // so we can insert a new select instruction.
1290 Value *TrueValue = TrueRet->getReturnValue();
1291 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001292
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001293 // Unwrap any PHI nodes in the return blocks.
1294 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1295 if (TVPN->getParent() == TrueSucc)
1296 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1297 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1298 if (FVPN->getParent() == FalseSucc)
1299 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1300
1301 // In order for this transformation to be safe, we must be able to
1302 // unconditionally execute both operands to the return. This is
1303 // normally the case, but we could have a potentially-trapping
1304 // constant expression that prevents this transformation from being
1305 // safe.
1306 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1307 if (TCV->canTrap())
1308 return false;
1309 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1310 if (FCV->canTrap())
1311 return false;
1312
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001313 // Okay, we collected all the mapped values and checked them for sanity, and
1314 // defined to really do this transformation. First, update the CFG.
1315 TrueSucc->removePredecessor(BI->getParent());
1316 FalseSucc->removePredecessor(BI->getParent());
1317
1318 // Insert select instructions where needed.
1319 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001320 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001321 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001322 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1323 } else if (isa<UndefValue>(TrueValue)) {
1324 TrueValue = FalseValue;
1325 } else {
1326 TrueValue = SelectInst::Create(BrCond, TrueValue,
1327 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001328 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001329 }
1330
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001331 Value *RI = !TrueValue ?
Owen Anderson1d0be152009-08-13 21:58:54 +00001332 ReturnInst::Create(BI->getContext(), BI) :
1333 ReturnInst::Create(BI->getContext(), TrueValue, BI);
Daniel Dunbare317bcc2009-08-23 10:29:55 +00001334 (void) RI;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001335
David Greene89d6fd32010-01-05 01:26:52 +00001336 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerbdff5482009-08-23 04:37:46 +00001337 << "\n " << *BI << "NewRet = " << *RI
1338 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001339
Eli Friedman080efb82008-12-16 20:54:32 +00001340 EraseTerminatorInstAndDCECond(BI);
1341
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001342 return true;
1343}
1344
Chris Lattner1347e872008-07-13 21:12:01 +00001345/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1346/// and if a predecessor branches to us and one of our successors, fold the
1347/// setcc into the predecessor and use logical operations to pick the right
1348/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001349bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001350 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001351 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Owen Andersone84178a2010-07-14 19:52:16 +00001352 if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
1353 Cond->getParent() != BB || !Cond->hasOneUse())
1354 return false;
Chris Lattner093a4382008-07-13 22:23:11 +00001355
Chris Lattner1347e872008-07-13 21:12:01 +00001356 // Only allow this if the condition is a simple instruction that can be
1357 // executed unconditionally. It must be in the same block as the branch, and
1358 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001359 BasicBlock::iterator FrontIt = BB->front();
1360 // Ignore dbg intrinsics.
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001361 while (isa<DbgInfoIntrinsic>(FrontIt))
Devang Pateld0a203d2009-02-04 21:39:48 +00001362 ++FrontIt;
Owen Andersone84178a2010-07-14 19:52:16 +00001363
1364 // Allow a single instruction to be hoisted in addition to the compare
1365 // that feeds the branch. We later ensure that any values that _it_ uses
1366 // were also live in the predecessor, so that we don't unnecessarily create
1367 // register pressure or inhibit out-of-order execution.
1368 Instruction *BonusInst = 0;
1369 if (&*FrontIt != Cond &&
Owen Anderson2722dfa2010-07-15 16:38:22 +00001370 FrontIt->hasOneUse() && *FrontIt->use_begin() == Cond &&
1371 FrontIt->isSafeToSpeculativelyExecute()) {
Owen Andersone84178a2010-07-14 19:52:16 +00001372 BonusInst = &*FrontIt;
1373 ++FrontIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001374 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001375
Owen Andersone84178a2010-07-14 19:52:16 +00001376 // Only a single bonus inst is allowed.
1377 if (&*FrontIt != Cond)
1378 return false;
1379
Chris Lattner1347e872008-07-13 21:12:01 +00001380 // Make sure the instruction after the condition is the cond branch.
1381 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001382 // Ingore dbg intrinsics.
1383 while(isa<DbgInfoIntrinsic>(CondIt))
1384 ++CondIt;
1385 if (&*CondIt != BI) {
1386 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001387 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001388 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001389
1390 // Cond is known to be a compare or binary operator. Check to make sure that
1391 // neither operand is a potentially-trapping constant expression.
1392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1393 if (CE->canTrap())
1394 return false;
1395 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1396 if (CE->canTrap())
1397 return false;
1398
Chris Lattner1347e872008-07-13 21:12:01 +00001399
1400 // Finally, don't infinitely unroll conditional loops.
1401 BasicBlock *TrueDest = BI->getSuccessor(0);
1402 BasicBlock *FalseDest = BI->getSuccessor(1);
1403 if (TrueDest == BB || FalseDest == BB)
1404 return false;
1405
1406 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1407 BasicBlock *PredBlock = *PI;
1408 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001409
Chris Lattner093a4382008-07-13 22:23:11 +00001410 // Check that we have two conditional branches. If there is a PHI node in
1411 // the common successor, verify that the same value flows in from both
1412 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001413 if (PBI == 0 || PBI->isUnconditional() ||
1414 !SafeToMergeTerminators(BI, PBI))
1415 continue;
1416
Owen Andersone84178a2010-07-14 19:52:16 +00001417 // Ensure that any values used in the bonus instruction are also used
1418 // by the terminator of the predecessor. This means that those values
1419 // must already have been resolved, so we won't be inhibiting the
1420 // out-of-order core by speculating them earlier.
1421 if (BonusInst) {
1422 // Collect the values used by the bonus inst
1423 SmallPtrSet<Value*, 4> UsedValues;
1424 for (Instruction::op_iterator OI = BonusInst->op_begin(),
1425 OE = BonusInst->op_end(); OI != OE; ++OI) {
1426 Value* V = *OI;
1427 if (!isa<Constant>(V))
1428 UsedValues.insert(V);
1429 }
1430
1431 SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
1432 Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
1433
1434 // Walk up to four levels back up the use-def chain of the predecessor's
1435 // terminator to see if all those values were used. The choice of four
1436 // levels is arbitrary, to provide a compile-time-cost bound.
1437 while (!Worklist.empty()) {
1438 std::pair<Value*, unsigned> Pair = Worklist.back();
1439 Worklist.pop_back();
1440
1441 if (Pair.second >= 4) continue;
1442 UsedValues.erase(Pair.first);
1443 if (UsedValues.empty()) break;
1444
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001445 if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
Owen Andersone84178a2010-07-14 19:52:16 +00001446 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1447 OI != OE; ++OI)
1448 Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
1449 }
1450 }
1451
1452 if (!UsedValues.empty()) return false;
1453 }
1454
Chris Lattner36989092008-07-13 21:20:19 +00001455 Instruction::BinaryOps Opc;
1456 bool InvertPredCond = false;
1457
1458 if (PBI->getSuccessor(0) == TrueDest)
1459 Opc = Instruction::Or;
1460 else if (PBI->getSuccessor(1) == FalseDest)
1461 Opc = Instruction::And;
1462 else if (PBI->getSuccessor(0) == FalseDest)
1463 Opc = Instruction::And, InvertPredCond = true;
1464 else if (PBI->getSuccessor(1) == TrueDest)
1465 Opc = Instruction::Or, InvertPredCond = true;
1466 else
1467 continue;
1468
David Greene89d6fd32010-01-05 01:26:52 +00001469 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Chris Lattner6ff645b2009-01-19 23:03:13 +00001470
Chris Lattner36989092008-07-13 21:20:19 +00001471 // If we need to invert the condition in the pred block to match, do so now.
1472 if (InvertPredCond) {
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001473 Value *NewCond = PBI->getCondition();
1474
1475 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
1476 CmpInst *CI = cast<CmpInst>(NewCond);
1477 CI->setPredicate(CI->getInversePredicate());
1478 } else {
1479 NewCond = BinaryOperator::CreateNot(NewCond,
Chris Lattner36989092008-07-13 21:20:19 +00001480 PBI->getCondition()->getName()+".not", PBI);
Chris Lattnerdaa02ab2010-12-13 07:00:06 +00001481 }
1482
Chris Lattner1347e872008-07-13 21:12:01 +00001483 PBI->setCondition(NewCond);
1484 BasicBlock *OldTrue = PBI->getSuccessor(0);
1485 BasicBlock *OldFalse = PBI->getSuccessor(1);
1486 PBI->setSuccessor(0, OldFalse);
1487 PBI->setSuccessor(1, OldTrue);
1488 }
Chris Lattner70087f32008-07-13 21:15:11 +00001489
Owen Andersone84178a2010-07-14 19:52:16 +00001490 // If we have a bonus inst, clone it into the predecessor block.
1491 Instruction *NewBonus = 0;
1492 if (BonusInst) {
1493 NewBonus = BonusInst->clone();
1494 PredBlock->getInstList().insert(PBI, NewBonus);
1495 NewBonus->takeName(BonusInst);
1496 BonusInst->setName(BonusInst->getName()+".old");
1497 }
1498
Chris Lattner36989092008-07-13 21:20:19 +00001499 // Clone Cond into the predecessor basic block, and or/and the
1500 // two conditions together.
Nick Lewycky67760642009-09-27 07:38:41 +00001501 Instruction *New = Cond->clone();
Owen Andersone84178a2010-07-14 19:52:16 +00001502 if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
Chris Lattner36989092008-07-13 21:20:19 +00001503 PredBlock->getInstList().insert(PBI, New);
1504 New->takeName(Cond);
1505 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001506
Chris Lattner36989092008-07-13 21:20:19 +00001507 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1508 New, "or.cond", PBI);
1509 PBI->setCondition(NewCond);
1510 if (PBI->getSuccessor(0) == BB) {
1511 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1512 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001513 }
Chris Lattner36989092008-07-13 21:20:19 +00001514 if (PBI->getSuccessor(1) == BB) {
1515 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1516 PBI->setSuccessor(1, FalseDest);
1517 }
Chris Lattner117f8cf2010-12-14 05:57:30 +00001518 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001519 }
1520 return false;
1521}
1522
Chris Lattner867661a2008-07-13 21:53:26 +00001523/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1524/// predecessor of another block, this function tries to simplify it. We know
1525/// that PBI and BI are both conditional branches, and BI is in one of the
1526/// successor blocks of PBI - PBI branches to BI.
1527static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1528 assert(PBI->isConditional() && BI->isConditional());
1529 BasicBlock *BB = BI->getParent();
Dan Gohman4ae51262009-08-12 16:23:25 +00001530
Chris Lattner867661a2008-07-13 21:53:26 +00001531 // If this block ends with a branch instruction, and if there is a
1532 // predecessor that ends on a branch of the same condition, make
1533 // this conditional branch redundant.
1534 if (PBI->getCondition() == BI->getCondition() &&
1535 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1536 // Okay, the outcome of this conditional branch is statically
1537 // knowable. If this block had a single pred, handle specially.
1538 if (BB->getSinglePredecessor()) {
1539 // Turn this into a branch on constant.
1540 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001541 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
1542 CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001543 return true; // Nuke the branch on constant.
1544 }
1545
1546 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1547 // in the constant and simplify the block result. Subsequent passes of
1548 // simplifycfg will thread the block.
1549 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001550 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Chris Lattner867661a2008-07-13 21:53:26 +00001551 BI->getCondition()->getName() + ".pr",
1552 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001553 // Okay, we're going to insert the PHI node. Since PBI is not the only
1554 // predecessor, compute the PHI'd conditional value for all of the preds.
1555 // Any predecessor where the condition is not computable we keep symbolic.
Gabor Greif62539832010-07-12 10:59:23 +00001556 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1557 BasicBlock *P = *PI;
1558 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner867661a2008-07-13 21:53:26 +00001559 PBI != BI && PBI->isConditional() &&
1560 PBI->getCondition() == BI->getCondition() &&
1561 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1562 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson1d0be152009-08-13 21:58:54 +00001563 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif62539832010-07-12 10:59:23 +00001564 CondIsTrue), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001565 } else {
Gabor Greif62539832010-07-12 10:59:23 +00001566 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner867661a2008-07-13 21:53:26 +00001567 }
Gabor Greif62539832010-07-12 10:59:23 +00001568 }
Chris Lattner867661a2008-07-13 21:53:26 +00001569
1570 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001571 return true;
1572 }
1573 }
1574
1575 // If this is a conditional branch in an empty block, and if any
1576 // predecessors is a conditional branch to one of our destinations,
1577 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001578 BasicBlock::iterator BBI = BB->begin();
1579 // Ignore dbg intrinsics.
1580 while (isa<DbgInfoIntrinsic>(BBI))
1581 ++BBI;
1582 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001583 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001584
1585
1586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1587 if (CE->canTrap())
1588 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001589
1590 int PBIOp, BIOp;
1591 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1592 PBIOp = BIOp = 0;
1593 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1594 PBIOp = 0, BIOp = 1;
1595 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1596 PBIOp = 1, BIOp = 0;
1597 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1598 PBIOp = BIOp = 1;
1599 else
1600 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001601
Chris Lattnerb8245122008-07-13 22:04:41 +00001602 // Check to make sure that the other destination of this branch
1603 // isn't BB itself. If so, this is an infinite loop that will
1604 // keep getting unwound.
1605 if (PBI->getSuccessor(PBIOp) == BB)
1606 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001607
Chris Lattnerb8245122008-07-13 22:04:41 +00001608 // Do not perform this transformation if it would require
1609 // insertion of a large number of select instructions. For targets
1610 // without predication/cmovs, this is a big pessimization.
1611 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001612
Chris Lattnerb8245122008-07-13 22:04:41 +00001613 unsigned NumPhis = 0;
1614 for (BasicBlock::iterator II = CommonDest->begin();
1615 isa<PHINode>(II); ++II, ++NumPhis)
1616 if (NumPhis > 2) // Disable this xform.
1617 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001618
Chris Lattnerb8245122008-07-13 22:04:41 +00001619 // Finally, if everything is ok, fold the branches to logical ops.
1620 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1621
David Greene89d6fd32010-01-05 01:26:52 +00001622 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerbdff5482009-08-23 04:37:46 +00001623 << "AND: " << *BI->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001624
Chris Lattner093a4382008-07-13 22:23:11 +00001625
1626 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1627 // branch in it, where one edge (OtherDest) goes back to itself but the other
1628 // exits. We don't *know* that the program avoids the infinite loop
1629 // (even though that seems likely). If we do this xform naively, we'll end up
1630 // recursively unpeeling the loop. Since we know that (after the xform is
1631 // done) that the block *is* infinite if reached, we just make it an obviously
1632 // infinite loop with no cond branch.
1633 if (OtherDest == BB) {
1634 // Insert it at the end of the function, because it's either code,
1635 // or it won't matter if it's hot. :)
Owen Anderson1d0be152009-08-13 21:58:54 +00001636 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
1637 "infloop", BB->getParent());
Chris Lattner093a4382008-07-13 22:23:11 +00001638 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1639 OtherDest = InfLoopBlock;
1640 }
1641
David Greene89d6fd32010-01-05 01:26:52 +00001642 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001643
1644 // BI may have other predecessors. Because of this, we leave
1645 // it alone, but modify PBI.
1646
1647 // Make sure we get to CommonDest on True&True directions.
1648 Value *PBICond = PBI->getCondition();
1649 if (PBIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001650 PBICond = BinaryOperator::CreateNot(PBICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001651 PBICond->getName()+".not",
1652 PBI);
1653 Value *BICond = BI->getCondition();
1654 if (BIOp)
Dan Gohman4ae51262009-08-12 16:23:25 +00001655 BICond = BinaryOperator::CreateNot(BICond,
Chris Lattnerb8245122008-07-13 22:04:41 +00001656 BICond->getName()+".not",
1657 PBI);
1658 // Merge the conditions.
1659 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1660
1661 // Modify PBI to branch on the new condition to the new dests.
1662 PBI->setCondition(Cond);
1663 PBI->setSuccessor(0, CommonDest);
1664 PBI->setSuccessor(1, OtherDest);
1665
1666 // OtherDest may have phi nodes. If so, add an entry from PBI's
1667 // block that are identical to the entries for BI's block.
Chris Lattner6de0a282010-12-14 07:09:42 +00001668 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Chris Lattnerb8245122008-07-13 22:04:41 +00001669
1670 // We know that the CommonDest already had an edge from PBI to
1671 // it. If it has PHIs though, the PHIs may have different
1672 // entries for BB and PBI's BB. If so, insert a select to make
1673 // them agree.
Chris Lattner6de0a282010-12-14 07:09:42 +00001674 PHINode *PN;
Chris Lattnerb8245122008-07-13 22:04:41 +00001675 for (BasicBlock::iterator II = CommonDest->begin();
1676 (PN = dyn_cast<PHINode>(II)); ++II) {
1677 Value *BIV = PN->getIncomingValueForBlock(BB);
1678 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1679 Value *PBIV = PN->getIncomingValue(PBBIdx);
1680 if (BIV != PBIV) {
1681 // Insert a select in PBI to pick the right value.
1682 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1683 PBIV->getName()+".mux", PBI);
1684 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001685 }
1686 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001687
David Greene89d6fd32010-01-05 01:26:52 +00001688 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
1689 DEBUG(dbgs() << *PBI->getParent()->getParent());
Chris Lattnerb8245122008-07-13 22:04:41 +00001690
1691 // This basic block is probably dead. We know it has at least
1692 // one fewer predecessor.
1693 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001694}
1695
Frits van Bommel7ac40c32010-12-05 18:29:03 +00001696// SimplifyIndirectBrOnSelect - Replaces
1697// (indirectbr (select cond, blockaddress(@fn, BlockA),
1698// blockaddress(@fn, BlockB)))
1699// with
1700// (br cond, BlockA, BlockB).
1701static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
1702 // Check that both operands of the select are block addresses.
1703 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
1704 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
1705 if (!TBA || !FBA)
1706 return false;
1707
1708 // Extract the actual blocks.
1709 BasicBlock *TrueBB = TBA->getBasicBlock();
1710 BasicBlock *FalseBB = FBA->getBasicBlock();
1711
1712 // Remove any superfluous successor edges from the CFG.
1713 // First, figure out which successors to preserve.
1714 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
1715 // successor.
1716 BasicBlock *KeepEdge1 = TrueBB;
1717 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
1718
1719 // Then remove the rest.
1720 for (unsigned I = 0, E = IBI->getNumSuccessors(); I != E; ++I) {
1721 BasicBlock *Succ = IBI->getSuccessor(I);
1722 // Make sure only to keep exactly one copy of each edge.
1723 if (Succ == KeepEdge1)
1724 KeepEdge1 = 0;
1725 else if (Succ == KeepEdge2)
1726 KeepEdge2 = 0;
1727 else
1728 Succ->removePredecessor(IBI->getParent());
1729 }
1730
1731 // Insert an appropriate new terminator.
1732 if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
1733 if (TrueBB == FalseBB)
1734 // We were only looking for one successor, and it was present.
1735 // Create an unconditional branch to it.
1736 BranchInst::Create(TrueBB, IBI);
1737 else
1738 // We found both of the successors we were looking for.
1739 // Create a conditional branch sharing the condition of the select.
1740 BranchInst::Create(TrueBB, FalseBB, SI->getCondition(), IBI);
1741 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
1742 // Neither of the selected blocks were successors, so this
1743 // indirectbr must be unreachable.
1744 new UnreachableInst(IBI->getContext(), IBI);
1745 } else {
1746 // One of the selected values was a successor, but the other wasn't.
1747 // Insert an unconditional branch to the one that was found;
1748 // the edge to the one that wasn't must be unreachable.
1749 if (KeepEdge1 == 0)
1750 // Only TrueBB was found.
1751 BranchInst::Create(TrueBB, IBI);
1752 else
1753 // Only FalseBB was found.
1754 BranchInst::Create(FalseBB, IBI);
1755 }
1756
1757 EraseTerminatorInstAndDCECond(IBI);
1758 return true;
1759}
1760
Chris Lattner61c77442010-12-13 03:18:54 +00001761/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
1762/// instruction (a seteq/setne with a constant) as the only instruction in a
1763/// block that ends with an uncond branch. We are looking for a very specific
1764/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
1765/// this case, we merge the first two "or's of icmp" into a switch, but then the
1766/// default value goes to an uncond block with a seteq in it, we get something
1767/// like:
1768///
1769/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
1770/// DEFAULT:
1771/// %tmp = icmp eq i8 %A, 92
1772/// br label %end
1773/// end:
1774/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
1775///
1776/// We prefer to split the edge to 'end' so that there is a true/false entry to
1777/// the PHI, merging the third icmp into the switch.
Chris Lattner302ba6f2010-12-14 06:17:25 +00001778static bool TryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
1779 const TargetData *TD) {
Chris Lattner61c77442010-12-13 03:18:54 +00001780 BasicBlock *BB = ICI->getParent();
1781 // If the block has any PHIs in it or the icmp has multiple uses, it is too
1782 // complex.
1783 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
1784
1785 Value *V = ICI->getOperand(0);
1786 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
1787
1788 // The pattern we're looking for is where our only predecessor is a switch on
1789 // 'V' and this block is the default case for the switch. In this case we can
1790 // fold the compared value into the switch to simplify things.
1791 BasicBlock *Pred = BB->getSinglePredecessor();
1792 if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
1793
1794 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
1795 if (SI->getCondition() != V)
1796 return false;
1797
1798 // If BB is reachable on a non-default case, then we simply know the value of
1799 // V in this block. Substitute it and constant fold the icmp instruction
1800 // away.
1801 if (SI->getDefaultDest() != BB) {
1802 ConstantInt *VVal = SI->findCaseDest(BB);
1803 assert(VVal && "Should have a unique destination value");
1804 ICI->setOperand(0, VVal);
1805
Chris Lattner302ba6f2010-12-14 06:17:25 +00001806 if (Value *V = SimplifyInstruction(ICI, TD)) {
1807 ICI->replaceAllUsesWith(V);
Chris Lattner61c77442010-12-13 03:18:54 +00001808 ICI->eraseFromParent();
1809 }
1810 // BB is now empty, so it is likely to simplify away.
1811 return SimplifyCFG(BB) | true;
1812 }
1813
Chris Lattnerabf70672010-12-13 03:43:57 +00001814 // Ok, the block is reachable from the default dest. If the constant we're
1815 // comparing exists in one of the other edges, then we can constant fold ICI
1816 // and zap it.
1817 if (SI->findCaseValue(Cst) != 0) {
1818 Value *V;
1819 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1820 V = ConstantInt::getFalse(BB->getContext());
1821 else
1822 V = ConstantInt::getTrue(BB->getContext());
1823
1824 ICI->replaceAllUsesWith(V);
1825 ICI->eraseFromParent();
1826 // BB is now empty, so it is likely to simplify away.
1827 return SimplifyCFG(BB) | true;
1828 }
1829
Chris Lattner61c77442010-12-13 03:18:54 +00001830 // The use of the icmp has to be in the 'end' block, by the only PHI node in
1831 // the block.
1832 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
1833 PHINode *PHIUse = dyn_cast<PHINode>(ICI->use_back());
1834 if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
1835 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
1836 return false;
1837
1838 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
1839 // true in the PHI.
1840 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
1841 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
1842
1843 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
1844 std::swap(DefaultCst, NewCst);
1845
1846 // Replace ICI (which is used by the PHI for the default value) with true or
1847 // false depending on if it is EQ or NE.
1848 ICI->replaceAllUsesWith(DefaultCst);
1849 ICI->eraseFromParent();
1850
1851 // Okay, the switch goes to this block on a default value. Add an edge from
1852 // the switch to the merge point on the compared value.
1853 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
1854 BB->getParent(), BB);
1855 SI->addCase(Cst, NewBB);
1856
1857 // NewBB branches to the phi block, add the uncond branch and the phi entry.
1858 BranchInst::Create(SuccBlock, NewBB);
1859 PHIUse->addIncoming(NewCst, NewBB);
1860 return true;
1861}
1862
Chris Lattner97fdb892010-12-13 05:03:41 +00001863/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
1864/// Check to see if it is branching on an or/and chain of icmp instructions, and
1865/// fold it into a switch instruction if so.
1866static bool SimplifyBranchOnICmpChain(BranchInst *BI, const TargetData *TD) {
1867 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1868 if (Cond == 0) return false;
1869
1870
1871 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1872 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1873 // 'setne's and'ed together, collect them.
1874 Value *CompVal = 0;
1875 std::vector<ConstantInt*> Values;
1876 bool TrueWhenEqual = true;
1877 Value *ExtraCase = 0;
1878
1879 if (Cond->getOpcode() == Instruction::Or) {
1880 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, true);
1881 } else if (Cond->getOpcode() == Instruction::And) {
1882 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, TD, false);
1883 TrueWhenEqual = false;
1884 }
1885
1886 // If we didn't have a multiply compared value, fail.
1887 if (CompVal == 0) return false;
1888
1889 // There might be duplicate constants in the list, which the switch
1890 // instruction can't handle, remove them now.
1891 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
1892 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1893
1894 // If Extra was used, we require at least two switch values to do the
1895 // transformation. A switch with one value is just an cond branch.
1896 if (ExtraCase && Values.size() < 2) return false;
1897
1898 // Figure out which block is which destination.
1899 BasicBlock *DefaultBB = BI->getSuccessor(1);
1900 BasicBlock *EdgeBB = BI->getSuccessor(0);
1901 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1902
1903 BasicBlock *BB = BI->getParent();
1904
Chris Lattner302ba6f2010-12-14 06:17:25 +00001905 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner117f8cf2010-12-14 05:57:30 +00001906 << " cases into SWITCH. BB is:\n" << *BB);
1907
Chris Lattner97fdb892010-12-13 05:03:41 +00001908 // If there are any extra values that couldn't be folded into the switch
1909 // then we evaluate them with an explicit branch first. Split the block
1910 // right before the condbr to handle it.
1911 if (ExtraCase) {
1912 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
1913 // Remove the uncond branch added to the old block.
1914 TerminatorInst *OldTI = BB->getTerminator();
1915
Chris Lattner117f8cf2010-12-14 05:57:30 +00001916 if (TrueWhenEqual)
1917 BranchInst::Create(EdgeBB, NewBB, ExtraCase, OldTI);
1918 else
1919 BranchInst::Create(NewBB, EdgeBB, ExtraCase, OldTI);
1920
Chris Lattner97fdb892010-12-13 05:03:41 +00001921 OldTI->eraseFromParent();
Chris Lattner97bd89e2010-12-13 05:34:18 +00001922
1923 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
1924 // for the edge we just added.
Chris Lattner6de0a282010-12-14 07:09:42 +00001925 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Chris Lattner302ba6f2010-12-14 06:17:25 +00001926
1927 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
1928 << "\nEXTRABB = " << *BB);
Chris Lattner97fdb892010-12-13 05:03:41 +00001929 BB = NewBB;
1930 }
1931
1932 // Convert pointer to int before we switch.
1933 if (CompVal->getType()->isPointerTy()) {
1934 assert(TD && "Cannot switch on pointer without TargetData");
1935 CompVal = new PtrToIntInst(CompVal,
1936 TD->getIntPtrType(CompVal->getContext()),
1937 "magicptr", BI);
1938 }
1939
1940 // Create the new switch instruction now.
Chris Lattner3d512132010-12-13 06:25:44 +00001941 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB, Values.size(), BI);
Chris Lattner97fdb892010-12-13 05:03:41 +00001942
1943 // Add all of the 'cases' to the switch instruction.
1944 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1945 New->addCase(Values[i], EdgeBB);
1946
1947 // We added edges from PI to the EdgeBB. As such, if there were any
1948 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1949 // the number of edges added.
1950 for (BasicBlock::iterator BBI = EdgeBB->begin();
1951 isa<PHINode>(BBI); ++BBI) {
1952 PHINode *PN = cast<PHINode>(BBI);
1953 Value *InVal = PN->getIncomingValueForBlock(BB);
1954 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1955 PN->addIncoming(InVal, BB);
1956 }
1957
1958 // Erase the old branch instruction.
1959 EraseTerminatorInstAndDCECond(BI);
Chris Lattner117f8cf2010-12-14 05:57:30 +00001960
Chris Lattner302ba6f2010-12-14 06:17:25 +00001961 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattner97fdb892010-12-13 05:03:41 +00001962 return true;
1963}
1964
Chris Lattner3d512132010-12-13 06:25:44 +00001965bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI) {
1966 BasicBlock *BB = RI->getParent();
1967 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
1968
1969 // Find predecessors that end with branches.
1970 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1971 SmallVector<BranchInst*, 8> CondBranchPreds;
1972 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1973 BasicBlock *P = *PI;
1974 TerminatorInst *PTI = P->getTerminator();
1975 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
1976 if (BI->isUnconditional())
1977 UncondBranchPreds.push_back(P);
1978 else
1979 CondBranchPreds.push_back(BI);
1980 }
1981 }
1982
1983 // If we found some, do the transformation!
1984 if (!UncondBranchPreds.empty()) {
1985 while (!UncondBranchPreds.empty()) {
1986 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
1987 DEBUG(dbgs() << "FOLDING: " << *BB
1988 << "INTO UNCOND BRANCH PRED: " << *Pred);
1989 Instruction *UncondBranch = Pred->getTerminator();
1990 // Clone the return and add it to the end of the predecessor.
1991 Instruction *NewRet = RI->clone();
1992 Pred->getInstList().push_back(NewRet);
1993
1994 // If the return instruction returns a value, and if the value was a
1995 // PHI node in "BB", propagate the right value into the return.
1996 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
1997 i != e; ++i)
1998 if (PHINode *PN = dyn_cast<PHINode>(*i))
1999 if (PN->getParent() == BB)
2000 *i = PN->getIncomingValueForBlock(Pred);
2001
2002 // Update any PHI nodes in the returning block to realize that we no
2003 // longer branch to them.
2004 BB->removePredecessor(Pred);
Chris Lattner302ba6f2010-12-14 06:17:25 +00002005 UncondBranch->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002006 }
2007
2008 // If we eliminated all predecessors of the block, delete the block now.
2009 if (pred_begin(BB) == pred_end(BB))
2010 // We know there are no successors, so just nuke the block.
2011 BB->eraseFromParent();
2012
2013 return true;
2014 }
2015
2016 // Check out all of the conditional branches going to this return
2017 // instruction. If any of them just select between returns, change the
2018 // branch itself into a select/return pair.
2019 while (!CondBranchPreds.empty()) {
2020 BranchInst *BI = CondBranchPreds.pop_back_val();
2021
2022 // Check to see if the non-BB successor is also a return block.
2023 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2024 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
2025 SimplifyCondBranchToTwoReturns(BI))
2026 return true;
2027 }
2028 return false;
2029}
2030
2031bool SimplifyCFGOpt::SimplifyUnwind(UnwindInst *UI) {
2032 // Check to see if the first instruction in this block is just an unwind.
2033 // If so, replace any invoke instructions which use this as an exception
2034 // destination with call instructions.
2035 BasicBlock *BB = UI->getParent();
2036 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
2037
2038 bool Changed = false;
2039 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2040 while (!Preds.empty()) {
2041 BasicBlock *Pred = Preds.back();
2042 InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator());
2043 if (II && II->getUnwindDest() == BB) {
2044 // Insert a new branch instruction before the invoke, because this
2045 // is now a fall through.
2046 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2047 Pred->getInstList().remove(II); // Take out of symbol table
2048
2049 // Insert the call now.
2050 SmallVector<Value*,8> Args(II->op_begin(), II->op_end()-3);
2051 CallInst *CI = CallInst::Create(II->getCalledValue(),
2052 Args.begin(), Args.end(),
2053 II->getName(), BI);
2054 CI->setCallingConv(II->getCallingConv());
2055 CI->setAttributes(II->getAttributes());
2056 // If the invoke produced a value, the Call now does instead.
2057 II->replaceAllUsesWith(CI);
2058 delete II;
2059 Changed = true;
2060 }
2061
2062 Preds.pop_back();
2063 }
2064
2065 // If this block is now dead (and isn't the entry block), remove it.
2066 if (pred_begin(BB) == pred_end(BB) &&
2067 BB != &BB->getParent()->getEntryBlock()) {
2068 // We know there are no successors, so just nuke the block.
2069 BB->eraseFromParent();
2070 return true;
2071 }
2072
2073 return Changed;
2074}
2075
2076bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2077 BasicBlock *BB = UI->getParent();
2078
2079 bool Changed = false;
2080
2081 // If there are any instructions immediately before the unreachable that can
2082 // be removed, do so.
2083 while (UI != BB->begin()) {
2084 BasicBlock::iterator BBI = UI;
2085 --BBI;
2086 // Do not delete instructions that can have side effects, like calls
2087 // (which may never return) and volatile loads and stores.
2088 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
2089
2090 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2091 if (SI->isVolatile())
2092 break;
2093
2094 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2095 if (LI->isVolatile())
2096 break;
2097
2098 // Delete this instruction
Chris Lattner302ba6f2010-12-14 06:17:25 +00002099 BBI->eraseFromParent();
Chris Lattner3d512132010-12-13 06:25:44 +00002100 Changed = true;
2101 }
2102
2103 // If the unreachable instruction is the first in the block, take a gander
2104 // at all of the predecessors of this instruction, and simplify them.
2105 if (&BB->front() != UI) return Changed;
2106
2107 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
2108 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2109 TerminatorInst *TI = Preds[i]->getTerminator();
2110
2111 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2112 if (BI->isUnconditional()) {
2113 if (BI->getSuccessor(0) == BB) {
2114 new UnreachableInst(TI->getContext(), TI);
2115 TI->eraseFromParent();
2116 Changed = true;
2117 }
2118 } else {
2119 if (BI->getSuccessor(0) == BB) {
2120 BranchInst::Create(BI->getSuccessor(1), BI);
2121 EraseTerminatorInstAndDCECond(BI);
2122 } else if (BI->getSuccessor(1) == BB) {
2123 BranchInst::Create(BI->getSuccessor(0), BI);
2124 EraseTerminatorInstAndDCECond(BI);
2125 Changed = true;
2126 }
2127 }
2128 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2129 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2130 if (SI->getSuccessor(i) == BB) {
2131 BB->removePredecessor(SI->getParent());
2132 SI->removeCase(i);
2133 --i; --e;
2134 Changed = true;
2135 }
2136 // If the default value is unreachable, figure out the most popular
2137 // destination and make it the default.
2138 if (SI->getSuccessor(0) == BB) {
2139 std::map<BasicBlock*, unsigned> Popularity;
2140 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2141 Popularity[SI->getSuccessor(i)]++;
2142
2143 // Find the most popular block.
2144 unsigned MaxPop = 0;
2145 BasicBlock *MaxBlock = 0;
2146 for (std::map<BasicBlock*, unsigned>::iterator
2147 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2148 if (I->second > MaxPop) {
2149 MaxPop = I->second;
2150 MaxBlock = I->first;
2151 }
2152 }
2153 if (MaxBlock) {
2154 // Make this the new default, allowing us to delete any explicit
2155 // edges to it.
2156 SI->setSuccessor(0, MaxBlock);
2157 Changed = true;
2158
2159 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2160 // it.
2161 if (isa<PHINode>(MaxBlock->begin()))
2162 for (unsigned i = 0; i != MaxPop-1; ++i)
2163 MaxBlock->removePredecessor(SI->getParent());
2164
2165 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2166 if (SI->getSuccessor(i) == MaxBlock) {
2167 SI->removeCase(i);
2168 --i; --e;
2169 }
2170 }
2171 }
2172 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2173 if (II->getUnwindDest() == BB) {
2174 // Convert the invoke to a call instruction. This would be a good
2175 // place to note that the call does not throw though.
2176 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
2177 II->removeFromParent(); // Take out of symbol table
2178
2179 // Insert the call now...
2180 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
2181 CallInst *CI = CallInst::Create(II->getCalledValue(),
2182 Args.begin(), Args.end(),
2183 II->getName(), BI);
2184 CI->setCallingConv(II->getCallingConv());
2185 CI->setAttributes(II->getAttributes());
2186 // If the invoke produced a value, the call does now instead.
2187 II->replaceAllUsesWith(CI);
2188 delete II;
2189 Changed = true;
2190 }
2191 }
2192 }
2193
2194 // If this block is now dead, remove it.
2195 if (pred_begin(BB) == pred_end(BB) &&
2196 BB != &BB->getParent()->getEntryBlock()) {
2197 // We know there are no successors, so just nuke the block.
2198 BB->eraseFromParent();
2199 return true;
2200 }
2201
2202 return Changed;
2203}
2204
2205
2206bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI) {
2207 // If this switch is too complex to want to look at, ignore it.
2208 if (!isValueEqualityComparison(SI))
2209 return false;
2210
2211 BasicBlock *BB = SI->getParent();
2212
2213 // If we only have one predecessor, and if it is a branch on this value,
2214 // see if that predecessor totally determines the outcome of this switch.
2215 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2216 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
Chris Lattner021c9d32010-12-13 06:36:51 +00002217 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002218
2219 // If the block only contains the switch, see if we can fold the block
2220 // away into any preds.
2221 BasicBlock::iterator BBI = BB->begin();
2222 // Ignore dbg intrinsics.
2223 while (isa<DbgInfoIntrinsic>(BBI))
2224 ++BBI;
2225 if (SI == &*BBI)
2226 if (FoldValueComparisonIntoPredecessors(SI))
Chris Lattner021c9d32010-12-13 06:36:51 +00002227 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002228
2229 return false;
2230}
2231
2232bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
2233 BasicBlock *BB = IBI->getParent();
2234 bool Changed = false;
2235
2236 // Eliminate redundant destinations.
2237 SmallPtrSet<Value *, 8> Succs;
2238 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
2239 BasicBlock *Dest = IBI->getDestination(i);
2240 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
2241 Dest->removePredecessor(BB);
2242 IBI->removeDestination(i);
2243 --i; --e;
2244 Changed = true;
2245 }
2246 }
2247
2248 if (IBI->getNumDestinations() == 0) {
2249 // If the indirectbr has no successors, change it to unreachable.
2250 new UnreachableInst(IBI->getContext(), IBI);
2251 EraseTerminatorInstAndDCECond(IBI);
2252 return true;
2253 }
2254
2255 if (IBI->getNumDestinations() == 1) {
2256 // If the indirectbr has one successor, change it to a direct branch.
2257 BranchInst::Create(IBI->getDestination(0), IBI);
2258 EraseTerminatorInstAndDCECond(IBI);
2259 return true;
2260 }
2261
2262 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
2263 if (SimplifyIndirectBrOnSelect(IBI, SI))
2264 return SimplifyCFG(BB) | true;
2265 }
2266 return Changed;
2267}
2268
2269bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI) {
2270 BasicBlock *BB = BI->getParent();
2271
2272 // If the Terminator is the only non-phi instruction, simplify the block.
2273 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
2274 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
2275 TryToSimplifyUncondBranchFromEmptyBlock(BB))
2276 return true;
2277
2278 // If the only instruction in the block is a seteq/setne comparison
2279 // against a constant, try to simplify the block.
2280 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
2281 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
2282 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
2283 ;
Chris Lattner302ba6f2010-12-14 06:17:25 +00002284 if (I->isTerminator() && TryToSimplifyUncondBranchWithICmpInIt(ICI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002285 return true;
2286 }
2287
2288 return false;
2289}
2290
2291
2292bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI) {
2293 BasicBlock *BB = BI->getParent();
2294
2295 // Conditional branch
2296 if (isValueEqualityComparison(BI)) {
2297 // If we only have one predecessor, and if it is a branch on this value,
2298 // see if that predecessor totally determines the outcome of this
2299 // switch.
2300 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
2301 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
2302 return SimplifyCFG(BB) | true;
2303
2304 // This block must be empty, except for the setcond inst, if it exists.
2305 // Ignore dbg intrinsics.
2306 BasicBlock::iterator I = BB->begin();
2307 // Ignore dbg intrinsics.
2308 while (isa<DbgInfoIntrinsic>(I))
2309 ++I;
2310 if (&*I == BI) {
2311 if (FoldValueComparisonIntoPredecessors(BI))
2312 return SimplifyCFG(BB) | true;
2313 } else if (&*I == cast<Instruction>(BI->getCondition())){
2314 ++I;
2315 // Ignore dbg intrinsics.
2316 while (isa<DbgInfoIntrinsic>(I))
2317 ++I;
2318 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI))
2319 return SimplifyCFG(BB) | true;
2320 }
2321 }
2322
2323 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
2324 if (SimplifyBranchOnICmpChain(BI, TD))
2325 return true;
2326
2327 // We have a conditional branch to two blocks that are only reachable
2328 // from BI. We know that the condbr dominates the two blocks, so see if
2329 // there is any identical code in the "then" and "else" blocks. If so, we
2330 // can hoist it up to the branching block.
2331 if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
2332 if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2333 if (HoistThenElseCodeToIf(BI))
2334 return SimplifyCFG(BB) | true;
2335 } else {
2336 // If Successor #1 has multiple preds, we may be able to conditionally
2337 // execute Successor #0 if it branches to successor #1.
2338 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
2339 if (Succ0TI->getNumSuccessors() == 1 &&
2340 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
2341 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
2342 return SimplifyCFG(BB) | true;
2343 }
2344 } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
2345 // If Successor #0 has multiple preds, we may be able to conditionally
2346 // execute Successor #1 if it branches to successor #0.
2347 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
2348 if (Succ1TI->getNumSuccessors() == 1 &&
2349 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
2350 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
2351 return SimplifyCFG(BB) | true;
2352 }
2353
2354 // If this is a branch on a phi node in the current block, thread control
2355 // through this block if any PHI node entries are constants.
2356 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
2357 if (PN->getParent() == BI->getParent())
Chris Lattner302ba6f2010-12-14 06:17:25 +00002358 if (FoldCondBranchOnPHI(BI, TD))
Chris Lattner3d512132010-12-13 06:25:44 +00002359 return SimplifyCFG(BB) | true;
2360
2361 // If this basic block is ONLY a setcc and a branch, and if a predecessor
2362 // branches to us and one of our successors, fold the setcc into the
2363 // predecessor and use logical operations to pick the right destination.
2364 if (FoldBranchToCommonDest(BI))
Owen Anderson2d9220e2010-12-13 23:49:28 +00002365 return SimplifyCFG(BB) | true;
Chris Lattner3d512132010-12-13 06:25:44 +00002366
2367 // Scan predecessor blocks for conditional branches.
2368 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2369 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2370 if (PBI != BI && PBI->isConditional())
2371 if (SimplifyCondBranchToCondBranch(PBI, BI))
2372 return SimplifyCFG(BB) | true;
2373
2374 return false;
2375}
2376
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002377bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00002378 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002379
Chris Lattner302ba6f2010-12-14 06:17:25 +00002380 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00002381 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00002382
Dan Gohmane2c6d132010-08-14 00:29:42 +00002383 // Remove basic blocks that have no predecessors (except the entry block)...
2384 // or that just have themself as a predecessor. These are unreachable.
Chris Lattner302ba6f2010-12-14 06:17:25 +00002385 if ((pred_begin(BB) == pred_end(BB) &&
2386 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohmane2c6d132010-08-14 00:29:42 +00002387 BB->getSinglePredecessor() == BB) {
David Greene89d6fd32010-01-05 01:26:52 +00002388 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner71af9b02008-12-03 06:40:52 +00002389 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00002390 return true;
2391 }
2392
Chris Lattner694e37f2003-08-17 19:41:53 +00002393 // Check to see if we can constant propagate this terminator instruction
2394 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00002395 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00002396
Dan Gohman2c635662009-10-30 22:39:04 +00002397 // Check for and eliminate duplicate PHI nodes in this block.
2398 Changed |= EliminateDuplicatePHINodes(BB);
2399
Chris Lattnerddb97a22010-12-13 05:10:48 +00002400 // Merge basic blocks into their predecessor if there is only one distinct
2401 // pred, and if there is only one distinct successor of the predecessor, and
2402 // if there are no PHI nodes.
2403 //
2404 if (MergeBlockIntoPredecessor(BB))
2405 return true;
2406
Dan Gohman882d87d2008-03-11 21:53:06 +00002407 // If there is a trivial two-entry PHI node in this basic block, and we can
2408 // eliminate it, do so now.
2409 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
2410 if (PN->getNumIncomingValues() == 2)
Chris Lattner73c50a62010-12-14 07:00:00 +00002411 Changed |= FoldTwoEntryPHINode(PN, TD);
Dan Gohman882d87d2008-03-11 21:53:06 +00002412
Chris Lattner3d512132010-12-13 06:25:44 +00002413 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner021c9d32010-12-13 06:36:51 +00002414 if (BI->isUnconditional()) {
2415 if (SimplifyUncondBranch(BI)) return true;
2416 } else {
Chris Lattner117f8cf2010-12-14 05:57:30 +00002417 if (SimplifyCondBranch(BI)) return true;
Chris Lattner021c9d32010-12-13 06:36:51 +00002418 }
2419 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
2420 if (SimplifyReturn(RI)) return true;
2421 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
2422 if (SimplifySwitch(SI)) return true;
2423 } else if (UnreachableInst *UI =
2424 dyn_cast<UnreachableInst>(BB->getTerminator())) {
2425 if (SimplifyUnreachable(UI)) return true;
2426 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
2427 if (SimplifyUnwind(UI)) return true;
2428 } else if (IndirectBrInst *IBI =
2429 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
2430 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattner19831ec2004-02-16 06:35:48 +00002431 }
2432
Chris Lattner694e37f2003-08-17 19:41:53 +00002433 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002434}
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002435
2436/// SimplifyCFG - This function is used to do simplification of a CFG. For
2437/// example, it adjusts branches to branches to eliminate the extra hop, it
2438/// eliminates unreachable basic blocks, and does other "peephole" optimization
2439/// of the CFG. It returns true if a modification was made.
2440///
Jakob Stoklund Olesen58e9ee82010-02-05 22:03:18 +00002441bool llvm::SimplifyCFG(BasicBlock *BB, const TargetData *TD) {
2442 return SimplifyCFGOpt(TD).run(BB);
2443}