blob: 2aeb0bb1cec6d815114b05f3caef5cba1f367cf5 [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();
1181 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +00001182 // NOTE: we currently cannot transform this case if the PHI node is used
1183 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +00001184 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1185 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001186
1187 // Degenerate case of a single entry PHI.
1188 if (PN->getNumIncomingValues() == 1) {
Chris Lattner29874e02008-12-03 19:44:02 +00001189 FoldSingleEntryPHINodes(PN->getParent());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001190 return true;
1191 }
1192
1193 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +00001194 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +00001195
1196 // Okay, this is a simple enough basic block. See if any phi values are
1197 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001198 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1199 ConstantInt *CB;
1200 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +00001201 CB->getType() == Type::Int1Ty) {
Chris Lattnereaba3a12005-09-19 23:49:37 +00001202 // Okay, we now know that all edges from PredBB should be revectored to
1203 // branch to RealDest.
1204 BasicBlock *PredBB = PN->getIncomingBlock(i);
Reid Spencer579dca12007-01-12 04:24:46 +00001205 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnereaba3a12005-09-19 23:49:37 +00001206
Chris Lattnere9487f02005-09-20 01:48:40 +00001207 if (RealDest == BB) continue; // Skip self loops.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001208
Chris Lattnere9487f02005-09-20 01:48:40 +00001209 // The dest block might have PHI nodes, other predecessors and other
1210 // difficult cases. Instead of being smart about this, just insert a new
1211 // block that jumps to the destination block, effectively splitting
1212 // the edge we are about to create.
Gabor Greif051a9502008-04-06 20:25:17 +00001213 BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
1214 RealDest->getParent(), RealDest);
1215 BranchInst::Create(RealDest, EdgeBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001216 PHINode *PN;
1217 for (BasicBlock::iterator BBI = RealDest->begin();
1218 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1219 Value *V = PN->getIncomingValueForBlock(BB);
1220 PN->addIncoming(V, EdgeBB);
1221 }
1222
1223 // BB may have instructions that are being threaded over. Clone these
1224 // instructions into EdgeBB. We know that there will be no uses of the
1225 // cloned instructions outside of EdgeBB.
1226 BasicBlock::iterator InsertPt = EdgeBB->begin();
1227 std::map<Value*, Value*> TranslateMap; // Track translated values.
1228 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1229 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1230 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1231 } else {
1232 // Clone the instruction.
1233 Instruction *N = BBI->clone();
1234 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1235
1236 // Update operands due to translation.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001237 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1238 i != e; ++i) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001239 std::map<Value*, Value*>::iterator PI =
Gabor Greiff7ea3632008-06-10 22:03:26 +00001240 TranslateMap.find(*i);
Chris Lattnere9487f02005-09-20 01:48:40 +00001241 if (PI != TranslateMap.end())
Gabor Greiff7ea3632008-06-10 22:03:26 +00001242 *i = PI->second;
Chris Lattnere9487f02005-09-20 01:48:40 +00001243 }
1244
1245 // Check for trivial simplification.
1246 if (Constant *C = ConstantFoldInstruction(N)) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001247 TranslateMap[BBI] = C;
1248 delete N; // Constant folded away, don't need actual inst
1249 } else {
1250 // Insert the new instruction into its new home.
1251 EdgeBB->getInstList().insert(InsertPt, N);
1252 if (!BBI->use_empty())
1253 TranslateMap[BBI] = N;
1254 }
1255 }
1256 }
1257
Chris Lattnereaba3a12005-09-19 23:49:37 +00001258 // Loop over all of the edges from PredBB to BB, changing them to branch
Chris Lattnere9487f02005-09-20 01:48:40 +00001259 // to EdgeBB instead.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001260 TerminatorInst *PredBBTI = PredBB->getTerminator();
1261 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1262 if (PredBBTI->getSuccessor(i) == BB) {
1263 BB->removePredecessor(PredBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001264 PredBBTI->setSuccessor(i, EdgeBB);
Chris Lattnereaba3a12005-09-19 23:49:37 +00001265 }
1266
Chris Lattnereaba3a12005-09-19 23:49:37 +00001267 // Recurse, simplifying any other constants.
1268 return FoldCondBranchOnPHI(BI) | true;
1269 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001270 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001271
1272 return false;
1273}
1274
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001275/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1276/// PHI node, see if we can eliminate it.
1277static bool FoldTwoEntryPHINode(PHINode *PN) {
Owen Anderson0a205a42009-07-05 22:41:43 +00001278 LLVMContext* Context = PN->getParent()->getContext();
1279
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001280 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1281 // statement", which has a very simple dominance structure. Basically, we
1282 // are trying to find the condition that is being branched on, which
1283 // subsequently causes this merge to happen. We really want control
1284 // dependence information for this check, but simplifycfg can't keep it up
1285 // to date, and this catches most of the cases we care about anyway.
1286 //
1287 BasicBlock *BB = PN->getParent();
1288 BasicBlock *IfTrue, *IfFalse;
1289 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1290 if (!IfCond) return false;
1291
Chris Lattner822a8792006-11-18 19:19:36 +00001292 // Okay, we found that we can merge this two-entry phi node into a select.
1293 // Doing so would require us to fold *all* two entry phi nodes in this block.
1294 // At some point this becomes non-profitable (particularly if the target
1295 // doesn't support cmov's). Only do this transformation if there are two or
1296 // fewer PHI nodes in this block.
1297 unsigned NumPhis = 0;
1298 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1299 if (NumPhis > 2)
1300 return false;
1301
Bill Wendling0d45a092006-11-26 10:17:54 +00001302 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1303 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001304
1305 // Loop over the PHI's seeing if we can promote them all to select
1306 // instructions. While we are at it, keep track of the instructions
1307 // that need to be moved to the dominating block.
1308 std::set<Instruction*> AggressiveInsts;
1309
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001310 BasicBlock::iterator AfterPHIIt = BB->begin();
1311 while (isa<PHINode>(AfterPHIIt)) {
1312 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1313 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1314 if (PN->getIncomingValue(0) != PN)
1315 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1316 else
Owen Anderson0a205a42009-07-05 22:41:43 +00001317 PN->replaceAllUsesWith(Context->getUndef(PN->getType()));
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001318 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1319 &AggressiveInsts) ||
1320 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1321 &AggressiveInsts)) {
Chris Lattner055dc102005-09-23 07:23:18 +00001322 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001323 }
1324 }
1325
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001326 // If we all PHI nodes are promotable, check to make sure that all
1327 // instructions in the predecessor blocks can be promoted as well. If
1328 // not, we won't be able to get rid of the control flow, so it's not
1329 // worth promoting to select instructions.
1330 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1331 PN = cast<PHINode>(BB->begin());
1332 BasicBlock *Pred = PN->getIncomingBlock(0);
1333 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1334 IfBlock1 = Pred;
1335 DomBlock = *pred_begin(Pred);
1336 for (BasicBlock::iterator I = Pred->begin();
1337 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001338 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001339 // This is not an aggressive instruction that we can promote.
1340 // Because of this, we won't be able to get rid of the control
1341 // flow, so the xform is not worth it.
1342 return false;
1343 }
1344 }
1345
1346 Pred = PN->getIncomingBlock(1);
1347 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1348 IfBlock2 = Pred;
1349 DomBlock = *pred_begin(Pred);
1350 for (BasicBlock::iterator I = Pred->begin();
1351 !isa<TerminatorInst>(I); ++I)
Devang Patel383d7ed2009-02-03 22:12:02 +00001352 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001353 // This is not an aggressive instruction that we can promote.
1354 // Because of this, we won't be able to get rid of the control
1355 // flow, so the xform is not worth it.
1356 return false;
1357 }
1358 }
1359
1360 // If we can still promote the PHI nodes after this gauntlet of tests,
1361 // do all of the PHI's now.
1362
1363 // Move all 'aggressive' instructions, which are defined in the
1364 // conditional parts of the if's up to the dominating block.
1365 if (IfBlock1) {
1366 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1367 IfBlock1->getInstList(),
1368 IfBlock1->begin(),
1369 IfBlock1->getTerminator());
1370 }
1371 if (IfBlock2) {
1372 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1373 IfBlock2->getInstList(),
1374 IfBlock2->begin(),
1375 IfBlock2->getTerminator());
1376 }
1377
1378 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1379 // Change the PHI node into a select instruction.
1380 Value *TrueVal =
1381 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1382 Value *FalseVal =
1383 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1384
Gabor Greif051a9502008-04-06 20:25:17 +00001385 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001386 PN->replaceAllUsesWith(NV);
1387 NV->takeName(PN);
1388
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001389 BB->getInstList().erase(PN);
1390 }
1391 return true;
1392}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001393
Devang Patel998cbb02009-02-05 21:46:41 +00001394/// isTerminatorFirstRelevantInsn - Return true if Term is very first
1395/// instruction ignoring Phi nodes and dbg intrinsics.
1396static bool isTerminatorFirstRelevantInsn(BasicBlock *BB, Instruction *Term) {
1397 BasicBlock::iterator BBI = Term;
1398 while (BBI != BB->begin()) {
1399 --BBI;
1400 if (!isa<DbgInfoIntrinsic>(BBI))
1401 break;
1402 }
Devang Patel0464a142009-02-10 22:14:17 +00001403
1404 if (isa<PHINode>(BBI) || &*BBI == Term || isa<DbgInfoIntrinsic>(BBI))
Devang Patel998cbb02009-02-05 21:46:41 +00001405 return true;
1406 return false;
1407}
1408
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001409/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1410/// to two returning blocks, try to merge them together into one return,
1411/// introducing a select if the return values disagree.
1412static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1413 assert(BI->isConditional() && "Must be a conditional branch");
1414 BasicBlock *TrueSucc = BI->getSuccessor(0);
1415 BasicBlock *FalseSucc = BI->getSuccessor(1);
1416 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1417 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1418
1419 // Check to ensure both blocks are empty (just a return) or optionally empty
1420 // with PHI nodes. If there are other instructions, merging would cause extra
1421 // computation on one path or the other.
Devang Patel2cc86a12009-02-05 00:30:42 +00001422 if (!isTerminatorFirstRelevantInsn(TrueSucc, TrueRet))
1423 return false;
1424 if (!isTerminatorFirstRelevantInsn(FalseSucc, FalseRet))
1425 return false;
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001426
1427 // Okay, we found a branch that is going to two return nodes. If
1428 // there is no return value for this function, just change the
1429 // branch into a return.
1430 if (FalseRet->getNumOperands() == 0) {
1431 TrueSucc->removePredecessor(BI->getParent());
1432 FalseSucc->removePredecessor(BI->getParent());
1433 ReturnInst::Create(0, BI);
Eli Friedman080efb82008-12-16 20:54:32 +00001434 EraseTerminatorInstAndDCECond(BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001435 return true;
1436 }
1437
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001438 // Otherwise, figure out what the true and false return values are
1439 // so we can insert a new select instruction.
1440 Value *TrueValue = TrueRet->getReturnValue();
1441 Value *FalseValue = FalseRet->getReturnValue();
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001442
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001443 // Unwrap any PHI nodes in the return blocks.
1444 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1445 if (TVPN->getParent() == TrueSucc)
1446 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1447 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1448 if (FVPN->getParent() == FalseSucc)
1449 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1450
1451 // In order for this transformation to be safe, we must be able to
1452 // unconditionally execute both operands to the return. This is
1453 // normally the case, but we could have a potentially-trapping
1454 // constant expression that prevents this transformation from being
1455 // safe.
1456 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1457 if (TCV->canTrap())
1458 return false;
1459 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1460 if (FCV->canTrap())
1461 return false;
1462
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001463 // Okay, we collected all the mapped values and checked them for sanity, and
1464 // defined to really do this transformation. First, update the CFG.
1465 TrueSucc->removePredecessor(BI->getParent());
1466 FalseSucc->removePredecessor(BI->getParent());
1467
1468 // Insert select instructions where needed.
1469 Value *BrCond = BI->getCondition();
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001470 if (TrueValue) {
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001471 // Insert a select if the results differ.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001472 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1473 } else if (isa<UndefValue>(TrueValue)) {
1474 TrueValue = FalseValue;
1475 } else {
1476 TrueValue = SelectInst::Create(BrCond, TrueValue,
1477 FalseValue, "retval", BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001478 }
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001479 }
1480
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001481 Value *RI = !TrueValue ?
1482 ReturnInst::Create(BI) :
1483 ReturnInst::Create(TrueValue, BI);
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001484
1485 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1486 << "\n " << *BI << "NewRet = " << *RI
1487 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1488
Eli Friedman080efb82008-12-16 20:54:32 +00001489 EraseTerminatorInstAndDCECond(BI);
1490
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001491 return true;
1492}
1493
Chris Lattner1347e872008-07-13 21:12:01 +00001494/// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
1495/// and if a predecessor branches to us and one of our successors, fold the
1496/// setcc into the predecessor and use logical operations to pick the right
1497/// destination.
Dan Gohman4b35f832009-06-27 21:30:38 +00001498bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
Chris Lattner093a4382008-07-13 22:23:11 +00001499 BasicBlock *BB = BI->getParent();
Chris Lattner1347e872008-07-13 21:12:01 +00001500 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
1501 if (Cond == 0) return false;
1502
Chris Lattner093a4382008-07-13 22:23:11 +00001503
Chris Lattner1347e872008-07-13 21:12:01 +00001504 // Only allow this if the condition is a simple instruction that can be
1505 // executed unconditionally. It must be in the same block as the branch, and
1506 // must be at the front of the block.
Devang Pateld0a203d2009-02-04 21:39:48 +00001507 BasicBlock::iterator FrontIt = BB->front();
1508 // Ignore dbg intrinsics.
1509 while(isa<DbgInfoIntrinsic>(FrontIt))
1510 ++FrontIt;
Chris Lattner1347e872008-07-13 21:12:01 +00001511 if ((!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
Devang Pateld0a203d2009-02-04 21:39:48 +00001512 Cond->getParent() != BB || &*FrontIt != Cond || !Cond->hasOneUse()) {
Chris Lattner1347e872008-07-13 21:12:01 +00001513 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001514 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001515
Chris Lattner1347e872008-07-13 21:12:01 +00001516 // Make sure the instruction after the condition is the cond branch.
1517 BasicBlock::iterator CondIt = Cond; ++CondIt;
Devang Pateld0a203d2009-02-04 21:39:48 +00001518 // Ingore dbg intrinsics.
1519 while(isa<DbgInfoIntrinsic>(CondIt))
1520 ++CondIt;
1521 if (&*CondIt != BI) {
1522 assert (!isa<DbgInfoIntrinsic>(CondIt) && "Hey do not forget debug info!");
Chris Lattner1347e872008-07-13 21:12:01 +00001523 return false;
Devang Pateld0a203d2009-02-04 21:39:48 +00001524 }
Chris Lattner6ff645b2009-01-19 23:03:13 +00001525
1526 // Cond is known to be a compare or binary operator. Check to make sure that
1527 // neither operand is a potentially-trapping constant expression.
1528 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
1529 if (CE->canTrap())
1530 return false;
1531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
1532 if (CE->canTrap())
1533 return false;
1534
Chris Lattner1347e872008-07-13 21:12:01 +00001535
1536 // Finally, don't infinitely unroll conditional loops.
1537 BasicBlock *TrueDest = BI->getSuccessor(0);
1538 BasicBlock *FalseDest = BI->getSuccessor(1);
1539 if (TrueDest == BB || FalseDest == BB)
1540 return false;
1541
1542 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1543 BasicBlock *PredBlock = *PI;
1544 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Chris Lattner6ff645b2009-01-19 23:03:13 +00001545
Chris Lattner093a4382008-07-13 22:23:11 +00001546 // Check that we have two conditional branches. If there is a PHI node in
1547 // the common successor, verify that the same value flows in from both
1548 // blocks.
Chris Lattner1347e872008-07-13 21:12:01 +00001549 if (PBI == 0 || PBI->isUnconditional() ||
1550 !SafeToMergeTerminators(BI, PBI))
1551 continue;
1552
Chris Lattner36989092008-07-13 21:20:19 +00001553 Instruction::BinaryOps Opc;
1554 bool InvertPredCond = false;
1555
1556 if (PBI->getSuccessor(0) == TrueDest)
1557 Opc = Instruction::Or;
1558 else if (PBI->getSuccessor(1) == FalseDest)
1559 Opc = Instruction::And;
1560 else if (PBI->getSuccessor(0) == FalseDest)
1561 Opc = Instruction::And, InvertPredCond = true;
1562 else if (PBI->getSuccessor(1) == TrueDest)
1563 Opc = Instruction::Or, InvertPredCond = true;
1564 else
1565 continue;
1566
Chris Lattner6ff645b2009-01-19 23:03:13 +00001567 DOUT << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB;
1568
Chris Lattner36989092008-07-13 21:20:19 +00001569 // If we need to invert the condition in the pred block to match, do so now.
1570 if (InvertPredCond) {
Chris Lattner1347e872008-07-13 21:12:01 +00001571 Value *NewCond =
1572 BinaryOperator::CreateNot(PBI->getCondition(),
Chris Lattner36989092008-07-13 21:20:19 +00001573 PBI->getCondition()->getName()+".not", PBI);
Chris Lattner1347e872008-07-13 21:12:01 +00001574 PBI->setCondition(NewCond);
1575 BasicBlock *OldTrue = PBI->getSuccessor(0);
1576 BasicBlock *OldFalse = PBI->getSuccessor(1);
1577 PBI->setSuccessor(0, OldFalse);
1578 PBI->setSuccessor(1, OldTrue);
1579 }
Chris Lattner70087f32008-07-13 21:15:11 +00001580
Chris Lattner36989092008-07-13 21:20:19 +00001581 // Clone Cond into the predecessor basic block, and or/and the
1582 // two conditions together.
1583 Instruction *New = Cond->clone();
1584 PredBlock->getInstList().insert(PBI, New);
1585 New->takeName(Cond);
1586 Cond->setName(New->getName()+".old");
Chris Lattner70087f32008-07-13 21:15:11 +00001587
Chris Lattner36989092008-07-13 21:20:19 +00001588 Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
1589 New, "or.cond", PBI);
1590 PBI->setCondition(NewCond);
1591 if (PBI->getSuccessor(0) == BB) {
1592 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1593 PBI->setSuccessor(0, TrueDest);
Chris Lattner1347e872008-07-13 21:12:01 +00001594 }
Chris Lattner36989092008-07-13 21:20:19 +00001595 if (PBI->getSuccessor(1) == BB) {
1596 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1597 PBI->setSuccessor(1, FalseDest);
1598 }
1599 return true;
Chris Lattner1347e872008-07-13 21:12:01 +00001600 }
1601 return false;
1602}
1603
Chris Lattner867661a2008-07-13 21:53:26 +00001604/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
1605/// predecessor of another block, this function tries to simplify it. We know
1606/// that PBI and BI are both conditional branches, and BI is in one of the
1607/// successor blocks of PBI - PBI branches to BI.
1608static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
1609 assert(PBI->isConditional() && BI->isConditional());
1610 BasicBlock *BB = BI->getParent();
Owen Anderson0a205a42009-07-05 22:41:43 +00001611 LLVMContext* Context = BB->getContext();
Chris Lattner867661a2008-07-13 21:53:26 +00001612
1613 // If this block ends with a branch instruction, and if there is a
1614 // predecessor that ends on a branch of the same condition, make
1615 // this conditional branch redundant.
1616 if (PBI->getCondition() == BI->getCondition() &&
1617 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1618 // Okay, the outcome of this conditional branch is statically
1619 // knowable. If this block had a single pred, handle specially.
1620 if (BB->getSinglePredecessor()) {
1621 // Turn this into a branch on constant.
1622 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson0a205a42009-07-05 22:41:43 +00001623 BI->setCondition(Context->getConstantInt(Type::Int1Ty, CondIsTrue));
Chris Lattner867661a2008-07-13 21:53:26 +00001624 return true; // Nuke the branch on constant.
1625 }
1626
1627 // Otherwise, if there are multiple predecessors, insert a PHI that merges
1628 // in the constant and simplify the block result. Subsequent passes of
1629 // simplifycfg will thread the block.
1630 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1631 PHINode *NewPN = PHINode::Create(Type::Int1Ty,
1632 BI->getCondition()->getName() + ".pr",
1633 BB->begin());
Chris Lattnereb388af2008-07-13 21:55:46 +00001634 // Okay, we're going to insert the PHI node. Since PBI is not the only
1635 // predecessor, compute the PHI'd conditional value for all of the preds.
1636 // Any predecessor where the condition is not computable we keep symbolic.
Chris Lattner867661a2008-07-13 21:53:26 +00001637 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1638 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1639 PBI != BI && PBI->isConditional() &&
1640 PBI->getCondition() == BI->getCondition() &&
1641 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1642 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Owen Anderson0a205a42009-07-05 22:41:43 +00001643 NewPN->addIncoming(Context->getConstantInt(Type::Int1Ty,
Chris Lattner867661a2008-07-13 21:53:26 +00001644 CondIsTrue), *PI);
1645 } else {
1646 NewPN->addIncoming(BI->getCondition(), *PI);
1647 }
1648
1649 BI->setCondition(NewPN);
Chris Lattner867661a2008-07-13 21:53:26 +00001650 return true;
1651 }
1652 }
1653
1654 // If this is a conditional branch in an empty block, and if any
1655 // predecessors is a conditional branch to one of our destinations,
1656 // fold the conditions into logical ops and one cond br.
Zhou Shenga8d57fe2009-02-26 06:56:37 +00001657 BasicBlock::iterator BBI = BB->begin();
1658 // Ignore dbg intrinsics.
1659 while (isa<DbgInfoIntrinsic>(BBI))
1660 ++BBI;
1661 if (&*BBI != BI)
Chris Lattnerb8245122008-07-13 22:04:41 +00001662 return false;
Chris Lattner63bf29b2009-01-20 01:15:41 +00001663
1664
1665 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
1666 if (CE->canTrap())
1667 return false;
Chris Lattnerb8245122008-07-13 22:04:41 +00001668
1669 int PBIOp, BIOp;
1670 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
1671 PBIOp = BIOp = 0;
1672 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
1673 PBIOp = 0, BIOp = 1;
1674 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
1675 PBIOp = 1, BIOp = 0;
1676 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
1677 PBIOp = BIOp = 1;
1678 else
1679 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001680
Chris Lattnerb8245122008-07-13 22:04:41 +00001681 // Check to make sure that the other destination of this branch
1682 // isn't BB itself. If so, this is an infinite loop that will
1683 // keep getting unwound.
1684 if (PBI->getSuccessor(PBIOp) == BB)
1685 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001686
Chris Lattnerb8245122008-07-13 22:04:41 +00001687 // Do not perform this transformation if it would require
1688 // insertion of a large number of select instructions. For targets
1689 // without predication/cmovs, this is a big pessimization.
1690 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner867661a2008-07-13 21:53:26 +00001691
Chris Lattnerb8245122008-07-13 22:04:41 +00001692 unsigned NumPhis = 0;
1693 for (BasicBlock::iterator II = CommonDest->begin();
1694 isa<PHINode>(II); ++II, ++NumPhis)
1695 if (NumPhis > 2) // Disable this xform.
1696 return false;
Chris Lattner867661a2008-07-13 21:53:26 +00001697
Chris Lattnerb8245122008-07-13 22:04:41 +00001698 // Finally, if everything is ok, fold the branches to logical ops.
1699 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1700
Chris Lattnerb8245122008-07-13 22:04:41 +00001701 DOUT << "FOLDING BRs:" << *PBI->getParent()
1702 << "AND: " << *BI->getParent();
1703
Chris Lattner093a4382008-07-13 22:23:11 +00001704
1705 // If OtherDest *is* BB, then BB is a basic block with a single conditional
1706 // branch in it, where one edge (OtherDest) goes back to itself but the other
1707 // exits. We don't *know* that the program avoids the infinite loop
1708 // (even though that seems likely). If we do this xform naively, we'll end up
1709 // recursively unpeeling the loop. Since we know that (after the xform is
1710 // done) that the block *is* infinite if reached, we just make it an obviously
1711 // infinite loop with no cond branch.
1712 if (OtherDest == BB) {
1713 // Insert it at the end of the function, because it's either code,
1714 // or it won't matter if it's hot. :)
1715 BasicBlock *InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
1716 BranchInst::Create(InfLoopBlock, InfLoopBlock);
1717 OtherDest = InfLoopBlock;
1718 }
1719
Chris Lattnerb8245122008-07-13 22:04:41 +00001720 DOUT << *PBI->getParent()->getParent();
1721
1722 // BI may have other predecessors. Because of this, we leave
1723 // it alone, but modify PBI.
1724
1725 // Make sure we get to CommonDest on True&True directions.
1726 Value *PBICond = PBI->getCondition();
1727 if (PBIOp)
1728 PBICond = BinaryOperator::CreateNot(PBICond,
1729 PBICond->getName()+".not",
1730 PBI);
1731 Value *BICond = BI->getCondition();
1732 if (BIOp)
1733 BICond = BinaryOperator::CreateNot(BICond,
1734 BICond->getName()+".not",
1735 PBI);
1736 // Merge the conditions.
1737 Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
1738
1739 // Modify PBI to branch on the new condition to the new dests.
1740 PBI->setCondition(Cond);
1741 PBI->setSuccessor(0, CommonDest);
1742 PBI->setSuccessor(1, OtherDest);
1743
1744 // OtherDest may have phi nodes. If so, add an entry from PBI's
1745 // block that are identical to the entries for BI's block.
1746 PHINode *PN;
1747 for (BasicBlock::iterator II = OtherDest->begin();
1748 (PN = dyn_cast<PHINode>(II)); ++II) {
1749 Value *V = PN->getIncomingValueForBlock(BB);
1750 PN->addIncoming(V, PBI->getParent());
1751 }
1752
1753 // We know that the CommonDest already had an edge from PBI to
1754 // it. If it has PHIs though, the PHIs may have different
1755 // entries for BB and PBI's BB. If so, insert a select to make
1756 // them agree.
1757 for (BasicBlock::iterator II = CommonDest->begin();
1758 (PN = dyn_cast<PHINode>(II)); ++II) {
1759 Value *BIV = PN->getIncomingValueForBlock(BB);
1760 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1761 Value *PBIV = PN->getIncomingValue(PBBIdx);
1762 if (BIV != PBIV) {
1763 // Insert a select in PBI to pick the right value.
1764 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1765 PBIV->getName()+".mux", PBI);
1766 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner867661a2008-07-13 21:53:26 +00001767 }
1768 }
Chris Lattnerb8245122008-07-13 22:04:41 +00001769
1770 DOUT << "INTO: " << *PBI->getParent();
1771
1772 DOUT << *PBI->getParent()->getParent();
1773
1774 // This basic block is probably dead. We know it has at least
1775 // one fewer predecessor.
1776 return true;
Chris Lattner867661a2008-07-13 21:53:26 +00001777}
1778
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001779
Bill Wendling5049fa62009-01-19 23:43:56 +00001780/// SimplifyCFG - This function is used to do simplification of a CFG. For
1781/// example, it adjusts branches to branches to eliminate the extra hop, it
1782/// eliminates unreachable basic blocks, and does other "peephole" optimization
1783/// of the CFG. It returns true if a modification was made.
1784///
1785/// WARNING: The entry node of a function may not be simplified.
1786///
Chris Lattnerf7703df2004-01-09 06:12:26 +00001787bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001788 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001789 Function *M = BB->getParent();
1790
1791 assert(BB && BB->getParent() && "Block not embedded in function!");
1792 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Dan Gohmanecb7a772007-03-22 16:38:57 +00001793 assert(&BB->getParent()->getEntryBlock() != BB &&
1794 "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00001795
Chris Lattner5a5c9a52008-11-27 07:54:38 +00001796 // Remove basic blocks that have no predecessors... or that just have themself
1797 // as a predecessor. These are unreachable.
1798 if (pred_begin(BB) == pred_end(BB) || BB->getSinglePredecessor() == BB) {
Bill Wendling0d45a092006-11-26 10:17:54 +00001799 DOUT << "Removing BB: \n" << *BB;
Chris Lattner71af9b02008-12-03 06:40:52 +00001800 DeleteDeadBlock(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00001801 return true;
1802 }
1803
Chris Lattner694e37f2003-08-17 19:41:53 +00001804 // Check to see if we can constant propagate this terminator instruction
1805 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001806 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00001807
Dan Gohman882d87d2008-03-11 21:53:06 +00001808 // If there is a trivial two-entry PHI node in this basic block, and we can
1809 // eliminate it, do so now.
1810 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1811 if (PN->getNumIncomingValues() == 2)
1812 Changed |= FoldTwoEntryPHINode(PN);
1813
Chris Lattner19831ec2004-02-16 06:35:48 +00001814 // If this is a returning block with only PHI nodes in it, fold the return
1815 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +00001816 //
1817 // If any predecessor is a conditional branch that just selects among
1818 // different return values, fold the replace the branch/return with a select
1819 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +00001820 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Patel2cc86a12009-02-05 00:30:42 +00001821 if (isTerminatorFirstRelevantInsn(BB, BB->getTerminator())) {
Chris Lattner147af6b2004-04-02 18:13:43 +00001822 // Find predecessors that end with branches.
Chris Lattner82442432008-02-18 07:42:56 +00001823 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1824 SmallVector<BranchInst*, 8> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +00001825 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1826 TerminatorInst *PTI = (*PI)->getTerminator();
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001827 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001828 if (BI->isUnconditional())
1829 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +00001830 else
1831 CondBranchPreds.push_back(BI);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001832 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001833 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001834
Chris Lattner19831ec2004-02-16 06:35:48 +00001835 // If we found some, do the transformation!
Bill Wendling1c855032009-03-03 19:25:16 +00001836 if (!UncondBranchPreds.empty()) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001837 while (!UncondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001838 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
Bill Wendling0d45a092006-11-26 10:17:54 +00001839 DOUT << "FOLDING: " << *BB
1840 << "INTO UNCOND BRANCH PRED: " << *Pred;
Chris Lattner19831ec2004-02-16 06:35:48 +00001841 Instruction *UncondBranch = Pred->getTerminator();
1842 // Clone the return and add it to the end of the predecessor.
1843 Instruction *NewRet = RI->clone();
1844 Pred->getInstList().push_back(NewRet);
1845
Devang Patel5622f072009-02-24 00:05:16 +00001846 BasicBlock::iterator BBI = RI;
1847 if (BBI != BB->begin()) {
1848 // Move region end info into the predecessor.
1849 if (DbgRegionEndInst *DREI = dyn_cast<DbgRegionEndInst>(--BBI))
1850 DREI->moveBefore(NewRet);
1851 }
1852
Chris Lattner19831ec2004-02-16 06:35:48 +00001853 // If the return instruction returns a value, and if the value was a
1854 // PHI node in "BB", propagate the right value into the return.
Gabor Greiff7ea3632008-06-10 22:03:26 +00001855 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
1856 i != e; ++i)
1857 if (PHINode *PN = dyn_cast<PHINode>(*i))
Chris Lattner19831ec2004-02-16 06:35:48 +00001858 if (PN->getParent() == BB)
Gabor Greiff7ea3632008-06-10 22:03:26 +00001859 *i = PN->getIncomingValueForBlock(Pred);
Chris Lattnerffba5822008-04-28 00:19:07 +00001860
Chris Lattner19831ec2004-02-16 06:35:48 +00001861 // Update any PHI nodes in the returning block to realize that we no
1862 // longer branch to them.
1863 BB->removePredecessor(Pred);
1864 Pred->getInstList().erase(UncondBranch);
1865 }
1866
1867 // If we eliminated all predecessors of the block, delete the block now.
1868 if (pred_begin(BB) == pred_end(BB))
1869 // We know there are no successors, so just nuke the block.
Devang Patel5622f072009-02-24 00:05:16 +00001870 M->getBasicBlockList().erase(BB);
Chris Lattner19831ec2004-02-16 06:35:48 +00001871
Chris Lattner19831ec2004-02-16 06:35:48 +00001872 return true;
1873 }
Chris Lattner147af6b2004-04-02 18:13:43 +00001874
1875 // Check out all of the conditional branches going to this return
1876 // instruction. If any of them just select between returns, change the
1877 // branch itself into a select/return pair.
1878 while (!CondBranchPreds.empty()) {
Dan Gohmane9d87f42009-05-06 17:22:41 +00001879 BranchInst *BI = CondBranchPreds.pop_back_val();
Chris Lattner147af6b2004-04-02 18:13:43 +00001880
1881 // Check to see if the non-BB successor is also a return block.
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001882 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
1883 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
1884 SimplifyCondBranchToTwoReturns(BI))
1885 return true;
Chris Lattner147af6b2004-04-02 18:13:43 +00001886 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001887 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001888 } else if (isa<UnwindInst>(BB->begin())) {
Chris Lattnere14ea082004-02-24 05:54:22 +00001889 // Check to see if the first instruction in this block is just an unwind.
1890 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001891 // destination with call instructions, and any unconditional branch
1892 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +00001893 //
Chris Lattner82442432008-02-18 07:42:56 +00001894 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnere14ea082004-02-24 05:54:22 +00001895 while (!Preds.empty()) {
1896 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001897 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
Nick Lewycky280a6e62008-04-25 16:53:59 +00001898 if (BI->isUnconditional()) {
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001899 Pred->getInstList().pop_back(); // nuke uncond branch
1900 new UnwindInst(Pred); // Use unwind.
1901 Changed = true;
1902 }
Nick Lewycky3f4cc312008-03-09 07:50:37 +00001903 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +00001904 if (II->getUnwindDest() == BB) {
1905 // Insert a new branch instruction before the invoke, because this
1906 // is now a fall through...
Gabor Greif051a9502008-04-06 20:25:17 +00001907 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattnere14ea082004-02-24 05:54:22 +00001908 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001909
Chris Lattnere14ea082004-02-24 05:54:22 +00001910 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00001911 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00001912 CallInst *CI = CallInst::Create(II->getCalledValue(),
Gabor Greiff7ea3632008-06-10 22:03:26 +00001913 Args.begin(), Args.end(),
1914 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001915 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00001916 CI->setAttributes(II->getAttributes());
Chris Lattnere14ea082004-02-24 05:54:22 +00001917 // If the invoke produced a value, the Call now does instead
1918 II->replaceAllUsesWith(CI);
1919 delete II;
1920 Changed = true;
1921 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001922
Chris Lattnere14ea082004-02-24 05:54:22 +00001923 Preds.pop_back();
1924 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001925
1926 // If this block is now dead, remove it.
1927 if (pred_begin(BB) == pred_end(BB)) {
1928 // We know there are no successors, so just nuke the block.
1929 M->getBasicBlockList().erase(BB);
1930 return true;
1931 }
1932
Chris Lattner623369a2005-02-24 06:17:52 +00001933 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1934 if (isValueEqualityComparison(SI)) {
1935 // If we only have one predecessor, and if it is a branch on this value,
1936 // see if that predecessor totally determines the outcome of this switch.
1937 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1938 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1939 return SimplifyCFG(BB) || 1;
1940
1941 // If the block only contains the switch, see if we can fold the block
1942 // away into any preds.
Zhou Sheng9a7c7432009-02-25 15:34:27 +00001943 BasicBlock::iterator BBI = BB->begin();
1944 // Ignore dbg intrinsics.
1945 while (isa<DbgInfoIntrinsic>(BBI))
1946 ++BBI;
1947 if (SI == &*BBI)
Chris Lattner623369a2005-02-24 06:17:52 +00001948 if (FoldValueComparisonIntoPredecessors(SI))
1949 return SimplifyCFG(BB) || 1;
1950 }
Chris Lattner542f1492004-02-28 21:28:10 +00001951 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001952 if (BI->isUnconditional()) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00001953 BasicBlock::iterator BBI = BB->getFirstNonPHI();
Chris Lattner7e663482005-08-03 00:11:16 +00001954
1955 BasicBlock *Succ = BI->getSuccessor(0);
Devang Pateld0a203d2009-02-04 21:39:48 +00001956 // Ignore dbg intrinsics.
1957 while (isa<DbgInfoIntrinsic>(BBI))
1958 ++BBI;
Chris Lattner7e663482005-08-03 00:11:16 +00001959 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1960 Succ != BB) // Don't hurt infinite loops!
1961 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
Chris Lattner1347e872008-07-13 21:12:01 +00001962 return true;
Chris Lattner7e663482005-08-03 00:11:16 +00001963
1964 } else { // Conditional branch
Reid Spencer3ed469c2006-11-02 20:25:50 +00001965 if (isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001966 // If we only have one predecessor, and if it is a branch on this value,
1967 // see if that predecessor totally determines the outcome of this
1968 // switch.
1969 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1970 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1971 return SimplifyCFG(BB) || 1;
1972
Chris Lattnere67fa052004-05-01 23:35:43 +00001973 // This block must be empty, except for the setcond inst, if it exists.
Devang Patel556b20a2009-02-04 01:06:11 +00001974 // Ignore dbg intrinsics.
Chris Lattnere67fa052004-05-01 23:35:43 +00001975 BasicBlock::iterator I = BB->begin();
Devang Pateld0a203d2009-02-04 21:39:48 +00001976 // Ignore dbg intrinsics.
Devang Patel556b20a2009-02-04 01:06:11 +00001977 while (isa<DbgInfoIntrinsic>(I))
Devang Pateld0a203d2009-02-04 21:39:48 +00001978 ++I;
1979 if (&*I == BI) {
Chris Lattnere67fa052004-05-01 23:35:43 +00001980 if (FoldValueComparisonIntoPredecessors(BI))
1981 return SimplifyCFG(BB) | true;
Devang Pateld0a203d2009-02-04 21:39:48 +00001982 } else if (&*I == cast<Instruction>(BI->getCondition())){
1983 ++I;
1984 // Ignore dbg intrinsics.
1985 while (isa<DbgInfoIntrinsic>(I))
1986 ++I;
1987 if(&*I == BI) {
1988 if (FoldValueComparisonIntoPredecessors(BI))
1989 return SimplifyCFG(BB) | true;
1990 }
1991 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001992 }
Devang Pateld0a203d2009-02-04 21:39:48 +00001993
Chris Lattnereaba3a12005-09-19 23:49:37 +00001994 // If this is a branch on a phi node in the current block, thread control
1995 // through this block if any PHI node entries are constants.
1996 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1997 if (PN->getParent() == BI->getParent())
1998 if (FoldCondBranchOnPHI(BI))
1999 return SimplifyCFG(BB) | true;
Chris Lattnere67fa052004-05-01 23:35:43 +00002000
2001 // If this basic block is ONLY a setcc and a branch, and if a predecessor
2002 // branches to us and one of our successors, fold the setcc into the
2003 // predecessor and use logical operations to pick the right destination.
Chris Lattner1347e872008-07-13 21:12:01 +00002004 if (FoldBranchToCommonDest(BI))
2005 return SimplifyCFG(BB) | 1;
Chris Lattnere67fa052004-05-01 23:35:43 +00002006
Chris Lattner867661a2008-07-13 21:53:26 +00002007
2008 // Scan predecessor blocks for conditional branches.
Chris Lattner2e42e362005-09-20 00:43:16 +00002009 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2010 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner867661a2008-07-13 21:53:26 +00002011 if (PBI != BI && PBI->isConditional())
2012 if (SimplifyCondBranchToCondBranch(PBI, BI))
2013 return SimplifyCFG(BB) | true;
Chris Lattnerd52c2612004-02-24 07:23:58 +00002014 }
Chris Lattner698f96f2004-10-18 04:07:22 +00002015 } else if (isa<UnreachableInst>(BB->getTerminator())) {
2016 // If there are any instructions immediately before the unreachable that can
2017 // be removed, do so.
2018 Instruction *Unreachable = BB->getTerminator();
2019 while (Unreachable != BB->begin()) {
2020 BasicBlock::iterator BBI = Unreachable;
2021 --BBI;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002022 // Do not delete instructions that can have side effects, like calls
2023 // (which may never return) and volatile loads and stores.
Dale Johannesen80b8a622009-03-12 17:42:45 +00002024 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Chris Lattnerf8131c92008-10-29 17:46:26 +00002025
2026 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
2027 if (SI->isVolatile())
2028 break;
2029
2030 if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
2031 if (LI->isVolatile())
2032 break;
2033
Chris Lattner698f96f2004-10-18 04:07:22 +00002034 // Delete this instruction
2035 BB->getInstList().erase(BBI);
2036 Changed = true;
2037 }
2038
2039 // If the unreachable instruction is the first in the block, take a gander
2040 // at all of the predecessors of this instruction, and simplify them.
2041 if (&BB->front() == Unreachable) {
Chris Lattner82442432008-02-18 07:42:56 +00002042 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner698f96f2004-10-18 04:07:22 +00002043 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
2044 TerminatorInst *TI = Preds[i]->getTerminator();
2045
2046 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2047 if (BI->isUnconditional()) {
2048 if (BI->getSuccessor(0) == BB) {
2049 new UnreachableInst(TI);
2050 TI->eraseFromParent();
2051 Changed = true;
2052 }
2053 } else {
2054 if (BI->getSuccessor(0) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002055 BranchInst::Create(BI->getSuccessor(1), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002056 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002057 } else if (BI->getSuccessor(1) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00002058 BranchInst::Create(BI->getSuccessor(0), BI);
Eli Friedman080efb82008-12-16 20:54:32 +00002059 EraseTerminatorInstAndDCECond(BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00002060 Changed = true;
2061 }
2062 }
2063 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2064 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2065 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00002066 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00002067 SI->removeCase(i);
2068 --i; --e;
2069 Changed = true;
2070 }
2071 // If the default value is unreachable, figure out the most popular
2072 // destination and make it the default.
2073 if (SI->getSuccessor(0) == BB) {
2074 std::map<BasicBlock*, unsigned> Popularity;
2075 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2076 Popularity[SI->getSuccessor(i)]++;
2077
2078 // Find the most popular block.
2079 unsigned MaxPop = 0;
2080 BasicBlock *MaxBlock = 0;
2081 for (std::map<BasicBlock*, unsigned>::iterator
2082 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
2083 if (I->second > MaxPop) {
2084 MaxPop = I->second;
2085 MaxBlock = I->first;
2086 }
2087 }
2088 if (MaxBlock) {
2089 // Make this the new default, allowing us to delete any explicit
2090 // edges to it.
2091 SI->setSuccessor(0, MaxBlock);
2092 Changed = true;
2093
Chris Lattner42eb7522005-05-20 22:19:54 +00002094 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
2095 // it.
2096 if (isa<PHINode>(MaxBlock->begin()))
2097 for (unsigned i = 0; i != MaxPop-1; ++i)
2098 MaxBlock->removePredecessor(SI->getParent());
2099
Chris Lattner698f96f2004-10-18 04:07:22 +00002100 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
2101 if (SI->getSuccessor(i) == MaxBlock) {
2102 SI->removeCase(i);
2103 --i; --e;
2104 }
2105 }
2106 }
2107 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
2108 if (II->getUnwindDest() == BB) {
2109 // Convert the invoke to a call instruction. This would be a good
2110 // place to note that the call does not throw though.
Gabor Greif051a9502008-04-06 20:25:17 +00002111 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattner698f96f2004-10-18 04:07:22 +00002112 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00002113
Chris Lattner698f96f2004-10-18 04:07:22 +00002114 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00002115 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00002116 CallInst *CI = CallInst::Create(II->getCalledValue(),
2117 Args.begin(), Args.end(),
2118 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00002119 CI->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00002120 CI->setAttributes(II->getAttributes());
Chris Lattner698f96f2004-10-18 04:07:22 +00002121 // If the invoke produced a value, the Call does now instead.
2122 II->replaceAllUsesWith(CI);
2123 delete II;
2124 Changed = true;
2125 }
2126 }
2127 }
2128
2129 // If this block is now dead, remove it.
2130 if (pred_begin(BB) == pred_end(BB)) {
2131 // We know there are no successors, so just nuke the block.
2132 M->getBasicBlockList().erase(BB);
2133 return true;
2134 }
2135 }
Chris Lattner19831ec2004-02-16 06:35:48 +00002136 }
2137
Chris Lattner01d1ee32002-05-21 20:50:24 +00002138 // Merge basic blocks into their predecessor if there is only one distinct
2139 // pred, and if there is only one distinct successor of the predecessor, and
2140 // if there are no PHI nodes.
2141 //
Owen Andersoncfa94192008-07-18 17:49:43 +00002142 if (MergeBlockIntoPredecessor(BB))
2143 return true;
2144
2145 // Otherwise, if this block only has a single predecessor, and if that block
2146 // is a conditional branch, see if we can hoist any code from this block up
2147 // into our predecessor.
Chris Lattner2355f942004-02-11 01:17:07 +00002148 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
2149 BasicBlock *OnlyPred = *PI++;
2150 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
2151 if (*PI != OnlyPred) {
2152 OnlyPred = 0; // There are multiple different predecessors...
2153 break;
2154 }
Owen Andersoncfa94192008-07-18 17:49:43 +00002155
Chris Lattner37dc9382004-11-30 00:29:14 +00002156 if (OnlyPred)
Chris Lattner76134372004-12-10 17:42:31 +00002157 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
2158 if (BI->isConditional()) {
2159 // Get the other block.
2160 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
2161 PI = pred_begin(OtherBB);
2162 ++PI;
Owen Andersoncfa94192008-07-18 17:49:43 +00002163
Chris Lattner76134372004-12-10 17:42:31 +00002164 if (PI == pred_end(OtherBB)) {
2165 // We have a conditional branch to two blocks that are only reachable
2166 // from the condbr. We know that the condbr dominates the two blocks,
2167 // so see if there is any identical code in the "then" and "else"
2168 // blocks. If so, we can hoist it up to the branching block.
2169 Changed |= HoistThenElseCodeToIf(BI);
Evan Cheng4d09efd2008-06-07 08:52:29 +00002170 } else {
Owen Andersoncfa94192008-07-18 17:49:43 +00002171 BasicBlock* OnlySucc = NULL;
Evan Cheng4d09efd2008-06-07 08:52:29 +00002172 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
2173 SI != SE; ++SI) {
2174 if (!OnlySucc)
2175 OnlySucc = *SI;
2176 else if (*SI != OnlySucc) {
2177 OnlySucc = 0; // There are multiple distinct successors!
2178 break;
2179 }
2180 }
2181
2182 if (OnlySucc == OtherBB) {
2183 // If BB's only successor is the other successor of the predecessor,
2184 // i.e. a triangle, see if we can hoist any code from this block up
2185 // to the "if" block.
2186 Changed |= SpeculativelyExecuteBB(BI, BB);
2187 }
Chris Lattner76134372004-12-10 17:42:31 +00002188 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002189 }
Chris Lattner37dc9382004-11-30 00:29:14 +00002190
Chris Lattner0d560082004-02-24 05:38:11 +00002191 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
2192 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
2193 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2194 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
2195 Instruction *Cond = cast<Instruction>(BI->getCondition());
2196 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2197 // 'setne's and'ed together, collect them.
2198 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +00002199 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +00002200 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
Chris Lattner42a75512007-01-15 02:27:26 +00002201 if (CompVal && CompVal->getType()->isInteger()) {
Chris Lattner0d560082004-02-24 05:38:11 +00002202 // There might be duplicate constants in the list, which the switch
2203 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +00002204 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +00002205 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanfd939082005-04-21 23:48:37 +00002206
Chris Lattner0d560082004-02-24 05:38:11 +00002207 // Figure out which block is which destination.
2208 BasicBlock *DefaultBB = BI->getSuccessor(1);
2209 BasicBlock *EdgeBB = BI->getSuccessor(0);
2210 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00002211
Chris Lattner0d560082004-02-24 05:38:11 +00002212 // Create the new switch instruction now.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00002213 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
2214 Values.size(), BI);
Misha Brukmanfd939082005-04-21 23:48:37 +00002215
Chris Lattner0d560082004-02-24 05:38:11 +00002216 // Add all of the 'cases' to the switch instruction.
2217 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2218 New->addCase(Values[i], EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00002219
Chris Lattner0d560082004-02-24 05:38:11 +00002220 // We added edges from PI to the EdgeBB. As such, if there were any
2221 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2222 // the number of edges added.
2223 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +00002224 isa<PHINode>(BBI); ++BBI) {
2225 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner0d560082004-02-24 05:38:11 +00002226 Value *InVal = PN->getIncomingValueForBlock(*PI);
2227 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2228 PN->addIncoming(InVal, *PI);
2229 }
2230
2231 // Erase the old branch instruction.
Eli Friedman080efb82008-12-16 20:54:32 +00002232 EraseTerminatorInstAndDCECond(BI);
Chris Lattner0d560082004-02-24 05:38:11 +00002233 return true;
2234 }
2235 }
2236
Chris Lattner694e37f2003-08-17 19:41:53 +00002237 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00002238}