blob: 2e526901dc884aedc9129d27441c7446f7203654 [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"
Owen Anderson0a205a42009-07-05 22:41:43 +000019#include "llvm/LLVMContext.h"
Chris Lattner0d560082004-02-24 05:38:11 +000020#include "llvm/Type.h"
Reid Spencerc1030572007-01-19 21:13:56 +000021#include "llvm/DerivedTypes.h"
Dale Johannesenf8bc3002009-05-13 18:25:07 +000022#include "llvm/GlobalVariable.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000023#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000025#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnereaba3a12005-09-19 23:49:37 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000027#include "llvm/ADT/SmallVector.h"
Chris Lattnerc9951232007-04-02 01:44:59 +000028#include "llvm/ADT/SmallPtrSet.h"
Evan Cheng502a4f52008-06-12 21:15:59 +000029#include "llvm/ADT/Statistic.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000030#include <algorithm>
31#include <functional>
Chris Lattnerd52c2612004-02-24 07:23:58 +000032#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000033#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000034using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000035
Evan Cheng502a4f52008-06-12 21:15:59 +000036STATISTIC(NumSpeculations, "Number of speculative executed instructions");
37
Chris Lattner2bdcb562005-08-03 00:19:45 +000038/// SafeToMergeTerminators - Return true if it is safe to merge these two
39/// terminator instructions together.
40///
41static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
42 if (SI1 == SI2) return false; // Can't merge with self!
43
44 // It is not safe to merge these two switch instructions if they have a common
45 // successor, and if that successor has a PHI node, and if *that* PHI node has
46 // conflicting incoming values from the two switch blocks.
47 BasicBlock *SI1BB = SI1->getParent();
48 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000049 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000050
51 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
52 if (SI1Succs.count(*I))
53 for (BasicBlock::iterator BBI = (*I)->begin();
54 isa<PHINode>(BBI); ++BBI) {
55 PHINode *PN = cast<PHINode>(BBI);
56 if (PN->getIncomingValueForBlock(SI1BB) !=
57 PN->getIncomingValueForBlock(SI2BB))
58 return false;
59 }
60
61 return true;
62}
63
64/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
65/// now be entries in it from the 'NewPred' block. The values that will be
66/// flowing into the PHI nodes will be the same as those coming in from
67/// ExistPred, an existing predecessor of Succ.
68static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
69 BasicBlock *ExistPred) {
70 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
71 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
72 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
73
Chris Lattner093a4382008-07-13 22:23:11 +000074 PHINode *PN;
75 for (BasicBlock::iterator I = Succ->begin();
76 (PN = dyn_cast<PHINode>(I)); ++I)
77 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner2bdcb562005-08-03 00:19:45 +000078}
79
Bill Wendling5049fa62009-01-19 23:43:56 +000080/// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
81/// almost-empty BB ending in an unconditional branch to Succ, into succ.
82///
83/// Assumption: Succ is the single successor for BB.
84///
Chris Lattner3b3efc72005-08-03 00:29:26 +000085static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000086 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000087
Matthijs Kooijman5e179a22008-05-23 09:09:41 +000088 DOUT << "Looking to fold " << BB->getNameStart() << " into "
89 << Succ->getNameStart() << "\n";
Dale Johannesenf33b1102009-03-19 17:23:29 +000090 // Shortcut, if there is only a single predecessor it must be BB and merging
Matthijs Kooijman5e179a22008-05-23 09:09:41 +000091 // is always safe
92 if (Succ->getSinglePredecessor()) return true;
93
94 typedef SmallPtrSet<Instruction*, 16> InstrSet;
95 InstrSet BBPHIs;
96
97 // Make a list of all phi nodes in BB
98 BasicBlock::iterator BBI = BB->begin();
99 while (isa<PHINode>(*BBI)) BBPHIs.insert(BBI++);
100
101 // Make a list of the predecessors of BB
102 typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
103 BlockSet BBPreds(pred_begin(BB), pred_end(BB));
104
105 // Use that list to make another list of common predecessors of BB and Succ
106 BlockSet CommonPreds;
107 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
108 PI != PE; ++PI)
109 if (BBPreds.count(*PI))
110 CommonPreds.insert(*PI);
111
112 // Shortcut, if there are no common predecessors, merging is always safe
Dan Gohmana8c763b2008-08-14 18:13:49 +0000113 if (CommonPreds.empty())
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000114 return true;
115
116 // Look at all the phi nodes in Succ, to see if they present a conflict when
117 // merging these blocks
118 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
119 PHINode *PN = cast<PHINode>(I);
120
121 // If the incoming value from BB is again a PHINode in
122 // BB which has the same incoming value for *PI as PN does, we can
123 // merge the phi nodes and then the blocks can still be merged
124 PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
125 if (BBPN && BBPN->getParent() == BB) {
126 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
127 PI != PE; PI++) {
128 if (BBPN->getIncomingValueForBlock(*PI)
129 != PN->getIncomingValueForBlock(*PI)) {
130 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
131 << Succ->getNameStart() << " is conflicting with "
132 << BBPN->getNameStart() << " with regard to common predecessor "
133 << (*PI)->getNameStart() << "\n";
134 return false;
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000135 }
136 }
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000137 // Remove this phinode from the list of phis in BB, since it has been
138 // handled.
139 BBPHIs.erase(BBPN);
140 } else {
141 Value* Val = PN->getIncomingValueForBlock(BB);
142 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
143 PI != PE; PI++) {
144 // See if the incoming value for the common predecessor is equal to the
145 // one for BB, in which case this phi node will not prevent the merging
146 // of the block.
147 if (Val != PN->getIncomingValueForBlock(*PI)) {
148 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
149 << Succ->getNameStart() << " is conflicting with regard to common "
150 << "predecessor " << (*PI)->getNameStart() << "\n";
151 return false;
152 }
153 }
Chris Lattner1aad9212005-08-03 00:59:12 +0000154 }
Chris Lattner1aad9212005-08-03 00:59:12 +0000155 }
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000156
157 // If there are any other phi nodes in BB that don't have a phi node in Succ
158 // to merge with, they must be moved to Succ completely. However, for any
159 // predecessors of Succ, branches will be added to the phi node that just
160 // point to itself. So, for any common predecessors, this must not cause
161 // conflicts.
162 for (InstrSet::iterator I = BBPHIs.begin(), E = BBPHIs.end();
163 I != E; I++) {
164 PHINode *PN = cast<PHINode>(*I);
165 for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
166 PI != PE; PI++)
167 if (PN->getIncomingValueForBlock(*PI) != PN) {
168 DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in "
169 << BB->getNameStart() << " is conflicting with regard to common "
170 << "predecessor " << (*PI)->getNameStart() << "\n";
171 return false;
172 }
173 }
174
Chris Lattner8e75ee22005-12-03 18:25:58 +0000175 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000176}
177
Chris Lattner7e663482005-08-03 00:11:16 +0000178/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
179/// branch to Succ, and contains no instructions other than PHI nodes and the
180/// branch. If possible, eliminate BB.
181static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
182 BasicBlock *Succ) {
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000183 // Check to see if merging these blocks would cause conflicts for any of the
184 // phi nodes in BB or Succ. If not, we can safely merge.
Chris Lattner3b3efc72005-08-03 00:29:26 +0000185 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner7e663482005-08-03 00:11:16 +0000186
Bill Wendling0d45a092006-11-26 10:17:54 +0000187 DOUT << "Killing Trivial BB: \n" << *BB;
Chris Lattner7e663482005-08-03 00:11:16 +0000188
Chris Lattner3b3efc72005-08-03 00:29:26 +0000189 if (isa<PHINode>(Succ->begin())) {
190 // If there is more than one pred of succ, and there are PHI nodes in
191 // the successor, then we need to add incoming edges for the PHI nodes
192 //
Chris Lattner82442432008-02-18 07:42:56 +0000193 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner3b3efc72005-08-03 00:29:26 +0000194
195 // Loop over all of the PHI nodes in the successor of BB.
196 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
197 PHINode *PN = cast<PHINode>(I);
198 Value *OldVal = PN->removeIncomingValue(BB, false);
199 assert(OldVal && "No entry in PHI for Pred BB!");
200
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000201 // If this incoming value is one of the PHI nodes in BB, the new entries
202 // in the PHI node are the entries from the old PHI.
Chris Lattner3b3efc72005-08-03 00:29:26 +0000203 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
204 PHINode *OldValPN = cast<PHINode>(OldVal);
205 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
Matthijs Kooijman5e179a22008-05-23 09:09:41 +0000206 // Note that, since we are merging phi nodes and BB and Succ might
207 // have common predecessors, we could end up with a phi node with
208 // identical incoming branches. This will be cleaned up later (and
209 // will trigger asserts if we try to clean it up now, without also
210 // simplifying the corresponding conditional branch).
Chris Lattner3b3efc72005-08-03 00:29:26 +0000211 PN->addIncoming(OldValPN->getIncomingValue(i),
212 OldValPN->getIncomingBlock(i));
213 } else {
Chris Lattner82442432008-02-18 07:42:56 +0000214 // Add an incoming value for each of the new incoming values.
215 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
216 PN->addIncoming(OldVal, BBPreds[i]);
Chris Lattner3b3efc72005-08-03 00:29:26 +0000217 }
218 }
219 }
220
Chris Lattner7e663482005-08-03 00:11:16 +0000221 if (isa<PHINode>(&BB->front())) {
Bill Wendling13524bf2009-01-19 08:46:20 +0000222 SmallVector<BasicBlock*, 16>
223 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
Chris Lattner7e663482005-08-03 00:11:16 +0000224
225 // Move all PHI nodes in BB to Succ if they are alive, otherwise
226 // delete them.
Chris Lattner9e0dad42009-01-19 02:07:32 +0000227 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000228 if (PN->use_empty()) {
229 // Just remove the dead phi. This happens if Succ's PHIs were the only
230 // users of the PHI nodes.
231 PN->eraseFromParent();
Chris Lattner9e0dad42009-01-19 02:07:32 +0000232 continue;
Chris Lattner7e663482005-08-03 00:11:16 +0000233 }
Chris Lattner9e0dad42009-01-19 02:07:32 +0000234
235 // The instruction is alive, so this means that BB must dominate all
236 // predecessors of Succ (Since all uses of the PN are after its
237 // definition, so in Succ or a block dominated by Succ. If a predecessor
238 // of Succ would not be dominated by BB, PN would violate the def before
239 // use SSA demand). Therefore, we can simply move the phi node to the
240 // next block.
241 Succ->getInstList().splice(Succ->begin(),
242 BB->getInstList(), BB->begin());
243
244 // We need to add new entries for the PHI node to account for
245 // predecessors of Succ that the PHI node does not take into
246 // account. At this point, since we know that BB dominated succ and all
247 // of its predecessors, this means that we should any newly added
248 // incoming edges should use the PHI node itself as the value for these
249 // edges, because they are loop back edges.
250 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
251 if (OldSuccPreds[i] != BB)
252 PN->addIncoming(PN, OldSuccPreds[i]);
253 }
Chris Lattner7e663482005-08-03 00:11:16 +0000254 }
255
256 // Everything that jumped to BB now goes to Succ.
Chris Lattner7e663482005-08-03 00:11:16 +0000257 BB->replaceAllUsesWith(Succ);
Chris Lattner86cc4232007-02-11 01:37:51 +0000258 if (!Succ->hasName()) Succ->takeName(BB);
Chris Lattner7e663482005-08-03 00:11:16 +0000259 BB->eraseFromParent(); // Delete the old basic block.
Chris Lattner7e663482005-08-03 00:11:16 +0000260 return true;
261}
262
Chris Lattner723c66d2004-02-11 03:36:04 +0000263/// GetIfCondition - Given a basic block (BB) with two predecessors (and
264/// presumably PHI nodes in it), check to see if the merge at this block is due
265/// to an "if condition". If so, return the boolean condition that determines
266/// which entry into BB will be taken. Also, return by references the block
267/// that will be entered from if the condition is true, and the block that will
268/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000269///
Chris Lattner723c66d2004-02-11 03:36:04 +0000270///
271static Value *GetIfCondition(BasicBlock *BB,
272 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
273 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
274 "Function can only handle blocks with 2 predecessors!");
275 BasicBlock *Pred1 = *pred_begin(BB);
276 BasicBlock *Pred2 = *++pred_begin(BB);
277
278 // We can only handle branches. Other control flow will be lowered to
279 // branches if possible anyway.
280 if (!isa<BranchInst>(Pred1->getTerminator()) ||
281 !isa<BranchInst>(Pred2->getTerminator()))
282 return 0;
283 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
284 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
285
286 // Eliminate code duplication by ensuring that Pred1Br is conditional if
287 // either are.
288 if (Pred2Br->isConditional()) {
289 // If both branches are conditional, we don't have an "if statement". In
290 // reality, we could transform this case, but since the condition will be
291 // required anyway, we stand no chance of eliminating it, so the xform is
292 // probably not profitable.
293 if (Pred1Br->isConditional())
294 return 0;
295
296 std::swap(Pred1, Pred2);
297 std::swap(Pred1Br, Pred2Br);
298 }
299
300 if (Pred1Br->isConditional()) {
301 // If we found a conditional branch predecessor, make sure that it branches
302 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
303 if (Pred1Br->getSuccessor(0) == BB &&
304 Pred1Br->getSuccessor(1) == Pred2) {
305 IfTrue = Pred1;
306 IfFalse = Pred2;
307 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
308 Pred1Br->getSuccessor(1) == BB) {
309 IfTrue = Pred2;
310 IfFalse = Pred1;
311 } else {
312 // We know that one arm of the conditional goes to BB, so the other must
313 // go somewhere unrelated, and this must not be an "if statement".
314 return 0;
315 }
316
317 // The only thing we have to watch out for here is to make sure that Pred2
318 // doesn't have incoming edges from other blocks. If it does, the condition
319 // doesn't dominate BB.
320 if (++pred_begin(Pred2) != pred_end(Pred2))
321 return 0;
322
323 return Pred1Br->getCondition();
324 }
325
326 // Ok, if we got here, both predecessors end with an unconditional branch to
327 // BB. Don't panic! If both blocks only have a single (identical)
328 // predecessor, and THAT is a conditional branch, then we're all ok!
329 if (pred_begin(Pred1) == pred_end(Pred1) ||
330 ++pred_begin(Pred1) != pred_end(Pred1) ||
331 pred_begin(Pred2) == pred_end(Pred2) ||
332 ++pred_begin(Pred2) != pred_end(Pred2) ||
333 *pred_begin(Pred1) != *pred_begin(Pred2))
334 return 0;
335
336 // Otherwise, if this is a conditional branch, then we can use it!
337 BasicBlock *CommonPred = *pred_begin(Pred1);
338 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
339 assert(BI->isConditional() && "Two successors but not conditional?");
340 if (BI->getSuccessor(0) == Pred1) {
341 IfTrue = Pred1;
342 IfFalse = Pred2;
343 } else {
344 IfTrue = Pred2;
345 IfFalse = Pred1;
346 }
347 return BI->getCondition();
348 }
349 return 0;
350}
351
Bill Wendling5049fa62009-01-19 23:43:56 +0000352/// DominatesMergePoint - If we have a merge point of an "if condition" as
353/// accepted above, return true if the specified value dominates the block. We
354/// don't handle the true generality of domination here, just a special case
355/// which works well enough for us.
356///
357/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
358/// see if V (which must be an instruction) is cheap to compute and is
359/// non-trapping. If both are true, the instruction is inserted into the set
360/// and true is returned.
Chris Lattner9c078662004-10-14 05:13:36 +0000361static bool DominatesMergePoint(Value *V, BasicBlock *BB,
362 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000363 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000364 if (!I) {
365 // Non-instructions all dominate instructions, but not all constantexprs
366 // can be executed unconditionally.
367 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
368 if (C->canTrap())
369 return false;
370 return true;
371 }
Chris Lattner570751c2004-04-09 22:50:22 +0000372 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000373
Chris Lattnerda895d62005-02-27 06:18:25 +0000374 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000375 // the bottom of this block.
376 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000377
Chris Lattner570751c2004-04-09 22:50:22 +0000378 // If this instruction is defined in a block that contains an unconditional
379 // branch to BB, then it must be in the 'conditional' part of the "if
380 // statement".
381 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
382 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner9c078662004-10-14 05:13:36 +0000383 if (!AggressiveInsts) return false;
Chris Lattner570751c2004-04-09 22:50:22 +0000384 // Okay, it looks like the instruction IS in the "condition". Check to
385 // see if its a cheap instruction to unconditionally compute, and if it
386 // only uses stuff defined outside of the condition. If so, hoist it out.
387 switch (I->getOpcode()) {
388 default: return false; // Cannot hoist this out safely.
Dale Johannesen3a56d142009-03-06 21:08:33 +0000389 case Instruction::Load: {
Chris Lattner570751c2004-04-09 22:50:22 +0000390 // We can hoist loads that are non-volatile and obviously cannot trap.
391 if (cast<LoadInst>(I)->isVolatile())
392 return false;
Eli Friedman080efb82008-12-16 20:54:32 +0000393 // FIXME: A computation of a constant can trap!
Chris Lattner570751c2004-04-09 22:50:22 +0000394 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spencer460f16c2004-07-18 00:32:14 +0000395 !isa<Constant>(I->getOperand(0)))
Chris Lattner570751c2004-04-09 22:50:22 +0000396 return false;
Dale Johannesenf8bc3002009-05-13 18:25:07 +0000397 // External weak globals may have address 0, so we can't load them.
Dale Johannesen7616a4a2009-05-14 18:41:18 +0000398 Value *V2 = I->getOperand(0)->getUnderlyingObject();
399 if (V2) {
400 GlobalVariable* GV = dyn_cast<GlobalVariable>(V2);
401 if (GV && GV->hasExternalWeakLinkage())
402 return false;
403 }
Chris Lattner570751c2004-04-09 22:50:22 +0000404 // Finally, we have to check to make sure there are no instructions
405 // before the load in its basic block, as we are going to hoist the loop
406 // out to its predecessor.
Dale Johannesen3a56d142009-03-06 21:08:33 +0000407 BasicBlock::iterator IP = PBB->begin();
408 while (isa<DbgInfoIntrinsic>(IP))
409 IP++;
410 if (IP != BasicBlock::iterator(I))
Chris Lattner570751c2004-04-09 22:50:22 +0000411 return false;
412 break;
Dale Johannesen3a56d142009-03-06 21:08:33 +0000413 }
Chris Lattner570751c2004-04-09 22:50:22 +0000414 case Instruction::Add:
415 case Instruction::Sub:
416 case Instruction::And:
417 case Instruction::Or:
418 case Instruction::Xor:
419 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000420 case Instruction::LShr:
421 case Instruction::AShr:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000422 case Instruction::ICmp:
Chris Lattner570751c2004-04-09 22:50:22 +0000423 break; // These are all cheap and non-trapping instructions.
424 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000425
Chris Lattner570751c2004-04-09 22:50:22 +0000426 // Okay, we can only really hoist these out if their operands are not
427 // defined in the conditional region.
Gabor Greiff7ea3632008-06-10 22:03:26 +0000428 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
429 if (!DominatesMergePoint(*i, BB, 0))
Chris Lattner570751c2004-04-09 22:50:22 +0000430 return false;
Chris Lattner9c078662004-10-14 05:13:36 +0000431 // Okay, it's safe to do this! Remember this instruction.
432 AggressiveInsts->insert(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000433 }
434
Chris Lattner723c66d2004-02-11 03:36:04 +0000435 return true;
436}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000437
Bill Wendling5049fa62009-01-19 23:43:56 +0000438/// GatherConstantSetEQs - Given a potentially 'or'd together collection of
439/// icmp_eq instructions that compare a value against a constant, return the
440/// value being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000441static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000442 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443 if (Inst->getOpcode() == Instruction::ICmp &&
444 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000445 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000446 Values.push_back(C);
447 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000448 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000449 Values.push_back(C);
450 return Inst->getOperand(1);
451 }
452 } else if (Inst->getOpcode() == Instruction::Or) {
453 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
454 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
455 if (LHS == RHS)
456 return LHS;
457 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000458 }
Chris Lattner0d560082004-02-24 05:38:11 +0000459 return 0;
460}
461
Bill Wendling5049fa62009-01-19 23:43:56 +0000462/// GatherConstantSetNEs - Given a potentially 'and'd together collection of
463/// setne instructions that compare a value against a constant, return the value
464/// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000465static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000466 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000467 if (Inst->getOpcode() == Instruction::ICmp &&
468 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000469 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000470 Values.push_back(C);
471 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000472 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000473 Values.push_back(C);
474 return Inst->getOperand(1);
475 }
Chris Lattner0d560082004-02-24 05:38:11 +0000476 } else if (Inst->getOpcode() == Instruction::And) {
477 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
478 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
479 if (LHS == RHS)
480 return LHS;
481 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000482 }
Chris Lattner0d560082004-02-24 05:38:11 +0000483 return 0;
484}
485
Chris Lattner0d560082004-02-24 05:38:11 +0000486/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
487/// bunch of comparisons of one value against constants, return the value and
488/// the constants being compared.
489static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000490 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000491 if (Cond->getOpcode() == Instruction::Or) {
492 CompVal = GatherConstantSetEQs(Cond, Values);
493
494 // Return true to indicate that the condition is true if the CompVal is
495 // equal to one of the constants.
496 return true;
497 } else if (Cond->getOpcode() == Instruction::And) {
498 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanfd939082005-04-21 23:48:37 +0000499
Chris Lattner0d560082004-02-24 05:38:11 +0000500 // Return false to indicate that the condition is false if the CompVal is
501 // equal to one of the constants.
502 return false;
503 }
504 return false;
505}
506
Eli Friedman080efb82008-12-16 20:54:32 +0000507static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
508 Instruction* Cond = 0;
509 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
510 Cond = dyn_cast<Instruction>(SI->getCondition());
511 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
512 if (BI->isConditional())
513 Cond = dyn_cast<Instruction>(BI->getCondition());
514 }
515
516 TI->eraseFromParent();
517 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
518}
519
Chris Lattner9fd49552008-11-27 23:25:44 +0000520/// isValueEqualityComparison - Return true if the specified terminator checks
521/// to see if a value is equal to constant integer value.
Chris Lattner542f1492004-02-28 21:28:10 +0000522static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000523 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
524 // Do not permit merging of large switch instructions into their
525 // predecessors unless there is only one predecessor.
526 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
527 pred_end(SI->getParent())) > 128)
528 return 0;
529
Chris Lattner542f1492004-02-28 21:28:10 +0000530 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000531 }
Chris Lattner542f1492004-02-28 21:28:10 +0000532 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
533 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000534 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
535 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
536 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
537 isa<ConstantInt>(ICI->getOperand(1)))
538 return ICI->getOperand(0);
Chris Lattner542f1492004-02-28 21:28:10 +0000539 return 0;
540}
541
Bill Wendling5049fa62009-01-19 23:43:56 +0000542/// GetValueEqualityComparisonCases - Given a value comparison instruction,
543/// decode all of the 'cases' that it represents and return the 'default' block.
Chris Lattner542f1492004-02-28 21:28:10 +0000544static BasicBlock *
Misha Brukmanfd939082005-04-21 23:48:37 +0000545GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000546 std::vector<std::pair<ConstantInt*,
547 BasicBlock*> > &Cases) {
548 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
549 Cases.reserve(SI->getNumCases());
550 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000551 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000552 return SI->getDefaultDest();
553 }
554
555 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000556 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
557 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
558 BI->getSuccessor(ICI->getPredicate() ==
559 ICmpInst::ICMP_NE)));
560 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000561}
562
563
Bill Wendling5049fa62009-01-19 23:43:56 +0000564/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
565/// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000566static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000567 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
568 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
569 if (Cases[i].second == BB) {
570 Cases.erase(Cases.begin()+i);
571 --i; --e;
572 }
573}
574
Bill Wendling5049fa62009-01-19 23:43:56 +0000575/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
576/// well.
Chris Lattner623369a2005-02-24 06:17:52 +0000577static bool
578ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
579 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
580 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
581
582 // Make V1 be smaller than V2.
583 if (V1->size() > V2->size())
584 std::swap(V1, V2);
585
586 if (V1->size() == 0) return false;
587 if (V1->size() == 1) {
588 // Just scan V2.
589 ConstantInt *TheVal = (*V1)[0].first;
590 for (unsigned i = 0, e = V2->size(); i != e; ++i)
591 if (TheVal == (*V2)[i].first)
592 return true;
593 }
594
595 // Otherwise, just sort both lists and compare element by element.
596 std::sort(V1->begin(), V1->end());
597 std::sort(V2->begin(), V2->end());
598 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
599 while (i1 != e1 && i2 != e2) {
600 if ((*V1)[i1].first == (*V2)[i2].first)
601 return true;
602 if ((*V1)[i1].first < (*V2)[i2].first)
603 ++i1;
604 else
605 ++i2;
606 }
607 return false;
608}
609
Bill Wendling5049fa62009-01-19 23:43:56 +0000610/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
611/// terminator instruction and its block is known to only have a single
612/// predecessor block, check to see if that predecessor is also a value
613/// comparison with the same value, and if that comparison determines the
614/// outcome of this comparison. If so, simplify TI. This does a very limited
615/// form of jump threading.
Chris Lattner623369a2005-02-24 06:17:52 +0000616static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
617 BasicBlock *Pred) {
618 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
619 if (!PredVal) return false; // Not a value comparison in predecessor.
620
621 Value *ThisVal = isValueEqualityComparison(TI);
622 assert(ThisVal && "This isn't a value comparison!!");
623 if (ThisVal != PredVal) return false; // Different predicates.
624
625 // Find out information about when control will move from Pred to TI's block.
626 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
627 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
628 PredCases);
629 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000630
Chris Lattner623369a2005-02-24 06:17:52 +0000631 // Find information about how control leaves this block.
632 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
633 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
634 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
635
636 // If TI's block is the default block from Pred's comparison, potentially
637 // simplify TI based on this knowledge.
638 if (PredDef == TI->getParent()) {
639 // If we are here, we know that the value is none of those cases listed in
640 // PredCases. If there are any cases in ThisCases that are in PredCases, we
641 // can simplify TI.
642 if (ValuesOverlap(PredCases, ThisCases)) {
Eli Friedman080efb82008-12-16 20:54:32 +0000643 if (isa<BranchInst>(TI)) {
Chris Lattner623369a2005-02-24 06:17:52 +0000644 // Okay, one of the successors of this condbr is dead. Convert it to a
645 // uncond br.
646 assert(ThisCases.size() == 1 && "Branch can only have one case!");
Chris Lattner623369a2005-02-24 06:17:52 +0000647 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000648 Instruction *NI = BranchInst::Create(ThisDef, TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000649
650 // Remove PHI node entries for the dead edge.
651 ThisCases[0].second->removePredecessor(TI->getParent());
652
Bill Wendling0d45a092006-11-26 10:17:54 +0000653 DOUT << "Threading pred instr: " << *Pred->getTerminator()
654 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000655
Eli Friedman080efb82008-12-16 20:54:32 +0000656 EraseTerminatorInstAndDCECond(TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000657 return true;
658
659 } else {
660 SwitchInst *SI = cast<SwitchInst>(TI);
661 // Okay, TI has cases that are statically dead, prune them away.
Chris Lattnerc9951232007-04-02 01:44:59 +0000662 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000663 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
664 DeadCases.insert(PredCases[i].first);
665
Bill Wendling0d45a092006-11-26 10:17:54 +0000666 DOUT << "Threading pred instr: " << *Pred->getTerminator()
667 << "Through successor TI: " << *TI;
Chris Lattner623369a2005-02-24 06:17:52 +0000668
669 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
670 if (DeadCases.count(SI->getCaseValue(i))) {
671 SI->getSuccessor(i)->removePredecessor(TI->getParent());
672 SI->removeCase(i);
673 }
674
Bill Wendling0d45a092006-11-26 10:17:54 +0000675 DOUT << "Leaving: " << *TI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000676 return true;
677 }
678 }
679
680 } else {
681 // Otherwise, TI's block must correspond to some matched value. Find out
682 // which value (or set of values) this is.
683 ConstantInt *TIV = 0;
684 BasicBlock *TIBB = TI->getParent();
685 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000686 if (PredCases[i].second == TIBB) {
Chris Lattner623369a2005-02-24 06:17:52 +0000687 if (TIV == 0)
688 TIV = PredCases[i].first;
689 else
690 return false; // Cannot handle multiple values coming to this block.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000691 }
Chris Lattner623369a2005-02-24 06:17:52 +0000692 assert(TIV && "No edge from pred to succ?");
693
694 // Okay, we found the one constant that our value can be if we get into TI's
695 // BB. Find out which successor will unconditionally be branched to.
696 BasicBlock *TheRealDest = 0;
697 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
698 if (ThisCases[i].first == TIV) {
699 TheRealDest = ThisCases[i].second;
700 break;
701 }
702
703 // If not handled by any explicit cases, it is handled by the default case.
704 if (TheRealDest == 0) TheRealDest = ThisDef;
705
706 // Remove PHI node entries for dead edges.
707 BasicBlock *CheckEdge = TheRealDest;
708 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
709 if (*SI != CheckEdge)
710 (*SI)->removePredecessor(TIBB);
711 else
712 CheckEdge = 0;
713
714 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000715 Instruction *NI = BranchInst::Create(TheRealDest, TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000716
Bill Wendling0d45a092006-11-26 10:17:54 +0000717 DOUT << "Threading pred instr: " << *Pred->getTerminator()
718 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000719
Eli Friedman080efb82008-12-16 20:54:32 +0000720 EraseTerminatorInstAndDCECond(TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000721 return true;
722 }
723 return false;
724}
725
Dale Johannesenc81f5442009-03-12 21:01:11 +0000726namespace {
727 /// ConstantIntOrdering - This class implements a stable ordering of constant
728 /// integers that does not depend on their address. This is important for
729 /// applications that sort ConstantInt's to ensure uniqueness.
730 struct ConstantIntOrdering {
731 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
732 return LHS->getValue().ult(RHS->getValue());
733 }
734 };
735}
Dale Johannesena9537cf2009-03-12 01:00:26 +0000736
Bill Wendling5049fa62009-01-19 23:43:56 +0000737/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
738/// equality comparison instruction (either a switch or a branch on "X == c").
739/// See if any of the predecessors of the terminator block are value comparisons
740/// on the same value. If so, and if safe to do so, fold them together.
Chris Lattner542f1492004-02-28 21:28:10 +0000741static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
742 BasicBlock *BB = TI->getParent();
743 Value *CV = isValueEqualityComparison(TI); // CondVal
744 assert(CV && "Not a comparison?");
745 bool Changed = false;
746
Chris Lattner82442432008-02-18 07:42:56 +0000747 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000748 while (!Preds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +0000749 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanfd939082005-04-21 23:48:37 +0000750
Chris Lattner542f1492004-02-28 21:28:10 +0000751 // See if the predecessor is a comparison with the same value.
752 TerminatorInst *PTI = Pred->getTerminator();
753 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
754
755 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
756 // Figure out which 'cases' to copy from SI to PSI.
757 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
758 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
759
760 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
761 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
762
763 // Based on whether the default edge from PTI goes to BB or not, fill in
764 // PredCases and PredDefault with the new switch cases we would like to
765 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000766 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000767
768 if (PredDefault == BB) {
769 // If this is the default destination from PTI, only the edges in TI
770 // that don't occur in PTI, or that branch to BB will be activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000771 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000772 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
773 if (PredCases[i].second != BB)
774 PTIHandled.insert(PredCases[i].first);
775 else {
776 // The default destination is BB, we don't need explicit targets.
777 std::swap(PredCases[i], PredCases.back());
778 PredCases.pop_back();
779 --i; --e;
780 }
781
782 // Reconstruct the new switch statement we will be building.
783 if (PredDefault != BBDefault) {
784 PredDefault->removePredecessor(Pred);
785 PredDefault = BBDefault;
786 NewSuccessors.push_back(BBDefault);
787 }
788 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
789 if (!PTIHandled.count(BBCases[i].first) &&
790 BBCases[i].second != BBDefault) {
791 PredCases.push_back(BBCases[i]);
792 NewSuccessors.push_back(BBCases[i].second);
793 }
794
795 } else {
796 // If this is not the default destination from PSI, only the edges
797 // in SI that occur in PSI with a destination of BB will be
798 // activated.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000799 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Chris Lattner542f1492004-02-28 21:28:10 +0000800 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
801 if (PredCases[i].second == BB) {
802 PTIHandled.insert(PredCases[i].first);
803 std::swap(PredCases[i], PredCases.back());
804 PredCases.pop_back();
805 --i; --e;
806 }
807
808 // Okay, now we know which constants were sent to BB from the
809 // predecessor. Figure out where they will all go now.
810 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
811 if (PTIHandled.count(BBCases[i].first)) {
812 // If this is one we are capable of getting...
813 PredCases.push_back(BBCases[i]);
814 NewSuccessors.push_back(BBCases[i].second);
815 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
816 }
817
818 // If there are any constants vectored to BB that TI doesn't handle,
819 // they must go to the default destination of TI.
Dale Johannesenc81f5442009-03-12 21:01:11 +0000820 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
821 PTIHandled.begin(),
Chris Lattner542f1492004-02-28 21:28:10 +0000822 E = PTIHandled.end(); I != E; ++I) {
823 PredCases.push_back(std::make_pair(*I, BBDefault));
824 NewSuccessors.push_back(BBDefault);
825 }
826 }
827
828 // Okay, at this point, we know which new successor Pred will get. Make
829 // sure we update the number of entries in the PHI nodes for these
830 // successors.
831 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
832 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
833
834 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000835 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
836 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000837 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
838 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000839
Eli Friedman080efb82008-12-16 20:54:32 +0000840 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner13b2f762005-01-01 16:02:12 +0000841
Chris Lattner542f1492004-02-28 21:28:10 +0000842 // Okay, last check. If BB is still a successor of PSI, then we must
843 // have an infinite loop case. If so, add an infinitely looping block
844 // to handle the case to preserve the behavior of the code.
845 BasicBlock *InfLoopBlock = 0;
846 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
847 if (NewSI->getSuccessor(i) == BB) {
848 if (InfLoopBlock == 0) {
Chris Lattner093a4382008-07-13 22:23:11 +0000849 // Insert it at the end of the function, because it's either code,
Chris Lattner542f1492004-02-28 21:28:10 +0000850 // or it won't matter if it's hot. :)
Gabor Greif051a9502008-04-06 20:25:17 +0000851 InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
852 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000853 }
854 NewSI->setSuccessor(i, InfLoopBlock);
855 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000856
Chris Lattner542f1492004-02-28 21:28:10 +0000857 Changed = true;
858 }
859 }
860 return Changed;
861}
862
Dale Johannesenc1f10402009-06-15 20:59:27 +0000863// isSafeToHoistInvoke - If we would need to insert a select that uses the
864// value of this invoke (comments in HoistThenElseCodeToIf explain why we
865// would need to do this), we can't hoist the invoke, as there is nowhere
866// to put the select in this case.
867static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
868 Instruction *I1, Instruction *I2) {
869 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
870 PHINode *PN;
871 for (BasicBlock::iterator BBI = SI->begin();
872 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
873 Value *BB1V = PN->getIncomingValueForBlock(BB1);
874 Value *BB2V = PN->getIncomingValueForBlock(BB2);
875 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
876 return false;
877 }
878 }
879 }
880 return true;
881}
882
Chris Lattner6306d072005-08-03 17:59:45 +0000883/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000884/// BB2, hoist any common code in the two blocks up into the branch block. The
885/// caller of this function guarantees that BI's block dominates BB1 and BB2.
886static bool HoistThenElseCodeToIf(BranchInst *BI) {
887 // This does very trivial matching, with limited scanning, to find identical
888 // instructions in the two blocks. In particular, we don't want to get into
889 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
890 // such, we currently just scan for obviously identical instructions in an
891 // identical order.
892 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
893 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
894
Devang Patel65085cf2009-02-04 00:03:08 +0000895 BasicBlock::iterator BB1_Itr = BB1->begin();
896 BasicBlock::iterator BB2_Itr = BB2->begin();
897
898 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
899 while (isa<DbgInfoIntrinsic>(I1))
900 I1 = BB1_Itr++;
901 while (isa<DbgInfoIntrinsic>(I2))
902 I2 = BB2_Itr++;
Dale Johannesenc1f10402009-06-15 20:59:27 +0000903 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
904 !I1->isIdenticalTo(I2) ||
905 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner37dc9382004-11-30 00:29:14 +0000906 return false;
907
908 // If we get here, we can hoist at least one instruction.
909 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000910
911 do {
912 // If we are hoisting the terminator instruction, don't move one (making a
913 // broken BB), instead clone it, and remove BI.
914 if (isa<TerminatorInst>(I1))
915 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000916
Chris Lattner37dc9382004-11-30 00:29:14 +0000917 // For a normal instruction, we just move one to right before the branch,
918 // then replace all uses of the other with the first. Finally, we remove
919 // the now redundant second instruction.
920 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
921 if (!I2->use_empty())
922 I2->replaceAllUsesWith(I1);
923 BB2->getInstList().erase(I2);
Misha Brukmanfd939082005-04-21 23:48:37 +0000924
Devang Patel65085cf2009-02-04 00:03:08 +0000925 I1 = BB1_Itr++;
926 while (isa<DbgInfoIntrinsic>(I1))
927 I1 = BB1_Itr++;
928 I2 = BB2_Itr++;
929 while (isa<DbgInfoIntrinsic>(I2))
930 I2 = BB2_Itr++;
Chris Lattner37dc9382004-11-30 00:29:14 +0000931 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
932
933 return true;
934
935HoistTerminator:
Dale Johannesenc1f10402009-06-15 20:59:27 +0000936 // It may not be possible to hoist an invoke.
937 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
938 return true;
939
Chris Lattner37dc9382004-11-30 00:29:14 +0000940 // Okay, it is safe to hoist the terminator.
941 Instruction *NT = I1->clone();
942 BIParent->getInstList().insert(BI, NT);
943 if (NT->getType() != Type::VoidTy) {
944 I1->replaceAllUsesWith(NT);
945 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000946 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000947 }
948
949 // Hoisting one of the terminators from our successor is a great thing.
950 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
951 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
952 // nodes, so we insert select instruction to compute the final result.
953 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
954 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
955 PHINode *PN;
956 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000957 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000958 Value *BB1V = PN->getIncomingValueForBlock(BB1);
959 Value *BB2V = PN->getIncomingValueForBlock(BB2);
960 if (BB1V != BB2V) {
961 // These values do not agree. Insert a select instruction before NT
962 // that determines the right value.
963 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
964 if (SI == 0)
Gabor Greif051a9502008-04-06 20:25:17 +0000965 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
966 BB1V->getName()+"."+BB2V->getName(), NT);
Chris Lattner37dc9382004-11-30 00:29:14 +0000967 // Make the PHI node use the select for all incoming values for BB1/BB2
968 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
969 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
970 PN->setIncomingValue(i, SI);
971 }
972 }
973 }
974
975 // Update any PHI nodes in our new successors.
976 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
977 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000978
Eli Friedman080efb82008-12-16 20:54:32 +0000979 EraseTerminatorInstAndDCECond(BI);
Chris Lattner37dc9382004-11-30 00:29:14 +0000980 return true;
981}
982
Evan Cheng4d09efd2008-06-07 08:52:29 +0000983/// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
984/// and an BB2 and the only successor of BB1 is BB2, hoist simple code
985/// (for now, restricted to a single instruction that's side effect free) from
986/// the BB1 into the branch block to speculatively execute it.
987static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
988 // Only speculatively execution a single instruction (not counting the
989 // terminator) for now.
Devang Patel06b1e672009-03-06 06:00:17 +0000990 Instruction *HInst = NULL;
991 Instruction *Term = BB1->getTerminator();
992 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end();
993 BBI != BBE; ++BBI) {
994 Instruction *I = BBI;
995 // Skip debug info.
996 if (isa<DbgInfoIntrinsic>(I)) continue;
997 if (I == Term) break;
998
999 if (!HInst)
1000 HInst = I;
1001 else
1002 return false;
1003 }
1004 if (!HInst)
1005 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001006
Evan Cheng797d9512008-06-11 19:18:20 +00001007 // Be conservative for now. FP select instruction can often be expensive.
1008 Value *BrCond = BI->getCondition();
1009 if (isa<Instruction>(BrCond) &&
1010 cast<Instruction>(BrCond)->getOpcode() == Instruction::FCmp)
1011 return false;
1012
Evan Cheng4d09efd2008-06-07 08:52:29 +00001013 // If BB1 is actually on the false edge of the conditional branch, remember
1014 // to swap the select operands later.
1015 bool Invert = false;
1016 if (BB1 != BI->getSuccessor(0)) {
1017 assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
1018 Invert = true;
1019 }
1020
1021 // Turn
1022 // BB:
1023 // %t1 = icmp
1024 // br i1 %t1, label %BB1, label %BB2
1025 // BB1:
1026 // %t3 = add %t2, c
1027 // br label BB2
1028 // BB2:
1029 // =>
1030 // BB:
1031 // %t1 = icmp
1032 // %t4 = add %t2, c
1033 // %t3 = select i1 %t1, %t2, %t3
Devang Patel06b1e672009-03-06 06:00:17 +00001034 switch (HInst->getOpcode()) {
Evan Cheng4d09efd2008-06-07 08:52:29 +00001035 default: return false; // Not safe / profitable to hoist.
1036 case Instruction::Add:
1037 case Instruction::Sub:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001038 // Not worth doing for vector ops.
1039 if (isa<VectorType>(HInst->getType()))
Chris Lattner9dd3b612009-01-18 23:22:07 +00001040 return false;
1041 break;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001042 case Instruction::And:
1043 case Instruction::Or:
1044 case Instruction::Xor:
1045 case Instruction::Shl:
1046 case Instruction::LShr:
1047 case Instruction::AShr:
Chris Lattner9dd3b612009-01-18 23:22:07 +00001048 // Don't mess with vector operations.
Devang Patel06b1e672009-03-06 06:00:17 +00001049 if (isa<VectorType>(HInst->getType()))
Evan Chenge5334ea2008-06-25 07:50:12 +00001050 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001051 break; // These are all cheap and non-trapping instructions.
1052 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001053
1054 // If the instruction is obviously dead, don't try to predicate it.
Devang Patel06b1e672009-03-06 06:00:17 +00001055 if (HInst->use_empty()) {
1056 HInst->eraseFromParent();
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001057 return true;
1058 }
Evan Cheng4d09efd2008-06-07 08:52:29 +00001059
1060 // Can we speculatively execute the instruction? And what is the value
1061 // if the condition is false? Consider the phi uses, if the incoming value
1062 // from the "if" block are all the same V, then V is the value of the
1063 // select if the condition is false.
1064 BasicBlock *BIParent = BI->getParent();
1065 SmallVector<PHINode*, 4> PHIUses;
1066 Value *FalseV = NULL;
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001067
1068 BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
Devang Patel06b1e672009-03-06 06:00:17 +00001069 for (Value::use_iterator UI = HInst->use_begin(), E = HInst->use_end();
Evan Cheng4d09efd2008-06-07 08:52:29 +00001070 UI != E; ++UI) {
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001071 // Ignore any user that is not a PHI node in BB2. These can only occur in
1072 // unreachable blocks, because they would not be dominated by the instr.
Evan Cheng4d09efd2008-06-07 08:52:29 +00001073 PHINode *PN = dyn_cast<PHINode>(UI);
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001074 if (!PN || PN->getParent() != BB2)
1075 return false;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001076 PHIUses.push_back(PN);
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001077
Evan Cheng4d09efd2008-06-07 08:52:29 +00001078 Value *PHIV = PN->getIncomingValueForBlock(BIParent);
1079 if (!FalseV)
1080 FalseV = PHIV;
1081 else if (FalseV != PHIV)
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001082 return false; // Inconsistent value when condition is false.
Evan Cheng4d09efd2008-06-07 08:52:29 +00001083 }
Chris Lattner6fe73bb2009-01-19 00:36:37 +00001084
1085 assert(FalseV && "Must have at least one user, and it must be a PHI");
Evan Cheng4d09efd2008-06-07 08:52:29 +00001086
Evan Cheng502a4f52008-06-12 21:15:59 +00001087 // Do not hoist the instruction if any of its operands are defined but not
1088 // used in this BB. The transformation will prevent the operand from
1089 // being sunk into the use block.
Devang Patel06b1e672009-03-06 06:00:17 +00001090 for (User::op_iterator i = HInst->op_begin(), e = HInst->op_end();
1091 i != e; ++i) {
Evan Cheng502a4f52008-06-12 21:15:59 +00001092 Instruction *OpI = dyn_cast<Instruction>(*i);
1093 if (OpI && OpI->getParent() == BIParent &&
1094 !OpI->isUsedInBasicBlock(BIParent))
1095 return false;
1096 }
1097
Devang Patel3d0a9a32008-09-18 22:50:42 +00001098 // If we get here, we can hoist the instruction. Try to place it
Dale Johannesen990afed2009-03-13 01:05:24 +00001099 // before the icmp instruction preceding the conditional branch.
Devang Patel3d0a9a32008-09-18 22:50:42 +00001100 BasicBlock::iterator InsertPos = BI;
Dale Johannesen990afed2009-03-13 01:05:24 +00001101 if (InsertPos != BIParent->begin())
1102 --InsertPos;
1103 // Skip debug info between condition and branch.
1104 while (InsertPos != BIParent->begin() && isa<DbgInfoIntrinsic>(InsertPos))
Devang Patel3d0a9a32008-09-18 22:50:42 +00001105 --InsertPos;
Devang Patel20da1f02008-10-03 18:57:37 +00001106 if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
Devang Patel3d0a9a32008-09-18 22:50:42 +00001107 SmallPtrSet<Instruction *, 4> BB1Insns;
1108 for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end();
1109 BB1I != BB1E; ++BB1I)
1110 BB1Insns.insert(BB1I);
1111 for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
1112 UI != UE; ++UI) {
1113 Instruction *Use = cast<Instruction>(*UI);
1114 if (BB1Insns.count(Use)) {
1115 // If BrCond uses the instruction that place it just before
1116 // branch instruction.
1117 InsertPos = BI;
1118 break;
1119 }
1120 }
1121 } else
1122 InsertPos = BI;
Devang Patel06b1e672009-03-06 06:00:17 +00001123 BIParent->getInstList().splice(InsertPos, BB1->getInstList(), HInst);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001124
1125 // Create a select whose true value is the speculatively executed value and
1126 // false value is the previously determined FalseV.
1127 SelectInst *SI;
1128 if (Invert)
Devang Patel06b1e672009-03-06 06:00:17 +00001129 SI = SelectInst::Create(BrCond, FalseV, HInst,
1130 FalseV->getName() + "." + HInst->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001131 else
Devang Patel06b1e672009-03-06 06:00:17 +00001132 SI = SelectInst::Create(BrCond, HInst, FalseV,
1133 HInst->getName() + "." + FalseV->getName(), BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00001134
1135 // Make the PHI node use the select for all incoming values for "then" and
1136 // "if" blocks.
1137 for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
1138 PHINode *PN = PHIUses[i];
1139 for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
1140 if (PN->getIncomingBlock(j) == BB1 ||
1141 PN->getIncomingBlock(j) == BIParent)
1142 PN->setIncomingValue(j, SI);
1143 }
1144
Evan Cheng502a4f52008-06-12 21:15:59 +00001145 ++NumSpeculations;
Evan Cheng4d09efd2008-06-07 08:52:29 +00001146 return true;
1147}
1148
Chris Lattner2e42e362005-09-20 00:43:16 +00001149/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1150/// across this block.
1151static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1152 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +00001153 unsigned Size = 0;
1154
Devang Patel9200c892009-03-10 18:00:05 +00001155 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesen8483e542009-03-12 23:18:09 +00001156 if (isa<DbgInfoIntrinsic>(BBI))
1157 continue;
Chris Lattnere9487f02005-09-20 01:48:40 +00001158 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesen8483e542009-03-12 23:18:09 +00001159 ++Size;
Chris Lattner2e42e362005-09-20 00:43:16 +00001160
Dale Johannesen8483e542009-03-12 23:18:09 +00001161 // We can only support instructions that do not define values that are
Chris Lattnere9487f02005-09-20 01:48:40 +00001162 // live outside of the current basic block.
1163 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
1164 UI != E; ++UI) {
1165 Instruction *U = cast<Instruction>(*UI);
1166 if (U->getParent() != BB || isa<PHINode>(U)) return false;
1167 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001168
1169 // Looks ok, continue checking.
1170 }
Chris Lattnere9487f02005-09-20 01:48:40 +00001171
Chris Lattner2e42e362005-09-20 00:43:16 +00001172 return true;
1173}
1174
Chris Lattnereaba3a12005-09-19 23:49:37 +00001175/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1176/// that is defined in the same block as the branch and if any PHI entries are
1177/// constants, thread edges corresponding to that entry to be branches to their
1178/// ultimate destination.
1179static bool FoldCondBranchOnPHI(BranchInst *BI) {
1180 BasicBlock *BB = BI->getParent();
Owen Anderson50895512009-07-06 18:42:36 +00001181 LLVMContext* Context = BB->getContext();
Chris Lattnereaba3a12005-09-19 23:49:37 +00001182 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001183 // NOTE: we currently cannot transform this case if the PHI node is used
1184 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001185 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1186 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001187
1188 // Degenerate case of a single entry PHI.
1189 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001190 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001191 return true;
1192 }
1193
1194 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001195 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001196
1197 // Okay, this is a simple enough basic block. See if any phi values are
1198 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001199 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1200 ConstantInt *CB;
1201 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001202 CB->getType() == Type::Int1Ty) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001203 // Okay, we now know that all edges from PredBB should be revectored to
1204 // branch to RealDest.
1205 BasicBlock *PredBB = PN->getIncomingBlock(i);
Reid Spencer579dca12007-01-12 04:24:46 +00001206 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001207
Chris Lattnere9487f02005-09-20 01:48:40 +00001208 if (RealDest == BB) continue; // Skip self loops.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001209
Chris Lattnere9487f02005-09-20 01:48:40 +00001210 // The dest block might have PHI nodes, other predecessors and other
1211 // difficult cases. Instead of being smart about this, just insert a new
1212 // block that jumps to the destination block, effectively splitting
1213 // the edge we are about to create.
Gabor Greif051a9502008-04-06 20:25:17 +00001214 BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
1215 RealDest->getParent(), RealDest);
1216 BranchInst::Create(RealDest, EdgeBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001217 PHINode *PN;
1218 for (BasicBlock::iterator BBI = RealDest->begin();
1219 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1220 Value *V = PN->getIncomingValueForBlock(BB);
1221 PN->addIncoming(V, EdgeBB);
1222 }
1223
1224 // BB may have instructions that are being threaded over. Clone these
1225 // instructions into EdgeBB. We know that there will be no uses of the
1226 // cloned instructions outside of EdgeBB.
1227 BasicBlock::iterator InsertPt = EdgeBB->begin();
1228 std::map<Value*, Value*> TranslateMap; // Track translated values.
1229 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1230 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1231 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1232 } else {
1233 // Clone the instruction.
1234 Instruction *N = BBI->clone();
1235 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1236
1237 // Update operands due to translation.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001238 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1239 i != e; ++i) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001240 std::map<Value*, Value*>::iterator PI =
Gabor Greiff7ea3632008-06-10 22:03:26 +00001241 TranslateMap.find(*i);
Chris Lattnere9487f02005-09-20 01:48:40 +00001242 if (PI != TranslateMap.end())
Gabor Greiff7ea3632008-06-10 22:03:26 +00001243 *i = PI->second;
Chris Lattnere9487f02005-09-20 01:48:40 +00001244 }
1245
1246 // Check for trivial simplification.
Owen Anderson50895512009-07-06 18:42:36 +00001247 if (Constant *C = ConstantFoldInstruction(N, Context)) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001248 TranslateMap[BBI] = C;
1249 delete N; // Constant folded away, don't need actual inst
1250 } else {
1251 // Insert the new instruction into its new home.
1252 EdgeBB->getInstList().insert(InsertPt, N);
1253 if (!BBI->use_empty())
1254 TranslateMap[BBI] = N;
1255 }
1256 }
1257 }
1258
Chris Lattnereaba3a12005-09-19 23:49:37 +00001259 // Loop over all of the edges from PredBB to BB, changing them to branch
Chris Lattnere9487f02005-09-20 01:48:40 +00001260 // to EdgeBB instead.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001261 TerminatorInst *PredBBTI = PredBB->getTerminator();
1262 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1263 if (PredBBTI->getSuccessor(i) == BB) {
1264 BB->removePredecessor(PredBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001265 PredBBTI->setSuccessor(i, EdgeBB);
Chris Lattnereaba3a12005-09-19 23:49:37 +00001266 }
1267
Chris Lattnereaba3a12005-09-19 23:49:37 +00001268 // Recurse, simplifying any other constants.
1269 return FoldCondBranchOnPHI(BI) | true;
1270 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001271 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001272
1273 return false;
1274}
1275
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001276/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1277/// PHI node, see if we can eliminate it.
1278static bool FoldTwoEntryPHINode(PHINode *PN) {
Owen Anderson0a205a42009-07-05 22:41:43 +00001279 LLVMContext* Context = PN->getParent()->getContext();
1280
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001281 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1282 // statement", which has a very simple dominance structure. Basically, we
1283 // are trying to find the condition that is being branched on, which
1284 // subsequently causes this merge to happen. We really want control
1285 // dependence information for this check, but simplifycfg can't keep it up
1286 // to date, and this catches most of the cases we care about anyway.
1287 //
1288 BasicBlock *BB = PN->getParent();
1289 BasicBlock *IfTrue, *IfFalse;
1290 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1291 if (!IfCond) return false;
1292
Chris Lattner822a8792006-11-18 19:19:36 +00001293 // Okay, we found that we can merge this two-entry phi node into a select.
1294 // Doing so would require us to fold *all* two entry phi nodes in this block.
1295 // At some point this becomes non-profitable (particularly if the target
1296 // doesn't support cmov's). Only do this transformation if there are two or
1297 // fewer PHI nodes in this block.
1298 unsigned NumPhis = 0;
1299 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1300 if (NumPhis > 2)
1301 return false;
1302
Bill Wendling0d45a092006-11-26 10:17:54 +00001303 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1304 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001305
1306 // Loop over the PHI's seeing if we can promote them all to select
1307 // instructions. While we are at it, keep track of the instructions
1308 // that need to be moved to the dominating block.
1309 std::set<Instruction*> AggressiveInsts;
1310
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001311 BasicBlock::iterator AfterPHIIt = BB->begin();
1312 while (isa<PHINode>(AfterPHIIt)) {
1313 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1314 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1315 if (PN->getIncomingValue(0) != PN)
1316 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1317 else
Owen Anderson0a205a42009-07-05 22:41:43 +00001318 PN->replaceAllUsesWith(Context->getUndef(PN->getType()));
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001319 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1320 &AggressiveInsts) ||
1321 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1322 &AggressiveInsts)) {
Chris Lattner055dc102005-09-23 07:23:18 +00001323 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001324 }
1325 }
1326
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001327 // If we all PHI nodes are promotable, check to make sure that all
1328 // instructions in the predecessor blocks can be promoted as well. If
1329 // not, we won't be able to get rid of the control flow, so it's not
1330 // worth promoting to select instructions.
1331 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1332 PN = cast<PHINode>(BB->begin());
1333 BasicBlock *Pred = PN->getIncomingBlock(0);
1334 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1335 IfBlock1 = Pred;
1336 DomBlock = *pred_begin(Pred);
1337 for (BasicBlock::iterator I = Pred->begin();
1338 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001339 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001340 // This is not an aggressive instruction that we can promote.
1341 // Because of this, we won't be able to get rid of the control
1342 // flow, so the xform is not worth it.
1343 return false;
1344 }
1345 }
1346
1347 Pred = PN->getIncomingBlock(1);
1348 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1349 IfBlock2 = Pred;
1350 DomBlock = *pred_begin(Pred);
1351 for (BasicBlock::iterator I = Pred->begin();
1352 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001353 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001354 // This is not an aggressive instruction that we can promote.
1355 // Because of this, we won't be able to get rid of the control
1356 // flow, so the xform is not worth it.
1357 return false;
1358 }
1359 }
1360
1361 // If we can still promote the PHI nodes after this gauntlet of tests,
1362 // do all of the PHI's now.
1363
1364 // Move all 'aggressive' instructions, which are defined in the
1365 // conditional parts of the if's up to the dominating block.
1366 if (IfBlock1) {
1367 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1368 IfBlock1->getInstList(),
1369 IfBlock1->begin(),
1370 IfBlock1->getTerminator());
1371 }
1372 if (IfBlock2) {
1373 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1374 IfBlock2->getInstList(),
1375 IfBlock2->begin(),
1376 IfBlock2->getTerminator());
1377 }
1378
1379 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1380 // Change the PHI node into a select instruction.
1381 Value *TrueVal =
1382 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1383 Value *FalseVal =
1384 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1385
Gabor Greif051a9502008-04-06 20:25:17 +00001386 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001387 PN->replaceAllUsesWith(NV);
1388 NV->takeName(PN);
1389
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001390 BB->getInstList().erase(PN);
1391 }
1392 return true;
1393}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001394
Devang Patel998cbb02009-02-05 21:46:41 +00001395/// isTerminatorFirstRelevantInsn - Return true if Term is very first
1396/// instruction ignoring Phi nodes and dbg intrinsics.
1397static bool isTerminatorFirstRelevantInsn(BasicBlock *BB, Instruction *Term) {
1398 BasicBlock::iterator BBI = Term;
1399 while (BBI != BB->begin()) {
1400 --BBI;
1401 if (!isa<DbgInfoIntrinsic>(BBI))
1402 break;
1403 }
Devang Patel0464a142009-02-10 22:14:17 +00001404
1405 if (isa<PHINode>(BBI) || &*BBI == Term || isa<DbgInfoIntrinsic>(BBI))
Devang Patel998cbb02009-02-05 21:46:41 +00001406 return true;
1407 return false;
1408}
1409
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001410/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1411/// to two returning blocks, try to merge them together into one return,
1412/// introducing a select if the return values disagree.
1413static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1414 assert(BI->isConditional() && "Must be a conditional branch");
1415 BasicBlock *TrueSucc = BI->getSuccessor(0);
1416 BasicBlock *FalseSucc = BI->getSuccessor(1);
1417 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1418 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1419
1420 // Check to ensure both blocks are empty (just a return) or optionally empty
1421 // with PHI nodes. If there are other instructions, merging would cause extra
1422 // computation on one path or the other.
Devang Patel2cc86a12009-02-05 00:30:42 +00001423 if (!isTerminatorFirstRelevantInsn(TrueSucc, TrueRet))
1424 return false;
1425 if (!isTerminatorFirstRelevantInsn(FalseSucc, FalseRet))
1426 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001427
1428 // Okay, we found a branch that is going to two return nodes. If
1429 // there is no return value for this function, just change the
1430 // branch into a return.
1431 if (FalseRet->getNumOperands() == 0) {
1432 TrueSucc->removePredecessor(BI->getParent());
1433 FalseSucc->removePredecessor(BI->getParent());
1434 ReturnInst::Create(0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001435 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001436 return true;
1437 }
1438
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001439 // Otherwise, figure out what the true and false return values are
1440 // so we can insert a new select instruction.
1441 Value *TrueValue = TrueRet->getReturnValue();
1442 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001443
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001444 // Unwrap any PHI nodes in the return blocks.
1445 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1446 if (TVPN->getParent() == TrueSucc)
1447 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1448 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1449 if (FVPN->getParent() == FalseSucc)
1450 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1451
1452 // In order for this transformation to be safe, we must be able to
1453 // unconditionally execute both operands to the return. This is
1454 // normally the case, but we could have a potentially-trapping
1455 // constant expression that prevents this transformation from being
1456 // safe.
1457 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1458 if (TCV->canTrap())
1459 return false;
1460 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1461 if (FCV->canTrap())
1462 return false;
1463
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001464 // Okay, we collected all the mapped values and checked them for sanity, and
1465 // defined to really do this transformation. First, update the CFG.
1466 TrueSucc->removePredecessor(BI->getParent());
1467 FalseSucc->removePredecessor(BI->getParent());
1468
1469 // Insert select instructions where needed.
1470 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001471 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001472 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001473 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1474 } else if (isa<UndefValue>(TrueValue)) {
1475 TrueValue = FalseValue;
1476 } else {
1477 TrueValue = SelectInst::Create(BrCond, TrueValue,
1478 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001479 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001480 }
1481
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001482 Value *RI = !TrueValue ?
1483 ReturnInst::Create(BI) :
1484 ReturnInst::Create(TrueValue, BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001485
1486 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1487 << "\n " << *BI << "NewRet = " << *RI
1488 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1489
Eli Friedman080efb82008-12-16 20:54:32 +00001490 EraseTerminatorInstAndDCECond(BI);
1491
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001492 return true;
1493}
1494
Chris Lattner1347e872008-07-13 21:12:01 +00001495/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1496/// and if a predecessor branches to us and one of our successors, fold the
1497/// setcc into the predecessor and use logical operations to pick the right
1498/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001499bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001500 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001501 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1502 if (Cond == 0) return false;
1503
Chris Lattner093a4382008-07-13 22:23:11 +00001504
Chris Lattner1347e872008-07-13 21:12:01 +00001505 // Only allow this if the condition is a simple instruction that can be
1506 // executed unconditionally. It must be in the same block as the branch, and
1507 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001508 BasicBlock::iterator FrontIt = BB->front();
1509 // Ignore dbg intrinsics.
1510 while(isa<DbgInfoIntrinsic>(FrontIt))
1511 ++FrontIt;
Chris Lattner1347e872008-07-13 21:12:01 +00001512 if ((!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
Devang Pateld0a203d2009-02-04 21:39:48 +00001513 Cond->getParent() != BB || &*FrontIt != Cond || !Cond->hasOneUse()) {
Chris Lattner1347e872008-07-13 21:12:01 +00001514 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001515 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001516
Chris Lattner1347e872008-07-13 21:12:01 +00001517 // Make sure the instruction after the condition is the cond branch.
1518 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001519 // Ingore dbg intrinsics.
1520 while(isa<DbgInfoIntrinsic>(CondIt))
1521 ++CondIt;
1522 if (&*CondIt != BI) {
1523 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001524 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001525 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001526
1527 // Cond is known to be a compare or binary operator. Check to make sure that
1528 // neither operand is a potentially-trapping constant expression.
1529 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1530 if (CE->canTrap())
1531 return false;
1532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1533 if (CE->canTrap())
1534 return false;
1535
Chris Lattner1347e872008-07-13 21:12:01 +00001536
1537 // Finally, don't infinitely unroll conditional loops.
1538 BasicBlock *TrueDest = BI->getSuccessor(0);
1539 BasicBlock *FalseDest = BI->getSuccessor(1);
1540 if (TrueDest == BB || FalseDest == BB)
1541 return false;
1542
1543 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1544 BasicBlock *PredBlock = *PI;
1545 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001546
Chris Lattner093a4382008-07-13 22:23:11 +00001547 // Check that we have two conditional branches. If there is a PHI node in
1548 // the common successor, verify that the same value flows in from both
1549 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001550 if (PBI == 0 || PBI->isUnconditional() ||
1551 !SafeToMergeTerminators(BI, PBI))
1552 continue;
1553
Chris Lattner36989092008-07-13 21:20:19 +00001554 Instruction::BinaryOps Opc;
1555 bool InvertPredCond = false;
1556
1557 if (PBI->getSuccessor(0) == TrueDest)
1558 Opc = Instruction::Or;
1559 else if (PBI->getSuccessor(1) == FalseDest)
1560 Opc = Instruction::And;
1561 else if (PBI->getSuccessor(0) == FalseDest)
1562 Opc = Instruction::And, InvertPredCond = true;
1563 else if (PBI->getSuccessor(1) == TrueDest)
1564 Opc = Instruction::Or, InvertPredCond = true;
1565 else
1566 continue;
1567
Chris Lattner6ff645b2009-01-19 23:03:13 +00001568 DOUT << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB;
1569
Chris Lattner36989092008-07-13 21:20:19 +00001570 // If we need to invert the condition in the pred block to match, do so now.
1571 if (InvertPredCond) {
Chris Lattner1347e872008-07-13 21:12:01 +00001572 Value *NewCond =
1573 BinaryOperator::CreateNot(PBI->getCondition(),
Chris Lattner36989092008-07-13 21:20:19 +00001574 PBI->getCondition()->getName()+".not", PBI);
Chris Lattner1347e872008-07-13 21:12:01 +00001575 PBI->setCondition(NewCond);
1576 BasicBlock *OldTrue = PBI->getSuccessor(0);
1577 BasicBlock *OldFalse = PBI->getSuccessor(1);
1578 PBI->setSuccessor(0, OldFalse);
1579 PBI->setSuccessor(1, OldTrue);
1580 }
Chris Lattner70087f32008-07-13 21:15:11 +00001581
Chris Lattner36989092008-07-13 21:20:19 +00001582 // Clone Cond into the predecessor basic block, and or/and the
1583 // two conditions together.
1584 Instruction *New = Cond->clone();
1585 PredBlock->getInstList().insert(PBI, New);
1586 New->takeName(Cond);
1587 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001588
Chris Lattner36989092008-07-13 21:20:19 +00001589 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1590 New, "or.cond", PBI);
1591 PBI->setCondition(NewCond);
1592 if (PBI->getSuccessor(0) == BB) {
1593 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1594 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001595 }
Chris Lattner36989092008-07-13 21:20:19 +00001596 if (PBI->getSuccessor(1) == BB) {
1597 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1598 PBI->setSuccessor(1, FalseDest);
1599 }
1600 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001601 }
1602 return false;
1603}
1604
Chris Lattner867661a2008-07-13 21:53:26 +00001605/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1606/// predecessor of another block, this function tries to simplify it. We know
1607/// that PBI and BI are both conditional branches, and BI is in one of the
1608/// successor blocks of PBI - PBI branches to BI.
1609static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1610 assert(PBI->isConditional() && BI->isConditional());
1611 BasicBlock *BB = BI->getParent();
Owen Anderson0a205a42009-07-05 22:41:43 +00001612 LLVMContext* Context = BB->getContext();
Chris Lattner867661a2008-07-13 21:53:26 +00001613
1614 // If this block ends with a branch instruction, and if there is a
1615 // predecessor that ends on a branch of the same condition, make
1616 // this conditional branch redundant.
1617 if (PBI->getCondition() == BI->getCondition() &&
1618 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1619 // Okay, the outcome of this conditional branch is statically
1620 // knowable. If this block had a single pred, handle specially.
1621 if (BB->getSinglePredecessor()) {
1622 // Turn this into a branch on constant.
1623 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson0a205a42009-07-05 22:41:43 +00001624 BI->setCondition(Context->getConstantInt(Type::Int1Ty, CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001625 return true; // Nuke the branch on constant.
1626 }
1627
1628 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1629 // in the constant and simplify the block result. Subsequent passes of
1630 // simplifycfg will thread the block.
1631 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1632 PHINode *NewPN = PHINode::Create(Type::Int1Ty,
1633 BI->getCondition()->getName() + ".pr",
1634 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001635 // Okay, we're going to insert the PHI node. Since PBI is not the only
1636 // predecessor, compute the PHI'd conditional value for all of the preds.
1637 // Any predecessor where the condition is not computable we keep symbolic.
Chris Lattner867661a2008-07-13 21:53:26 +00001638 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1639 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1640 PBI != BI && PBI->isConditional() &&
1641 PBI->getCondition() == BI->getCondition() &&
1642 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1643 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson0a205a42009-07-05 22:41:43 +00001644 NewPN->addIncoming(Context->getConstantInt(Type::Int1Ty,
Chris Lattner867661a2008-07-13 21:53:26 +00001645 CondIsTrue), *PI);
1646 } else {
1647 NewPN->addIncoming(BI->getCondition(), *PI);
1648 }
1649
1650 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001651 return true;
1652 }
1653 }
1654
1655 // If this is a conditional branch in an empty block, and if any
1656 // predecessors is a conditional branch to one of our destinations,
1657 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001658 BasicBlock::iterator BBI = BB->begin();
1659 // Ignore dbg intrinsics.
1660 while (isa<DbgInfoIntrinsic>(BBI))
1661 ++BBI;
1662 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001663 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001664
1665
1666 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1667 if (CE->canTrap())
1668 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001669
1670 int PBIOp, BIOp;
1671 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1672 PBIOp = BIOp = 0;
1673 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1674 PBIOp = 0, BIOp = 1;
1675 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1676 PBIOp = 1, BIOp = 0;
1677 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1678 PBIOp = BIOp = 1;
1679 else
1680 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001681
Chris Lattnerb8245122008-07-13 22:04:41 +00001682 // Check to make sure that the other destination of this branch
1683 // isn't BB itself. If so, this is an infinite loop that will
1684 // keep getting unwound.
1685 if (PBI->getSuccessor(PBIOp) == BB)
1686 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001687
Chris Lattnerb8245122008-07-13 22:04:41 +00001688 // Do not perform this transformation if it would require
1689 // insertion of a large number of select instructions. For targets
1690 // without predication/cmovs, this is a big pessimization.
1691 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001692
Chris Lattnerb8245122008-07-13 22:04:41 +00001693 unsigned NumPhis = 0;
1694 for (BasicBlock::iterator II = CommonDest->begin();
1695 isa<PHINode>(II); ++II, ++NumPhis)
1696 if (NumPhis > 2) // Disable this xform.
1697 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001698
Chris Lattnerb8245122008-07-13 22:04:41 +00001699 // Finally, if everything is ok, fold the branches to logical ops.
1700 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1701
Chris Lattnerb8245122008-07-13 22:04:41 +00001702 DOUT << "FOLDING BRs:" << *PBI->getParent()
1703 << "AND: " << *BI->getParent();
1704
Chris Lattner093a4382008-07-13 22:23:11 +00001705
1706 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1707 // branch in it, where one edge (OtherDest) goes back to itself but the other
1708 // exits. We don't *know* that the program avoids the infinite loop
1709 // (even though that seems likely). If we do this xform naively, we'll end up
1710 // recursively unpeeling the loop. Since we know that (after the xform is
1711 // done) that the block *is* infinite if reached, we just make it an obviously
1712 // infinite loop with no cond branch.
1713 if (OtherDest == BB) {
1714 // Insert it at the end of the function, because it's either code,
1715 // or it won't matter if it's hot. :)
1716 BasicBlock *InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
1717 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1718 OtherDest = InfLoopBlock;
1719 }
1720
Chris Lattnerb8245122008-07-13 22:04:41 +00001721 DOUT << *PBI->getParent()->getParent();
1722
1723 // BI may have other predecessors. Because of this, we leave
1724 // it alone, but modify PBI.
1725
1726 // Make sure we get to CommonDest on True&True directions.
1727 Value *PBICond = PBI->getCondition();
1728 if (PBIOp)
1729 PBICond = BinaryOperator::CreateNot(PBICond,
1730 PBICond->getName()+".not",
1731 PBI);
1732 Value *BICond = BI->getCondition();
1733 if (BIOp)
1734 BICond = BinaryOperator::CreateNot(BICond,
1735 BICond->getName()+".not",
1736 PBI);
1737 // Merge the conditions.
1738 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1739
1740 // Modify PBI to branch on the new condition to the new dests.
1741 PBI->setCondition(Cond);
1742 PBI->setSuccessor(0, CommonDest);
1743 PBI->setSuccessor(1, OtherDest);
1744
1745 // OtherDest may have phi nodes. If so, add an entry from PBI's
1746 // block that are identical to the entries for BI's block.
1747 PHINode *PN;
1748 for (BasicBlock::iterator II = OtherDest->begin();
1749 (PN = dyn_cast<PHINode>(II)); ++II) {
1750 Value *V = PN->getIncomingValueForBlock(BB);
1751 PN->addIncoming(V, PBI->getParent());
1752 }
1753
1754 // We know that the CommonDest already had an edge from PBI to
1755 // it. If it has PHIs though, the PHIs may have different
1756 // entries for BB and PBI's BB. If so, insert a select to make
1757 // them agree.
1758 for (BasicBlock::iterator II = CommonDest->begin();
1759 (PN = dyn_cast<PHINode>(II)); ++II) {
1760 Value *BIV = PN->getIncomingValueForBlock(BB);
1761 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1762 Value *PBIV = PN->getIncomingValue(PBBIdx);
1763 if (BIV != PBIV) {
1764 // Insert a select in PBI to pick the right value.
1765 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1766 PBIV->getName()+".mux", PBI);
1767 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001768 }
1769 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001770
1771 DOUT << "INTO: " << *PBI->getParent();
1772
1773 DOUT << *PBI->getParent()->getParent();
1774
1775 // This basic block is probably dead. We know it has at least
1776 // one fewer predecessor.
1777 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001778}
1779
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001780
Bill Wendling5049fa62009-01-19 23:43:56 +00001781/// SimplifyCFG - This function is used to do simplification of a CFG. For
1782/// example, it adjusts branches to branches to eliminate the extra hop, it
1783/// eliminates unreachable basic blocks, and does other "peephole" optimization
1784/// of the CFG. It returns true if a modification was made.
1785///
1786/// WARNING: The entry node of a function may not be simplified.
1787///
Chris Lattnerf7703df2004-01-09 06:12:26 +00001788bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001789 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001790 Function *M = BB->getParent();
1791
1792 assert(BB && BB->getParent() && "Block not embedded in function!");
1793 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Dan Gohmanecb7a772007-03-22 16:38:57 +00001794 assert(&BB->getParent()->getEntryBlock() != BB &&
1795 "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00001796
Chris Lattner5a5c9a52008-11-27 07:54:38 +00001797 // Remove basic blocks that have no predecessors... or that just have themself
1798 // as a predecessor. These are unreachable.
1799 if (pred_begin(BB) == pred_end(BB) || BB->getSinglePredecessor() == BB) {
Bill Wendling0d45a092006-11-26 10:17:54 +00001800 DOUT << "Removing BB: \n" << *BB;
Chris Lattner71af9b02008-12-03 06:40:52 +00001801 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00001802 return true;
1803 }
1804
Chris Lattner694e37f2003-08-17 19:41:53 +00001805 // Check to see if we can constant propagate this terminator instruction
1806 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001807 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00001808
Dan Gohman882d87d2008-03-11 21:53:06 +00001809 // If there is a trivial two-entry PHI node in this basic block, and we can
1810 // eliminate it, do so now.
1811 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1812 if (PN->getNumIncomingValues() == 2)
1813 Changed |= FoldTwoEntryPHINode(PN);
1814
Chris Lattner19831ec2004-02-16 06:35:48 +00001815 // If this is a returning block with only PHI nodes in it, fold the return
1816 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +00001817 //
1818 // If any predecessor is a conditional branch that just selects among
1819 // different return values, fold the replace the branch/return with a select
1820 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +00001821 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Patel2cc86a12009-02-05 00:30:42 +00001822 if (isTerminatorFirstRelevantInsn(BB, BB->getTerminator())) {
Chris Lattner147af6b2004-04-02 18:13:43 +00001823 // Find predecessors that end with branches.
Chris Lattner82442432008-02-18 07:42:56 +00001824 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1825 SmallVector<BranchInst*, 8> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +00001826 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1827 TerminatorInst *PTI = (*PI)->getTerminator();
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001828 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001829 if (BI->isUnconditional())
1830 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +00001831 else
1832 CondBranchPreds.push_back(BI);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001833 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001834 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001835
Chris Lattner19831ec2004-02-16 06:35:48 +00001836 // If we found some, do the transformation!
Bill Wendling1c855032009-03-03 19:25:16 +00001837 if (!UncondBranchPreds.empty()) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001838 while (!UncondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001839 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
Bill Wendling0d45a092006-11-26 10:17:54 +00001840 DOUT << "FOLDING: " << *BB
1841 << "INTO UNCOND BRANCH PRED: " << *Pred;
Chris Lattner19831ec2004-02-16 06:35:48 +00001842 Instruction *UncondBranch = Pred->getTerminator();
1843 // Clone the return and add it to the end of the predecessor.
1844 Instruction *NewRet = RI->clone();
1845 Pred->getInstList().push_back(NewRet);
1846
Devang Patel5622f072009-02-24 00:05:16 +00001847 BasicBlock::iterator BBI = RI;
1848 if (BBI != BB->begin()) {
1849 // Move region end info into the predecessor.
1850 if (DbgRegionEndInst *DREI = dyn_cast<DbgRegionEndInst>(--BBI))
1851 DREI->moveBefore(NewRet);
1852 }
1853
Chris Lattner19831ec2004-02-16 06:35:48 +00001854 // If the return instruction returns a value, and if the value was a
1855 // PHI node in "BB", propagate the right value into the return.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001856 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
1857 i != e; ++i)
1858 if (PHINode *PN = dyn_cast<PHINode>(*i))
Chris Lattner19831ec2004-02-16 06:35:48 +00001859 if (PN->getParent() == BB)
Gabor Greiff7ea3632008-06-10 22:03:26 +00001860 *i = PN->getIncomingValueForBlock(Pred);
Chris Lattnerffba5822008-04-28 00:19:07 +00001861
Chris Lattner19831ec2004-02-16 06:35:48 +00001862 // Update any PHI nodes in the returning block to realize that we no
1863 // longer branch to them.
1864 BB->removePredecessor(Pred);
1865 Pred->getInstList().erase(UncondBranch);
1866 }
1867
1868 // If we eliminated all predecessors of the block, delete the block now.
1869 if (pred_begin(BB) == pred_end(BB))
1870 // We know there are no successors, so just nuke the block.
Devang Patel5622f072009-02-24 00:05:16 +00001871 M->getBasicBlockList().erase(BB);
Chris Lattner19831ec2004-02-16 06:35:48 +00001872
Chris Lattner19831ec2004-02-16 06:35:48 +00001873 return true;
1874 }
Chris Lattner147af6b2004-04-02 18:13:43 +00001875
1876 // Check out all of the conditional branches going to this return
1877 // instruction. If any of them just select between returns, change the
1878 // branch itself into a select/return pair.
1879 while (!CondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001880 BranchInst *BI = CondBranchPreds.pop_back_val();
Chris Lattner147af6b2004-04-02 18:13:43 +00001881
1882 // Check to see if the non-BB successor is also a return block.
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001883 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
1884 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
1885 SimplifyCondBranchToTwoReturns(BI))
1886 return true;
Chris Lattner147af6b2004-04-02 18:13:43 +00001887 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001888 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001889 } else if (isa<UnwindInst>(BB->begin())) {
Chris Lattnere14ea082004-02-24 05:54:22 +00001890 // Check to see if the first instruction in this block is just an unwind.
1891 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001892 // destination with call instructions, and any unconditional branch
1893 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +00001894 //
Chris Lattner82442432008-02-18 07:42:56 +00001895 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnere14ea082004-02-24 05:54:22 +00001896 while (!Preds.empty()) {
1897 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001898 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
Nick Lewycky280a6e62008-04-25 16:53:59 +00001899 if (BI->isUnconditional()) {
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001900 Pred->getInstList().pop_back(); // nuke uncond branch
1901 new UnwindInst(Pred); // Use unwind.
1902 Changed = true;
1903 }
Nick Lewycky3f4cc312008-03-09 07:50:37 +00001904 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +00001905 if (II->getUnwindDest() == BB) {
1906 // Insert a new branch instruction before the invoke, because this
1907 // is now a fall through...
Gabor Greif051a9502008-04-06 20:25:17 +00001908 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattnere14ea082004-02-24 05:54:22 +00001909 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001910
Chris Lattnere14ea082004-02-24 05:54:22 +00001911 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00001912 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00001913 CallInst *CI = CallInst::Create(II->getCalledValue(),
Gabor Greiff7ea3632008-06-10 22:03:26 +00001914 Args.begin(), Args.end(),
1915 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001916 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00001917 CI->setAttributes(II->getAttributes());
Chris Lattnere14ea082004-02-24 05:54:22 +00001918 // If the invoke produced a value, the Call now does instead
1919 II->replaceAllUsesWith(CI);
1920 delete II;
1921 Changed = true;
1922 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001923
Chris Lattnere14ea082004-02-24 05:54:22 +00001924 Preds.pop_back();
1925 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001926
1927 // If this block is now dead, remove it.
1928 if (pred_begin(BB) == pred_end(BB)) {
1929 // We know there are no successors, so just nuke the block.
1930 M->getBasicBlockList().erase(BB);
1931 return true;
1932 }
1933
Chris Lattner623369a2005-02-24 06:17:52 +00001934 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1935 if (isValueEqualityComparison(SI)) {
1936 // If we only have one predecessor, and if it is a branch on this value,
1937 // see if that predecessor totally determines the outcome of this switch.
1938 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1939 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1940 return SimplifyCFG(BB) || 1;
1941
1942 // If the block only contains the switch, see if we can fold the block
1943 // away into any preds.
Zhou Sheng9a7c7432009-02-25 15:34:27 +00001944 BasicBlock::iterator BBI = BB->begin();
1945 // Ignore dbg intrinsics.
1946 while (isa<DbgInfoIntrinsic>(BBI))
1947 ++BBI;
1948 if (SI == &*BBI)
Chris Lattner623369a2005-02-24 06:17:52 +00001949 if (FoldValueComparisonIntoPredecessors(SI))
1950 return SimplifyCFG(BB) || 1;
1951 }
Chris Lattner542f1492004-02-28 21:28:10 +00001952 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001953 if (BI->isUnconditional()) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001954 BasicBlock::iterator BBI = BB->getFirstNonPHI();
Chris Lattner7e663482005-08-03 00:11:16 +00001955
1956 BasicBlock *Succ = BI->getSuccessor(0);
Devang Pateld0a203d2009-02-04 21:39:48 +00001957 // Ignore dbg intrinsics.
1958 while (isa<DbgInfoIntrinsic>(BBI))
1959 ++BBI;
Chris Lattner7e663482005-08-03 00:11:16 +00001960 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1961 Succ != BB) // Don't hurt infinite loops!
1962 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
Chris Lattner1347e872008-07-13 21:12:01 +00001963 return true;
Chris Lattner7e663482005-08-03 00:11:16 +00001964
1965 } else { // Conditional branch
Reid Spencer3ed469c2006-11-02 20:25:50 +00001966 if (isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001967 // If we only have one predecessor, and if it is a branch on this value,
1968 // see if that predecessor totally determines the outcome of this
1969 // switch.
1970 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1971 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1972 return SimplifyCFG(BB) || 1;
1973
Chris Lattnere67fa052004-05-01 23:35:43 +00001974 // This block must be empty, except for the setcond inst, if it exists.
Devang Patel556b20a2009-02-04 01:06:11 +00001975 // Ignore dbg intrinsics.
Chris Lattnere67fa052004-05-01 23:35:43 +00001976 BasicBlock::iterator I = BB->begin();
Devang Pateld0a203d2009-02-04 21:39:48 +00001977 // Ignore dbg intrinsics.
Devang Patel556b20a2009-02-04 01:06:11 +00001978 while (isa<DbgInfoIntrinsic>(I))
Devang Pateld0a203d2009-02-04 21:39:48 +00001979 ++I;
1980 if (&*I == BI) {
Chris Lattnere67fa052004-05-01 23:35:43 +00001981 if (FoldValueComparisonIntoPredecessors(BI))
1982 return SimplifyCFG(BB) | true;
Devang Pateld0a203d2009-02-04 21:39:48 +00001983 } else if (&*I == cast<Instruction>(BI->getCondition())){
1984 ++I;
1985 // Ignore dbg intrinsics.
1986 while (isa<DbgInfoIntrinsic>(I))
1987 ++I;
1988 if(&*I == BI) {
1989 if (FoldValueComparisonIntoPredecessors(BI))
1990 return SimplifyCFG(BB) | true;
1991 }
1992 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001993 }
Devang Pateld0a203d2009-02-04 21:39:48 +00001994
Chris Lattnereaba3a12005-09-19 23:49:37 +00001995 // If this is a branch on a phi node in the current block, thread control
1996 // through this block if any PHI node entries are constants.
1997 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1998 if (PN->getParent() == BI->getParent())
1999 if (FoldCondBranchOnPHI(BI))
2000 return SimplifyCFG(BB) | true;
Chris Lattnere67fa052004-05-01 23:35:43 +00002001
2002 // If this basic block is ONLY a setcc and a branch, and if a predecessor
2003 // branches to us and one of our successors, fold the setcc into the
2004 // predecessor and use logical operations to pick the right destination.
Chris Lattner1347e872008-07-13 21:12:01 +00002005 if (FoldBranchToCommonDest(BI))
2006 return SimplifyCFG(BB) | 1;
Chris Lattnere67fa052004-05-01 23:35:43 +00002007
Chris Lattner867661a2008-07-13 21:53:26 +00002008
2009 // Scan predecessor blocks for conditional branches.
Chris Lattner2e42e362005-09-20 00:43:16 +00002010 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2011 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner867661a2008-07-13 21:53:26 +00002012 if (PBI != BI && PBI->isConditional())
2013 if (SimplifyCondBranchToCondBranch(PBI, BI))
2014 return SimplifyCFG(BB) | true;
Chris Lattnerd52c2612004-02-24 07:23:58 +00002015 }
Chris Lattner698f96f2004-10-18 04:07:22 +00002016 } else if (isa<UnreachableInst>(BB->getTerminator())) {
2017 // If there are any instructions immediately before the unreachable that can
2018 // be removed, do so.
2019 Instruction *Unreachable = BB->getTerminator();
2020 while (Unreachable != BB->begin()) {
2021 BasicBlock::iterator BBI = Unreachable;
2022 --BBI;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002023 // Do not delete instructions that can have side effects, like calls
2024 // (which may never return) and volatile loads and stores.
Dale Johannesen80b8a622009-03-12 17:42:45 +00002025 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002026
2027 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2028 if (SI->isVolatile())
2029 break;
2030
2031 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2032 if (LI->isVolatile())
2033 break;
2034
Chris Lattner698f96f2004-10-18 04:07:22 +00002035 // Delete this instruction
2036 BB->getInstList().erase(BBI);
2037 Changed = true;
2038 }
2039
2040 // If the unreachable instruction is the first in the block, take a gander
2041 // at all of the predecessors of this instruction, and simplify them.
2042 if (&BB->front() == Unreachable) {
Chris Lattner82442432008-02-18 07:42:56 +00002043 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner698f96f2004-10-18 04:07:22 +00002044 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2045 TerminatorInst *TI = Preds[i]->getTerminator();
2046
2047 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2048 if (BI->isUnconditional()) {
2049 if (BI->getSuccessor(0) == BB) {
2050 new UnreachableInst(TI);
2051 TI->eraseFromParent();
2052 Changed = true;
2053 }
2054 } else {
2055 if (BI->getSuccessor(0) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002056 BranchInst::Create(BI->getSuccessor(1), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002057 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002058 } else if (BI->getSuccessor(1) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002059 BranchInst::Create(BI->getSuccessor(0), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002060 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002061 Changed = true;
2062 }
2063 }
2064 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2065 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2066 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00002067 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00002068 SI->removeCase(i);
2069 --i; --e;
2070 Changed = true;
2071 }
2072 // If the default value is unreachable, figure out the most popular
2073 // destination and make it the default.
2074 if (SI->getSuccessor(0) == BB) {
2075 std::map<BasicBlock*, unsigned> Popularity;
2076 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2077 Popularity[SI->getSuccessor(i)]++;
2078
2079 // Find the most popular block.
2080 unsigned MaxPop = 0;
2081 BasicBlock *MaxBlock = 0;
2082 for (std::map<BasicBlock*, unsigned>::iterator
2083 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2084 if (I->second > MaxPop) {
2085 MaxPop = I->second;
2086 MaxBlock = I->first;
2087 }
2088 }
2089 if (MaxBlock) {
2090 // Make this the new default, allowing us to delete any explicit
2091 // edges to it.
2092 SI->setSuccessor(0, MaxBlock);
2093 Changed = true;
2094
Chris Lattner42eb7522005-05-20 22:19:54 +00002095 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2096 // it.
2097 if (isa<PHINode>(MaxBlock->begin()))
2098 for (unsigned i = 0; i != MaxPop-1; ++i)
2099 MaxBlock->removePredecessor(SI->getParent());
2100
Chris Lattner698f96f2004-10-18 04:07:22 +00002101 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2102 if (SI->getSuccessor(i) == MaxBlock) {
2103 SI->removeCase(i);
2104 --i; --e;
2105 }
2106 }
2107 }
2108 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2109 if (II->getUnwindDest() == BB) {
2110 // Convert the invoke to a call instruction. This would be a good
2111 // place to note that the call does not throw though.
Gabor Greif051a9502008-04-06 20:25:17 +00002112 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattner698f96f2004-10-18 04:07:22 +00002113 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00002114
Chris Lattner698f96f2004-10-18 04:07:22 +00002115 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00002116 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00002117 CallInst *CI = CallInst::Create(II->getCalledValue(),
2118 Args.begin(), Args.end(),
2119 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00002120 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00002121 CI->setAttributes(II->getAttributes());
Chris Lattner698f96f2004-10-18 04:07:22 +00002122 // If the invoke produced a value, the Call does now instead.
2123 II->replaceAllUsesWith(CI);
2124 delete II;
2125 Changed = true;
2126 }
2127 }
2128 }
2129
2130 // If this block is now dead, remove it.
2131 if (pred_begin(BB) == pred_end(BB)) {
2132 // We know there are no successors, so just nuke the block.
2133 M->getBasicBlockList().erase(BB);
2134 return true;
2135 }
2136 }
Chris Lattner19831ec2004-02-16 06:35:48 +00002137 }
2138
Chris Lattner01d1ee32002-05-21 20:50:24 +00002139 // Merge basic blocks into their predecessor if there is only one distinct
2140 // pred, and if there is only one distinct successor of the predecessor, and
2141 // if there are no PHI nodes.
2142 //
Owen Andersoncfa94192008-07-18 17:49:43 +00002143 if (MergeBlockIntoPredecessor(BB))
2144 return true;
2145
2146 // Otherwise, if this block only has a single predecessor, and if that block
2147 // is a conditional branch, see if we can hoist any code from this block up
2148 // into our predecessor.
Chris Lattner2355f942004-02-11 01:17:07 +00002149 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
2150 BasicBlock *OnlyPred = *PI++;
2151 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
2152 if (*PI != OnlyPred) {
2153 OnlyPred = 0; // There are multiple different predecessors...
2154 break;
2155 }
Owen Andersoncfa94192008-07-18 17:49:43 +00002156
Chris Lattner37dc9382004-11-30 00:29:14 +00002157 if (OnlyPred)
Chris Lattner76134372004-12-10 17:42:31 +00002158 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
2159 if (BI->isConditional()) {
2160 // Get the other block.
2161 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
2162 PI = pred_begin(OtherBB);
2163 ++PI;
Owen Andersoncfa94192008-07-18 17:49:43 +00002164
Chris Lattner76134372004-12-10 17:42:31 +00002165 if (PI == pred_end(OtherBB)) {
2166 // We have a conditional branch to two blocks that are only reachable
2167 // from the condbr. We know that the condbr dominates the two blocks,
2168 // so see if there is any identical code in the "then" and "else"
2169 // blocks. If so, we can hoist it up to the branching block.
2170 Changed |= HoistThenElseCodeToIf(BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00002171 } else {
Owen Andersoncfa94192008-07-18 17:49:43 +00002172 BasicBlock* OnlySucc = NULL;
Evan Cheng4d09efd2008-06-07 08:52:29 +00002173 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
2174 SI != SE; ++SI) {
2175 if (!OnlySucc)
2176 OnlySucc = *SI;
2177 else if (*SI != OnlySucc) {
2178 OnlySucc = 0; // There are multiple distinct successors!
2179 break;
2180 }
2181 }
2182
2183 if (OnlySucc == OtherBB) {
2184 // If BB's only successor is the other successor of the predecessor,
2185 // i.e. a triangle, see if we can hoist any code from this block up
2186 // to the "if" block.
2187 Changed |= SpeculativelyExecuteBB(BI, BB);
2188 }
Chris Lattner76134372004-12-10 17:42:31 +00002189 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002190 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002191
Chris Lattner0d560082004-02-24 05:38:11 +00002192 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2193 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2194 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2195 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
2196 Instruction *Cond = cast<Instruction>(BI->getCondition());
2197 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2198 // 'setne's and'ed together, collect them.
2199 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +00002200 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +00002201 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
Chris Lattner42a75512007-01-15 02:27:26 +00002202 if (CompVal && CompVal->getType()->isInteger()) {
Chris Lattner0d560082004-02-24 05:38:11 +00002203 // There might be duplicate constants in the list, which the switch
2204 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +00002205 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +00002206 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanfd939082005-04-21 23:48:37 +00002207
Chris Lattner0d560082004-02-24 05:38:11 +00002208 // Figure out which block is which destination.
2209 BasicBlock *DefaultBB = BI->getSuccessor(1);
2210 BasicBlock *EdgeBB = BI->getSuccessor(0);
2211 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00002212
Chris Lattner0d560082004-02-24 05:38:11 +00002213 // Create the new switch instruction now.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00002214 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
2215 Values.size(), BI);
Misha Brukmanfd939082005-04-21 23:48:37 +00002216
Chris Lattner0d560082004-02-24 05:38:11 +00002217 // Add all of the 'cases' to the switch instruction.
2218 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2219 New->addCase(Values[i], EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00002220
Chris Lattner0d560082004-02-24 05:38:11 +00002221 // We added edges from PI to the EdgeBB. As such, if there were any
2222 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2223 // the number of edges added.
2224 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +00002225 isa<PHINode>(BBI); ++BBI) {
2226 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner0d560082004-02-24 05:38:11 +00002227 Value *InVal = PN->getIncomingValueForBlock(*PI);
2228 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2229 PN->addIncoming(InVal, *PI);
2230 }
2231
2232 // Erase the old branch instruction.
Eli Friedman080efb82008-12-16 20:54:32 +00002233 EraseTerminatorInstAndDCECond(BI);
Chris Lattner0d560082004-02-24 05:38:11 +00002234 return true;
2235 }
2236 }
2237
Chris Lattner694e37f2003-08-17 19:41:53 +00002238 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002239}