blob: 45d3d4e144dbc76d6879cf86c2f2b87cf8fa479b [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"
Chris Lattner0d560082004-02-24 05:38:11 +000018#include "llvm/Type.h"
Reid Spencerc1030572007-01-19 21:13:56 +000019#include "llvm/DerivedTypes.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000020#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000021#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000022#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnereaba3a12005-09-19 23:49:37 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000024#include "llvm/ADT/SmallVector.h"
Chris Lattnerc9951232007-04-02 01:44:59 +000025#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000026#include <algorithm>
27#include <functional>
Chris Lattnerd52c2612004-02-24 07:23:58 +000028#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000029#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattner2bdcb562005-08-03 00:19:45 +000032/// SafeToMergeTerminators - Return true if it is safe to merge these two
33/// terminator instructions together.
34///
35static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
36 if (SI1 == SI2) return false; // Can't merge with self!
37
38 // It is not safe to merge these two switch instructions if they have a common
39 // successor, and if that successor has a PHI node, and if *that* PHI node has
40 // conflicting incoming values from the two switch blocks.
41 BasicBlock *SI1BB = SI1->getParent();
42 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerc9951232007-04-02 01:44:59 +000043 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Chris Lattner2bdcb562005-08-03 00:19:45 +000044
45 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
46 if (SI1Succs.count(*I))
47 for (BasicBlock::iterator BBI = (*I)->begin();
48 isa<PHINode>(BBI); ++BBI) {
49 PHINode *PN = cast<PHINode>(BBI);
50 if (PN->getIncomingValueForBlock(SI1BB) !=
51 PN->getIncomingValueForBlock(SI2BB))
52 return false;
53 }
54
55 return true;
56}
57
58/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
59/// now be entries in it from the 'NewPred' block. The values that will be
60/// flowing into the PHI nodes will be the same as those coming in from
61/// ExistPred, an existing predecessor of Succ.
62static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
63 BasicBlock *ExistPred) {
64 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
65 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
66 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
67
68 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
69 PHINode *PN = cast<PHINode>(I);
70 Value *V = PN->getIncomingValueForBlock(ExistPred);
71 PN->addIncoming(V, NewPred);
72 }
73}
74
Chris Lattner3b3efc72005-08-03 00:29:26 +000075// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
76// almost-empty BB ending in an unconditional branch to Succ, into succ.
Chris Lattner01d1ee32002-05-21 20:50:24 +000077//
78// Assumption: Succ is the single successor for BB.
79//
Chris Lattner3b3efc72005-08-03 00:29:26 +000080static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000081 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000082
Chris Lattner01d1ee32002-05-21 20:50:24 +000083 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattnere2ca5402003-03-05 21:01:52 +000084 // Succ. If so, we cannot do the transformation if there are any PHI nodes
85 // with incompatible values coming in from the two edges!
Chris Lattner01d1ee32002-05-21 20:50:24 +000086 //
Chris Lattnerdc88dbe2005-08-03 00:38:27 +000087 if (isa<PHINode>(Succ->front())) {
Chris Lattnerc9951232007-04-02 01:44:59 +000088 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner8e75ee22005-12-03 18:25:58 +000089 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
Chris Lattnerdc88dbe2005-08-03 00:38:27 +000090 PI != PE; ++PI)
Chris Lattnerc9951232007-04-02 01:44:59 +000091 if (BBPreds.count(*PI)) {
Chris Lattnerdc88dbe2005-08-03 00:38:27 +000092 // Loop over all of the PHI nodes checking to see if there are
93 // incompatible values coming in.
94 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
95 PHINode *PN = cast<PHINode>(I);
96 // Loop up the entries in the PHI node for BB and for *PI if the
97 // values coming in are non-equal, we cannot merge these two blocks
98 // (instead we should insert a conditional move or something, then
99 // merge the blocks).
100 if (PN->getIncomingValueForBlock(BB) !=
101 PN->getIncomingValueForBlock(*PI))
102 return false; // Values are not equal...
103 }
104 }
105 }
Chris Lattner1aad9212005-08-03 00:59:12 +0000106
107 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
108 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
109 // fold these blocks, as we don't know whether BB dominates Succ or not to
110 // update the PHI nodes correctly.
111 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000112
Devang Patel01666bf2007-12-22 01:32:53 +0000113 // If the predecessors of Succ are only BB, handle it.
Chris Lattner1aad9212005-08-03 00:59:12 +0000114 bool IsSafe = true;
115 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
Devang Patel01666bf2007-12-22 01:32:53 +0000116 if (*PI != BB) {
Chris Lattner1aad9212005-08-03 00:59:12 +0000117 IsSafe = false;
118 break;
119 }
120 if (IsSafe) return true;
121
Chris Lattner8e75ee22005-12-03 18:25:58 +0000122 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
123 // BB and Succ have no common predecessors.
Chris Lattnera0fcc3e2006-05-14 18:45:44 +0000124 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
Chris Lattner1aad9212005-08-03 00:59:12 +0000125 PHINode *PN = cast<PHINode>(I);
126 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
127 ++UI)
Chris Lattner8e75ee22005-12-03 18:25:58 +0000128 if (cast<Instruction>(*UI)->getParent() != Succ)
129 return false;
Chris Lattner1aad9212005-08-03 00:59:12 +0000130 }
131
Chris Lattner8e75ee22005-12-03 18:25:58 +0000132 // Scan the predecessor sets of BB and Succ, making sure there are no common
133 // predecessors. Common predecessors would cause us to build a phi node with
134 // differing incoming values, which is not legal.
Chris Lattnerc9951232007-04-02 01:44:59 +0000135 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner8e75ee22005-12-03 18:25:58 +0000136 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
137 if (BBPreds.count(*PI))
138 return false;
139
140 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000141}
142
Chris Lattner7e663482005-08-03 00:11:16 +0000143/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
144/// branch to Succ, and contains no instructions other than PHI nodes and the
145/// branch. If possible, eliminate BB.
146static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
147 BasicBlock *Succ) {
148 // If our successor has PHI nodes, then we need to update them to include
149 // entries for BB's predecessors, not for BB itself. Be careful though,
150 // if this transformation fails (returns true) then we cannot do this
151 // transformation!
152 //
Chris Lattner3b3efc72005-08-03 00:29:26 +0000153 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner7e663482005-08-03 00:11:16 +0000154
Bill Wendling0d45a092006-11-26 10:17:54 +0000155 DOUT << "Killing Trivial BB: \n" << *BB;
Chris Lattner7e663482005-08-03 00:11:16 +0000156
Chris Lattner3b3efc72005-08-03 00:29:26 +0000157 if (isa<PHINode>(Succ->begin())) {
158 // If there is more than one pred of succ, and there are PHI nodes in
159 // the successor, then we need to add incoming edges for the PHI nodes
160 //
Chris Lattner82442432008-02-18 07:42:56 +0000161 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner3b3efc72005-08-03 00:29:26 +0000162
163 // Loop over all of the PHI nodes in the successor of BB.
164 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
165 PHINode *PN = cast<PHINode>(I);
166 Value *OldVal = PN->removeIncomingValue(BB, false);
167 assert(OldVal && "No entry in PHI for Pred BB!");
168
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000169 // If this incoming value is one of the PHI nodes in BB, the new entries
170 // in the PHI node are the entries from the old PHI.
Chris Lattner3b3efc72005-08-03 00:29:26 +0000171 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
172 PHINode *OldValPN = cast<PHINode>(OldVal);
173 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
174 PN->addIncoming(OldValPN->getIncomingValue(i),
175 OldValPN->getIncomingBlock(i));
176 } else {
Chris Lattner82442432008-02-18 07:42:56 +0000177 // Add an incoming value for each of the new incoming values.
178 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
179 PN->addIncoming(OldVal, BBPreds[i]);
Chris Lattner3b3efc72005-08-03 00:29:26 +0000180 }
181 }
182 }
183
Chris Lattner7e663482005-08-03 00:11:16 +0000184 if (isa<PHINode>(&BB->front())) {
Chris Lattner82442432008-02-18 07:42:56 +0000185 SmallVector<BasicBlock*, 16>
Chris Lattner7e663482005-08-03 00:11:16 +0000186 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
187
188 // Move all PHI nodes in BB to Succ if they are alive, otherwise
189 // delete them.
190 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000191 if (PN->use_empty()) {
192 // Just remove the dead phi. This happens if Succ's PHIs were the only
193 // users of the PHI nodes.
194 PN->eraseFromParent();
Chris Lattner7e663482005-08-03 00:11:16 +0000195 } else {
196 // The instruction is alive, so this means that Succ must have
197 // *ONLY* had BB as a predecessor, and the PHI node is still valid
198 // now. Simply move it into Succ, because we know that BB
199 // strictly dominated Succ.
Chris Lattnerd423b8b2005-08-03 00:23:42 +0000200 Succ->getInstList().splice(Succ->begin(),
201 BB->getInstList(), BB->begin());
Chris Lattner7e663482005-08-03 00:11:16 +0000202
203 // We need to add new entries for the PHI node to account for
204 // predecessors of Succ that the PHI node does not take into
205 // account. At this point, since we know that BB dominated succ,
206 // this means that we should any newly added incoming edges should
207 // use the PHI node as the value for these edges, because they are
208 // loop back edges.
209 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
210 if (OldSuccPreds[i] != BB)
211 PN->addIncoming(PN, OldSuccPreds[i]);
212 }
213 }
214
215 // Everything that jumped to BB now goes to Succ.
Chris Lattner7e663482005-08-03 00:11:16 +0000216 BB->replaceAllUsesWith(Succ);
Chris Lattner86cc4232007-02-11 01:37:51 +0000217 if (!Succ->hasName()) Succ->takeName(BB);
Chris Lattner7e663482005-08-03 00:11:16 +0000218 BB->eraseFromParent(); // Delete the old basic block.
Chris Lattner7e663482005-08-03 00:11:16 +0000219 return true;
220}
221
Chris Lattner723c66d2004-02-11 03:36:04 +0000222/// GetIfCondition - Given a basic block (BB) with two predecessors (and
223/// presumably PHI nodes in it), check to see if the merge at this block is due
224/// to an "if condition". If so, return the boolean condition that determines
225/// which entry into BB will be taken. Also, return by references the block
226/// that will be entered from if the condition is true, and the block that will
227/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000228///
Chris Lattner723c66d2004-02-11 03:36:04 +0000229///
230static Value *GetIfCondition(BasicBlock *BB,
231 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
232 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
233 "Function can only handle blocks with 2 predecessors!");
234 BasicBlock *Pred1 = *pred_begin(BB);
235 BasicBlock *Pred2 = *++pred_begin(BB);
236
237 // We can only handle branches. Other control flow will be lowered to
238 // branches if possible anyway.
239 if (!isa<BranchInst>(Pred1->getTerminator()) ||
240 !isa<BranchInst>(Pred2->getTerminator()))
241 return 0;
242 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
243 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
244
245 // Eliminate code duplication by ensuring that Pred1Br is conditional if
246 // either are.
247 if (Pred2Br->isConditional()) {
248 // If both branches are conditional, we don't have an "if statement". In
249 // reality, we could transform this case, but since the condition will be
250 // required anyway, we stand no chance of eliminating it, so the xform is
251 // probably not profitable.
252 if (Pred1Br->isConditional())
253 return 0;
254
255 std::swap(Pred1, Pred2);
256 std::swap(Pred1Br, Pred2Br);
257 }
258
259 if (Pred1Br->isConditional()) {
260 // If we found a conditional branch predecessor, make sure that it branches
261 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
262 if (Pred1Br->getSuccessor(0) == BB &&
263 Pred1Br->getSuccessor(1) == Pred2) {
264 IfTrue = Pred1;
265 IfFalse = Pred2;
266 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
267 Pred1Br->getSuccessor(1) == BB) {
268 IfTrue = Pred2;
269 IfFalse = Pred1;
270 } else {
271 // We know that one arm of the conditional goes to BB, so the other must
272 // go somewhere unrelated, and this must not be an "if statement".
273 return 0;
274 }
275
276 // The only thing we have to watch out for here is to make sure that Pred2
277 // doesn't have incoming edges from other blocks. If it does, the condition
278 // doesn't dominate BB.
279 if (++pred_begin(Pred2) != pred_end(Pred2))
280 return 0;
281
282 return Pred1Br->getCondition();
283 }
284
285 // Ok, if we got here, both predecessors end with an unconditional branch to
286 // BB. Don't panic! If both blocks only have a single (identical)
287 // predecessor, and THAT is a conditional branch, then we're all ok!
288 if (pred_begin(Pred1) == pred_end(Pred1) ||
289 ++pred_begin(Pred1) != pred_end(Pred1) ||
290 pred_begin(Pred2) == pred_end(Pred2) ||
291 ++pred_begin(Pred2) != pred_end(Pred2) ||
292 *pred_begin(Pred1) != *pred_begin(Pred2))
293 return 0;
294
295 // Otherwise, if this is a conditional branch, then we can use it!
296 BasicBlock *CommonPred = *pred_begin(Pred1);
297 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
298 assert(BI->isConditional() && "Two successors but not conditional?");
299 if (BI->getSuccessor(0) == Pred1) {
300 IfTrue = Pred1;
301 IfFalse = Pred2;
302 } else {
303 IfTrue = Pred2;
304 IfFalse = Pred1;
305 }
306 return BI->getCondition();
307 }
308 return 0;
309}
310
311
312// If we have a merge point of an "if condition" as accepted above, return true
313// if the specified value dominates the block. We don't handle the true
314// generality of domination here, just a special case which works well enough
315// for us.
Chris Lattner9c078662004-10-14 05:13:36 +0000316//
317// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
318// see if V (which must be an instruction) is cheap to compute and is
319// non-trapping. If both are true, the instruction is inserted into the set and
320// true is returned.
321static bool DominatesMergePoint(Value *V, BasicBlock *BB,
322 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000323 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb74b1812006-10-20 00:42:07 +0000324 if (!I) {
325 // Non-instructions all dominate instructions, but not all constantexprs
326 // can be executed unconditionally.
327 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
328 if (C->canTrap())
329 return false;
330 return true;
331 }
Chris Lattner570751c2004-04-09 22:50:22 +0000332 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000333
Chris Lattnerda895d62005-02-27 06:18:25 +0000334 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000335 // the bottom of this block.
336 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000337
Chris Lattner570751c2004-04-09 22:50:22 +0000338 // If this instruction is defined in a block that contains an unconditional
339 // branch to BB, then it must be in the 'conditional' part of the "if
340 // statement".
341 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
342 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner9c078662004-10-14 05:13:36 +0000343 if (!AggressiveInsts) return false;
Chris Lattner570751c2004-04-09 22:50:22 +0000344 // Okay, it looks like the instruction IS in the "condition". Check to
345 // see if its a cheap instruction to unconditionally compute, and if it
346 // only uses stuff defined outside of the condition. If so, hoist it out.
347 switch (I->getOpcode()) {
348 default: return false; // Cannot hoist this out safely.
349 case Instruction::Load:
350 // We can hoist loads that are non-volatile and obviously cannot trap.
351 if (cast<LoadInst>(I)->isVolatile())
352 return false;
353 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spencer460f16c2004-07-18 00:32:14 +0000354 !isa<Constant>(I->getOperand(0)))
Chris Lattner570751c2004-04-09 22:50:22 +0000355 return false;
356
357 // Finally, we have to check to make sure there are no instructions
358 // before the load in its basic block, as we are going to hoist the loop
359 // out to its predecessor.
360 if (PBB->begin() != BasicBlock::iterator(I))
361 return false;
362 break;
363 case Instruction::Add:
364 case Instruction::Sub:
365 case Instruction::And:
366 case Instruction::Or:
367 case Instruction::Xor:
368 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +0000369 case Instruction::LShr:
370 case Instruction::AShr:
Reid Spencere4d87aa2006-12-23 06:05:41 +0000371 case Instruction::ICmp:
372 case Instruction::FCmp:
Chris Lattner3d73bce2008-01-03 07:25:26 +0000373 if (I->getOperand(0)->getType()->isFPOrFPVector())
374 return false; // FP arithmetic might trap.
Chris Lattner570751c2004-04-09 22:50:22 +0000375 break; // These are all cheap and non-trapping instructions.
376 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000377
Chris Lattner570751c2004-04-09 22:50:22 +0000378 // Okay, we can only really hoist these out if their operands are not
379 // defined in the conditional region.
380 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner9c078662004-10-14 05:13:36 +0000381 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner570751c2004-04-09 22:50:22 +0000382 return false;
Chris Lattner9c078662004-10-14 05:13:36 +0000383 // Okay, it's safe to do this! Remember this instruction.
384 AggressiveInsts->insert(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000385 }
386
Chris Lattner723c66d2004-02-11 03:36:04 +0000387 return true;
388}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000389
Reid Spencere4d87aa2006-12-23 06:05:41 +0000390// GatherConstantSetEQs - Given a potentially 'or'd together collection of
391// icmp_eq instructions that compare a value against a constant, return the
392// value being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000393static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000394 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000395 if (Inst->getOpcode() == Instruction::ICmp &&
396 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000397 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000398 Values.push_back(C);
399 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000400 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000401 Values.push_back(C);
402 return Inst->getOperand(1);
403 }
404 } else if (Inst->getOpcode() == Instruction::Or) {
405 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
406 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
407 if (LHS == RHS)
408 return LHS;
409 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000410 }
Chris Lattner0d560082004-02-24 05:38:11 +0000411 return 0;
412}
413
414// GatherConstantSetNEs - Given a potentially 'and'd together collection of
415// setne instructions that compare a value against a constant, return the value
416// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000417static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000418 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000419 if (Inst->getOpcode() == Instruction::ICmp &&
420 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000421 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000422 Values.push_back(C);
423 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000424 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000425 Values.push_back(C);
426 return Inst->getOperand(1);
427 }
Chris Lattner0d560082004-02-24 05:38:11 +0000428 } else if (Inst->getOpcode() == Instruction::And) {
429 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
430 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
431 if (LHS == RHS)
432 return LHS;
433 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000434 }
Chris Lattner0d560082004-02-24 05:38:11 +0000435 return 0;
436}
437
438
439
440/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
441/// bunch of comparisons of one value against constants, return the value and
442/// the constants being compared.
443static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000444 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000445 if (Cond->getOpcode() == Instruction::Or) {
446 CompVal = GatherConstantSetEQs(Cond, Values);
447
448 // Return true to indicate that the condition is true if the CompVal is
449 // equal to one of the constants.
450 return true;
451 } else if (Cond->getOpcode() == Instruction::And) {
452 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanfd939082005-04-21 23:48:37 +0000453
Chris Lattner0d560082004-02-24 05:38:11 +0000454 // Return false to indicate that the condition is false if the CompVal is
455 // equal to one of the constants.
456 return false;
457 }
458 return false;
459}
460
461/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
462/// has no side effects, nuke it. If it uses any instructions that become dead
463/// because the instruction is now gone, nuke them too.
464static void ErasePossiblyDeadInstructionTree(Instruction *I) {
Chris Lattner8cfe6332006-08-03 21:40:24 +0000465 if (!isInstructionTriviallyDead(I)) return;
466
Chris Lattner82442432008-02-18 07:42:56 +0000467 SmallVector<Instruction*, 16> InstrsToInspect;
Chris Lattner8cfe6332006-08-03 21:40:24 +0000468 InstrsToInspect.push_back(I);
469
470 while (!InstrsToInspect.empty()) {
471 I = InstrsToInspect.back();
472 InstrsToInspect.pop_back();
473
474 if (!isInstructionTriviallyDead(I)) continue;
475
476 // If I is in the work list multiple times, remove previous instances.
477 for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
478 if (InstrsToInspect[i] == I) {
479 InstrsToInspect.erase(InstrsToInspect.begin()+i);
480 --i, --e;
481 }
482
483 // Add operands of dead instruction to worklist.
484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
485 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
486 InstrsToInspect.push_back(OpI);
487
488 // Remove dead instruction.
489 I->eraseFromParent();
Chris Lattner0d560082004-02-24 05:38:11 +0000490 }
491}
492
Chris Lattner542f1492004-02-28 21:28:10 +0000493// isValueEqualityComparison - Return true if the specified terminator checks to
494// see if a value is equal to constant integer value.
495static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000496 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
497 // Do not permit merging of large switch instructions into their
498 // predecessors unless there is only one predecessor.
499 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
500 pred_end(SI->getParent())) > 128)
501 return 0;
502
Chris Lattner542f1492004-02-28 21:28:10 +0000503 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000504 }
Chris Lattner542f1492004-02-28 21:28:10 +0000505 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
506 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencere4d87aa2006-12-23 06:05:41 +0000507 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
508 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
509 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
510 isa<ConstantInt>(ICI->getOperand(1)))
511 return ICI->getOperand(0);
Chris Lattner542f1492004-02-28 21:28:10 +0000512 return 0;
513}
514
515// Given a value comparison instruction, decode all of the 'cases' that it
516// represents and return the 'default' block.
517static BasicBlock *
Misha Brukmanfd939082005-04-21 23:48:37 +0000518GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000519 std::vector<std::pair<ConstantInt*,
520 BasicBlock*> > &Cases) {
521 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
522 Cases.reserve(SI->getNumCases());
523 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000524 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000525 return SI->getDefaultDest();
526 }
527
528 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000529 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
530 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
531 BI->getSuccessor(ICI->getPredicate() ==
532 ICmpInst::ICMP_NE)));
533 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattner542f1492004-02-28 21:28:10 +0000534}
535
536
Dan Gohmanfa73ea22007-05-24 14:36:04 +0000537// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
Chris Lattner623369a2005-02-24 06:17:52 +0000538// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000539static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000540 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
541 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
542 if (Cases[i].second == BB) {
543 Cases.erase(Cases.begin()+i);
544 --i; --e;
545 }
546}
547
548// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
549// well.
550static bool
551ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
552 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
553 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
554
555 // Make V1 be smaller than V2.
556 if (V1->size() > V2->size())
557 std::swap(V1, V2);
558
559 if (V1->size() == 0) return false;
560 if (V1->size() == 1) {
561 // Just scan V2.
562 ConstantInt *TheVal = (*V1)[0].first;
563 for (unsigned i = 0, e = V2->size(); i != e; ++i)
564 if (TheVal == (*V2)[i].first)
565 return true;
566 }
567
568 // Otherwise, just sort both lists and compare element by element.
569 std::sort(V1->begin(), V1->end());
570 std::sort(V2->begin(), V2->end());
571 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
572 while (i1 != e1 && i2 != e2) {
573 if ((*V1)[i1].first == (*V2)[i2].first)
574 return true;
575 if ((*V1)[i1].first < (*V2)[i2].first)
576 ++i1;
577 else
578 ++i2;
579 }
580 return false;
581}
582
583// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
584// terminator instruction and its block is known to only have a single
585// predecessor block, check to see if that predecessor is also a value
586// comparison with the same value, and if that comparison determines the outcome
587// of this comparison. If so, simplify TI. This does a very limited form of
588// jump threading.
589static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
590 BasicBlock *Pred) {
591 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
592 if (!PredVal) return false; // Not a value comparison in predecessor.
593
594 Value *ThisVal = isValueEqualityComparison(TI);
595 assert(ThisVal && "This isn't a value comparison!!");
596 if (ThisVal != PredVal) return false; // Different predicates.
597
598 // Find out information about when control will move from Pred to TI's block.
599 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
600 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
601 PredCases);
602 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000603
Chris Lattner623369a2005-02-24 06:17:52 +0000604 // Find information about how control leaves this block.
605 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
606 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
607 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
608
609 // If TI's block is the default block from Pred's comparison, potentially
610 // simplify TI based on this knowledge.
611 if (PredDef == TI->getParent()) {
612 // If we are here, we know that the value is none of those cases listed in
613 // PredCases. If there are any cases in ThisCases that are in PredCases, we
614 // can simplify TI.
615 if (ValuesOverlap(PredCases, ThisCases)) {
616 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
617 // Okay, one of the successors of this condbr is dead. Convert it to a
618 // uncond br.
619 assert(ThisCases.size() == 1 && "Branch can only have one case!");
620 Value *Cond = BTI->getCondition();
621 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000622 Instruction *NI = BranchInst::Create(ThisDef, TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000623
624 // Remove PHI node entries for the dead edge.
625 ThisCases[0].second->removePredecessor(TI->getParent());
626
Bill Wendling0d45a092006-11-26 10:17:54 +0000627 DOUT << "Threading pred instr: " << *Pred->getTerminator()
628 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000629
630 TI->eraseFromParent(); // Nuke the old one.
631 // If condition is now dead, nuke it.
632 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
633 ErasePossiblyDeadInstructionTree(CondI);
634 return true;
635
636 } else {
637 SwitchInst *SI = cast<SwitchInst>(TI);
638 // Okay, TI has cases that are statically dead, prune them away.
Chris Lattnerc9951232007-04-02 01:44:59 +0000639 SmallPtrSet<Constant*, 16> DeadCases;
Chris Lattner623369a2005-02-24 06:17:52 +0000640 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
641 DeadCases.insert(PredCases[i].first);
642
Bill Wendling0d45a092006-11-26 10:17:54 +0000643 DOUT << "Threading pred instr: " << *Pred->getTerminator()
644 << "Through successor TI: " << *TI;
Chris Lattner623369a2005-02-24 06:17:52 +0000645
646 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
647 if (DeadCases.count(SI->getCaseValue(i))) {
648 SI->getSuccessor(i)->removePredecessor(TI->getParent());
649 SI->removeCase(i);
650 }
651
Bill Wendling0d45a092006-11-26 10:17:54 +0000652 DOUT << "Leaving: " << *TI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000653 return true;
654 }
655 }
656
657 } else {
658 // Otherwise, TI's block must correspond to some matched value. Find out
659 // which value (or set of values) this is.
660 ConstantInt *TIV = 0;
661 BasicBlock *TIBB = TI->getParent();
662 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000663 if (PredCases[i].second == TIBB) {
Chris Lattner623369a2005-02-24 06:17:52 +0000664 if (TIV == 0)
665 TIV = PredCases[i].first;
666 else
667 return false; // Cannot handle multiple values coming to this block.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000668 }
Chris Lattner623369a2005-02-24 06:17:52 +0000669 assert(TIV && "No edge from pred to succ?");
670
671 // Okay, we found the one constant that our value can be if we get into TI's
672 // BB. Find out which successor will unconditionally be branched to.
673 BasicBlock *TheRealDest = 0;
674 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
675 if (ThisCases[i].first == TIV) {
676 TheRealDest = ThisCases[i].second;
677 break;
678 }
679
680 // If not handled by any explicit cases, it is handled by the default case.
681 if (TheRealDest == 0) TheRealDest = ThisDef;
682
683 // Remove PHI node entries for dead edges.
684 BasicBlock *CheckEdge = TheRealDest;
685 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
686 if (*SI != CheckEdge)
687 (*SI)->removePredecessor(TIBB);
688 else
689 CheckEdge = 0;
690
691 // Insert the new branch.
Gabor Greif051a9502008-04-06 20:25:17 +0000692 Instruction *NI = BranchInst::Create(TheRealDest, TI);
Chris Lattner623369a2005-02-24 06:17:52 +0000693
Bill Wendling0d45a092006-11-26 10:17:54 +0000694 DOUT << "Threading pred instr: " << *Pred->getTerminator()
695 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
Chris Lattner623369a2005-02-24 06:17:52 +0000696 Instruction *Cond = 0;
697 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
698 Cond = dyn_cast<Instruction>(BI->getCondition());
699 TI->eraseFromParent(); // Nuke the old one.
700
701 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
702 return true;
703 }
704 return false;
705}
706
Chris Lattner542f1492004-02-28 21:28:10 +0000707// FoldValueComparisonIntoPredecessors - The specified terminator is a value
708// equality comparison instruction (either a switch or a branch on "X == c").
709// See if any of the predecessors of the terminator block are value comparisons
710// on the same value. If so, and if safe to do so, fold them together.
711static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
712 BasicBlock *BB = TI->getParent();
713 Value *CV = isValueEqualityComparison(TI); // CondVal
714 assert(CV && "Not a comparison?");
715 bool Changed = false;
716
Chris Lattner82442432008-02-18 07:42:56 +0000717 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner542f1492004-02-28 21:28:10 +0000718 while (!Preds.empty()) {
719 BasicBlock *Pred = Preds.back();
720 Preds.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000721
Chris Lattner542f1492004-02-28 21:28:10 +0000722 // See if the predecessor is a comparison with the same value.
723 TerminatorInst *PTI = Pred->getTerminator();
724 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
725
726 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
727 // Figure out which 'cases' to copy from SI to PSI.
728 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
729 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
730
731 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
732 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
733
734 // Based on whether the default edge from PTI goes to BB or not, fill in
735 // PredCases and PredDefault with the new switch cases we would like to
736 // build.
Chris Lattner82442432008-02-18 07:42:56 +0000737 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattner542f1492004-02-28 21:28:10 +0000738
739 if (PredDefault == BB) {
740 // If this is the default destination from PTI, only the edges in TI
741 // that don't occur in PTI, or that branch to BB will be activated.
742 std::set<ConstantInt*> PTIHandled;
743 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
744 if (PredCases[i].second != BB)
745 PTIHandled.insert(PredCases[i].first);
746 else {
747 // The default destination is BB, we don't need explicit targets.
748 std::swap(PredCases[i], PredCases.back());
749 PredCases.pop_back();
750 --i; --e;
751 }
752
753 // Reconstruct the new switch statement we will be building.
754 if (PredDefault != BBDefault) {
755 PredDefault->removePredecessor(Pred);
756 PredDefault = BBDefault;
757 NewSuccessors.push_back(BBDefault);
758 }
759 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
760 if (!PTIHandled.count(BBCases[i].first) &&
761 BBCases[i].second != BBDefault) {
762 PredCases.push_back(BBCases[i]);
763 NewSuccessors.push_back(BBCases[i].second);
764 }
765
766 } else {
767 // If this is not the default destination from PSI, only the edges
768 // in SI that occur in PSI with a destination of BB will be
769 // activated.
770 std::set<ConstantInt*> PTIHandled;
771 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
772 if (PredCases[i].second == BB) {
773 PTIHandled.insert(PredCases[i].first);
774 std::swap(PredCases[i], PredCases.back());
775 PredCases.pop_back();
776 --i; --e;
777 }
778
779 // Okay, now we know which constants were sent to BB from the
780 // predecessor. Figure out where they will all go now.
781 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
782 if (PTIHandled.count(BBCases[i].first)) {
783 // If this is one we are capable of getting...
784 PredCases.push_back(BBCases[i]);
785 NewSuccessors.push_back(BBCases[i].second);
786 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
787 }
788
789 // If there are any constants vectored to BB that TI doesn't handle,
790 // they must go to the default destination of TI.
791 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
792 E = PTIHandled.end(); I != E; ++I) {
793 PredCases.push_back(std::make_pair(*I, BBDefault));
794 NewSuccessors.push_back(BBDefault);
795 }
796 }
797
798 // Okay, at this point, we know which new successor Pred will get. Make
799 // sure we update the number of entries in the PHI nodes for these
800 // successors.
801 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
802 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
803
804 // Now that the successors are updated, create the new Switch instruction.
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000805 SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
806 PredCases.size(), PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000807 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
808 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000809
810 Instruction *DeadCond = 0;
811 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
812 // If PTI is a branch, remember the condition.
813 DeadCond = dyn_cast<Instruction>(BI->getCondition());
Chris Lattner542f1492004-02-28 21:28:10 +0000814 Pred->getInstList().erase(PTI);
815
Chris Lattner13b2f762005-01-01 16:02:12 +0000816 // If the condition is dead now, remove the instruction tree.
817 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
818
Chris Lattner542f1492004-02-28 21:28:10 +0000819 // Okay, last check. If BB is still a successor of PSI, then we must
820 // have an infinite loop case. If so, add an infinitely looping block
821 // to handle the case to preserve the behavior of the code.
822 BasicBlock *InfLoopBlock = 0;
823 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
824 if (NewSI->getSuccessor(i) == BB) {
825 if (InfLoopBlock == 0) {
826 // Insert it at the end of the loop, because it's either code,
827 // or it won't matter if it's hot. :)
Gabor Greif051a9502008-04-06 20:25:17 +0000828 InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
829 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattner542f1492004-02-28 21:28:10 +0000830 }
831 NewSI->setSuccessor(i, InfLoopBlock);
832 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000833
Chris Lattner542f1492004-02-28 21:28:10 +0000834 Changed = true;
835 }
836 }
837 return Changed;
838}
839
Chris Lattner6306d072005-08-03 17:59:45 +0000840/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner37dc9382004-11-30 00:29:14 +0000841/// BB2, hoist any common code in the two blocks up into the branch block. The
842/// caller of this function guarantees that BI's block dominates BB1 and BB2.
843static bool HoistThenElseCodeToIf(BranchInst *BI) {
844 // This does very trivial matching, with limited scanning, to find identical
845 // instructions in the two blocks. In particular, we don't want to get into
846 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
847 // such, we currently just scan for obviously identical instructions in an
848 // identical order.
849 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
850 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
851
852 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
Reid Spencere4d87aa2006-12-23 06:05:41 +0000853 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
854 isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
Chris Lattner37dc9382004-11-30 00:29:14 +0000855 return false;
856
857 // If we get here, we can hoist at least one instruction.
858 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000859
860 do {
861 // If we are hoisting the terminator instruction, don't move one (making a
862 // broken BB), instead clone it, and remove BI.
863 if (isa<TerminatorInst>(I1))
864 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000865
Chris Lattner37dc9382004-11-30 00:29:14 +0000866 // For a normal instruction, we just move one to right before the branch,
867 // then replace all uses of the other with the first. Finally, we remove
868 // the now redundant second instruction.
869 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
870 if (!I2->use_empty())
871 I2->replaceAllUsesWith(I1);
872 BB2->getInstList().erase(I2);
Misha Brukmanfd939082005-04-21 23:48:37 +0000873
Chris Lattner37dc9382004-11-30 00:29:14 +0000874 I1 = BB1->begin();
875 I2 = BB2->begin();
Chris Lattner37dc9382004-11-30 00:29:14 +0000876 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
877
878 return true;
879
880HoistTerminator:
881 // Okay, it is safe to hoist the terminator.
882 Instruction *NT = I1->clone();
883 BIParent->getInstList().insert(BI, NT);
884 if (NT->getType() != Type::VoidTy) {
885 I1->replaceAllUsesWith(NT);
886 I2->replaceAllUsesWith(NT);
Chris Lattner86cc4232007-02-11 01:37:51 +0000887 NT->takeName(I1);
Chris Lattner37dc9382004-11-30 00:29:14 +0000888 }
889
890 // Hoisting one of the terminators from our successor is a great thing.
891 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
892 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
893 // nodes, so we insert select instruction to compute the final result.
894 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
895 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
896 PHINode *PN;
897 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000898 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000899 Value *BB1V = PN->getIncomingValueForBlock(BB1);
900 Value *BB2V = PN->getIncomingValueForBlock(BB2);
901 if (BB1V != BB2V) {
902 // These values do not agree. Insert a select instruction before NT
903 // that determines the right value.
904 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
905 if (SI == 0)
Gabor Greif051a9502008-04-06 20:25:17 +0000906 SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
907 BB1V->getName()+"."+BB2V->getName(), NT);
Chris Lattner37dc9382004-11-30 00:29:14 +0000908 // Make the PHI node use the select for all incoming values for BB1/BB2
909 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
910 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
911 PN->setIncomingValue(i, SI);
912 }
913 }
914 }
915
916 // Update any PHI nodes in our new successors.
917 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
918 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000919
Chris Lattner37dc9382004-11-30 00:29:14 +0000920 BI->eraseFromParent();
921 return true;
922}
923
Chris Lattner2e42e362005-09-20 00:43:16 +0000924/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
925/// across this block.
926static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
927 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattnere9487f02005-09-20 01:48:40 +0000928 unsigned Size = 0;
929
Chris Lattner2e42e362005-09-20 00:43:16 +0000930 // If this basic block contains anything other than a PHI (which controls the
931 // branch) and branch itself, bail out. FIXME: improve this in the future.
Chris Lattnere9487f02005-09-20 01:48:40 +0000932 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
933 if (Size > 10) return false; // Don't clone large BB's.
Chris Lattner2e42e362005-09-20 00:43:16 +0000934
Chris Lattnere9487f02005-09-20 01:48:40 +0000935 // We can only support instructions that are do not define values that are
936 // live outside of the current basic block.
937 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
938 UI != E; ++UI) {
939 Instruction *U = cast<Instruction>(*UI);
940 if (U->getParent() != BB || isa<PHINode>(U)) return false;
941 }
Chris Lattner2e42e362005-09-20 00:43:16 +0000942
943 // Looks ok, continue checking.
944 }
Chris Lattnere9487f02005-09-20 01:48:40 +0000945
Chris Lattner2e42e362005-09-20 00:43:16 +0000946 return true;
947}
948
Chris Lattnereaba3a12005-09-19 23:49:37 +0000949/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
950/// that is defined in the same block as the branch and if any PHI entries are
951/// constants, thread edges corresponding to that entry to be branches to their
952/// ultimate destination.
953static bool FoldCondBranchOnPHI(BranchInst *BI) {
954 BasicBlock *BB = BI->getParent();
955 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner9c88d982005-09-19 23:57:04 +0000956 // NOTE: we currently cannot transform this case if the PHI node is used
957 // outside of the block.
Chris Lattner2e42e362005-09-20 00:43:16 +0000958 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
959 return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +0000960
961 // Degenerate case of a single entry PHI.
962 if (PN->getNumIncomingValues() == 1) {
963 if (PN->getIncomingValue(0) != PN)
964 PN->replaceAllUsesWith(PN->getIncomingValue(0));
965 else
966 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
967 PN->eraseFromParent();
968 return true;
969 }
970
971 // Now we know that this block has multiple preds and two succs.
Chris Lattner2e42e362005-09-20 00:43:16 +0000972 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattnereaba3a12005-09-19 23:49:37 +0000973
974 // Okay, this is a simple enough basic block. See if any phi values are
975 // constants.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000976 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
977 ConstantInt *CB;
978 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
Reid Spencer4fe16d62007-01-11 18:21:29 +0000979 CB->getType() == Type::Int1Ty) {
Chris Lattnereaba3a12005-09-19 23:49:37 +0000980 // Okay, we now know that all edges from PredBB should be revectored to
981 // branch to RealDest.
982 BasicBlock *PredBB = PN->getIncomingBlock(i);
Reid Spencer579dca12007-01-12 04:24:46 +0000983 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Chris Lattnereaba3a12005-09-19 23:49:37 +0000984
Chris Lattnere9487f02005-09-20 01:48:40 +0000985 if (RealDest == BB) continue; // Skip self loops.
Chris Lattnereaba3a12005-09-19 23:49:37 +0000986
Chris Lattnere9487f02005-09-20 01:48:40 +0000987 // The dest block might have PHI nodes, other predecessors and other
988 // difficult cases. Instead of being smart about this, just insert a new
989 // block that jumps to the destination block, effectively splitting
990 // the edge we are about to create.
Gabor Greif051a9502008-04-06 20:25:17 +0000991 BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
992 RealDest->getParent(), RealDest);
993 BranchInst::Create(RealDest, EdgeBB);
Chris Lattnere9487f02005-09-20 01:48:40 +0000994 PHINode *PN;
995 for (BasicBlock::iterator BBI = RealDest->begin();
996 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
997 Value *V = PN->getIncomingValueForBlock(BB);
998 PN->addIncoming(V, EdgeBB);
999 }
1000
1001 // BB may have instructions that are being threaded over. Clone these
1002 // instructions into EdgeBB. We know that there will be no uses of the
1003 // cloned instructions outside of EdgeBB.
1004 BasicBlock::iterator InsertPt = EdgeBB->begin();
1005 std::map<Value*, Value*> TranslateMap; // Track translated values.
1006 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1007 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1008 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1009 } else {
1010 // Clone the instruction.
1011 Instruction *N = BBI->clone();
1012 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1013
1014 // Update operands due to translation.
1015 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1016 std::map<Value*, Value*>::iterator PI =
1017 TranslateMap.find(N->getOperand(i));
1018 if (PI != TranslateMap.end())
1019 N->setOperand(i, PI->second);
1020 }
1021
1022 // Check for trivial simplification.
1023 if (Constant *C = ConstantFoldInstruction(N)) {
Chris Lattnere9487f02005-09-20 01:48:40 +00001024 TranslateMap[BBI] = C;
1025 delete N; // Constant folded away, don't need actual inst
1026 } else {
1027 // Insert the new instruction into its new home.
1028 EdgeBB->getInstList().insert(InsertPt, N);
1029 if (!BBI->use_empty())
1030 TranslateMap[BBI] = N;
1031 }
1032 }
1033 }
1034
Chris Lattnereaba3a12005-09-19 23:49:37 +00001035 // Loop over all of the edges from PredBB to BB, changing them to branch
Chris Lattnere9487f02005-09-20 01:48:40 +00001036 // to EdgeBB instead.
Chris Lattnereaba3a12005-09-19 23:49:37 +00001037 TerminatorInst *PredBBTI = PredBB->getTerminator();
1038 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1039 if (PredBBTI->getSuccessor(i) == BB) {
1040 BB->removePredecessor(PredBB);
Chris Lattnere9487f02005-09-20 01:48:40 +00001041 PredBBTI->setSuccessor(i, EdgeBB);
Chris Lattnereaba3a12005-09-19 23:49:37 +00001042 }
1043
Chris Lattnereaba3a12005-09-19 23:49:37 +00001044 // Recurse, simplifying any other constants.
1045 return FoldCondBranchOnPHI(BI) | true;
1046 }
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001047 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001048
1049 return false;
1050}
1051
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001052/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1053/// PHI node, see if we can eliminate it.
1054static bool FoldTwoEntryPHINode(PHINode *PN) {
1055 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1056 // statement", which has a very simple dominance structure. Basically, we
1057 // are trying to find the condition that is being branched on, which
1058 // subsequently causes this merge to happen. We really want control
1059 // dependence information for this check, but simplifycfg can't keep it up
1060 // to date, and this catches most of the cases we care about anyway.
1061 //
1062 BasicBlock *BB = PN->getParent();
1063 BasicBlock *IfTrue, *IfFalse;
1064 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1065 if (!IfCond) return false;
1066
Chris Lattner822a8792006-11-18 19:19:36 +00001067 // Okay, we found that we can merge this two-entry phi node into a select.
1068 // Doing so would require us to fold *all* two entry phi nodes in this block.
1069 // At some point this becomes non-profitable (particularly if the target
1070 // doesn't support cmov's). Only do this transformation if there are two or
1071 // fewer PHI nodes in this block.
1072 unsigned NumPhis = 0;
1073 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1074 if (NumPhis > 2)
1075 return false;
1076
Bill Wendling0d45a092006-11-26 10:17:54 +00001077 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1078 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001079
1080 // Loop over the PHI's seeing if we can promote them all to select
1081 // instructions. While we are at it, keep track of the instructions
1082 // that need to be moved to the dominating block.
1083 std::set<Instruction*> AggressiveInsts;
1084
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001085 BasicBlock::iterator AfterPHIIt = BB->begin();
1086 while (isa<PHINode>(AfterPHIIt)) {
1087 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1088 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1089 if (PN->getIncomingValue(0) != PN)
1090 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1091 else
1092 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1093 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1094 &AggressiveInsts) ||
1095 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1096 &AggressiveInsts)) {
Chris Lattner055dc102005-09-23 07:23:18 +00001097 return false;
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001098 }
1099 }
1100
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001101 // If we all PHI nodes are promotable, check to make sure that all
1102 // instructions in the predecessor blocks can be promoted as well. If
1103 // not, we won't be able to get rid of the control flow, so it's not
1104 // worth promoting to select instructions.
1105 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1106 PN = cast<PHINode>(BB->begin());
1107 BasicBlock *Pred = PN->getIncomingBlock(0);
1108 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1109 IfBlock1 = Pred;
1110 DomBlock = *pred_begin(Pred);
1111 for (BasicBlock::iterator I = Pred->begin();
1112 !isa<TerminatorInst>(I); ++I)
1113 if (!AggressiveInsts.count(I)) {
1114 // This is not an aggressive instruction that we can promote.
1115 // Because of this, we won't be able to get rid of the control
1116 // flow, so the xform is not worth it.
1117 return false;
1118 }
1119 }
1120
1121 Pred = PN->getIncomingBlock(1);
1122 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1123 IfBlock2 = Pred;
1124 DomBlock = *pred_begin(Pred);
1125 for (BasicBlock::iterator I = Pred->begin();
1126 !isa<TerminatorInst>(I); ++I)
1127 if (!AggressiveInsts.count(I)) {
1128 // This is not an aggressive instruction that we can promote.
1129 // Because of this, we won't be able to get rid of the control
1130 // flow, so the xform is not worth it.
1131 return false;
1132 }
1133 }
1134
1135 // If we can still promote the PHI nodes after this gauntlet of tests,
1136 // do all of the PHI's now.
1137
1138 // Move all 'aggressive' instructions, which are defined in the
1139 // conditional parts of the if's up to the dominating block.
1140 if (IfBlock1) {
1141 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1142 IfBlock1->getInstList(),
1143 IfBlock1->begin(),
1144 IfBlock1->getTerminator());
1145 }
1146 if (IfBlock2) {
1147 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1148 IfBlock2->getInstList(),
1149 IfBlock2->begin(),
1150 IfBlock2->getTerminator());
1151 }
1152
1153 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1154 // Change the PHI node into a select instruction.
1155 Value *TrueVal =
1156 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1157 Value *FalseVal =
1158 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1159
Gabor Greif051a9502008-04-06 20:25:17 +00001160 Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
Chris Lattner86cc4232007-02-11 01:37:51 +00001161 PN->replaceAllUsesWith(NV);
1162 NV->takeName(PN);
1163
Chris Lattnerf58c1a52005-09-23 06:39:30 +00001164 BB->getInstList().erase(PN);
1165 }
1166 return true;
1167}
Chris Lattnereaba3a12005-09-19 23:49:37 +00001168
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001169/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1170/// to two returning blocks, try to merge them together into one return,
1171/// introducing a select if the return values disagree.
1172static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
1173 assert(BI->isConditional() && "Must be a conditional branch");
1174 BasicBlock *TrueSucc = BI->getSuccessor(0);
1175 BasicBlock *FalseSucc = BI->getSuccessor(1);
1176 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1177 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
1178
1179 // Check to ensure both blocks are empty (just a return) or optionally empty
1180 // with PHI nodes. If there are other instructions, merging would cause extra
1181 // computation on one path or the other.
1182 BasicBlock::iterator BBI = TrueRet;
1183 if (BBI != TrueSucc->begin() && !isa<PHINode>(--BBI))
1184 return false; // Not empty with optional phi nodes.
1185 BBI = FalseRet;
1186 if (BBI != FalseSucc->begin() && !isa<PHINode>(--BBI))
1187 return false; // Not empty with optional phi nodes.
1188
1189 // Okay, we found a branch that is going to two return nodes. If
1190 // there is no return value for this function, just change the
1191 // branch into a return.
1192 if (FalseRet->getNumOperands() == 0) {
1193 TrueSucc->removePredecessor(BI->getParent());
1194 FalseSucc->removePredecessor(BI->getParent());
1195 ReturnInst::Create(0, BI);
1196 BI->eraseFromParent();
1197 return true;
1198 }
1199
1200 // Otherwise, build up the result values for the new return.
1201 SmallVector<Value*, 4> TrueResult;
1202 SmallVector<Value*, 4> FalseResult;
1203
1204 for (unsigned i = 0, e = TrueRet->getNumOperands(); i != e; ++i) {
1205 // Otherwise, figure out what the true and false return values are
1206 // so we can insert a new select instruction.
1207 Value *TrueValue = TrueRet->getOperand(i);
1208 Value *FalseValue = FalseRet->getOperand(i);
1209
1210 // Unwrap any PHI nodes in the return blocks.
1211 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1212 if (TVPN->getParent() == TrueSucc)
1213 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1214 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1215 if (FVPN->getParent() == FalseSucc)
1216 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1217
1218 // In order for this transformation to be safe, we must be able to
1219 // unconditionally execute both operands to the return. This is
1220 // normally the case, but we could have a potentially-trapping
1221 // constant expression that prevents this transformation from being
1222 // safe.
1223 if (ConstantExpr *TCV = dyn_cast<ConstantExpr>(TrueValue))
1224 if (TCV->canTrap())
1225 return false;
1226 if (ConstantExpr *FCV = dyn_cast<ConstantExpr>(FalseValue))
1227 if (FCV->canTrap())
1228 return false;
1229
1230 TrueResult.push_back(TrueValue);
1231 FalseResult.push_back(FalseValue);
1232 }
1233
1234 // Okay, we collected all the mapped values and checked them for sanity, and
1235 // defined to really do this transformation. First, update the CFG.
1236 TrueSucc->removePredecessor(BI->getParent());
1237 FalseSucc->removePredecessor(BI->getParent());
1238
1239 // Insert select instructions where needed.
1240 Value *BrCond = BI->getCondition();
1241 for (unsigned i = 0, e = TrueRet->getNumOperands(); i != e; ++i) {
1242 // Insert a select if the results differ.
1243 if (TrueResult[i] == FalseResult[i] || isa<UndefValue>(FalseResult[i]))
1244 continue;
1245 if (isa<UndefValue>(TrueResult[i])) {
1246 TrueResult[i] = FalseResult[i];
1247 continue;
1248 }
1249
1250 TrueResult[i] = SelectInst::Create(BrCond, TrueResult[i],
1251 FalseResult[i], "retval", BI);
1252 }
1253
1254 Value *RI = ReturnInst::Create(&TrueResult[0], TrueResult.size(), BI);
1255
1256 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1257 << "\n " << *BI << "NewRet = " << *RI
1258 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1259
1260 BI->eraseFromParent();
1261
1262 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1263 ErasePossiblyDeadInstructionTree(BrCondI);
1264 return true;
1265}
1266
1267
Chris Lattner1654cff2004-06-19 07:02:14 +00001268namespace {
1269 /// ConstantIntOrdering - This class implements a stable ordering of constant
1270 /// integers that does not depend on their address. This is important for
1271 /// applications that sort ConstantInt's to ensure uniqueness.
1272 struct ConstantIntOrdering {
1273 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
Reid Spencere1c99d42007-03-02 23:01:14 +00001274 return LHS->getValue().ult(RHS->getValue());
Chris Lattner1654cff2004-06-19 07:02:14 +00001275 }
1276 };
1277}
1278
Chris Lattner01d1ee32002-05-21 20:50:24 +00001279// SimplifyCFG - This function is used to do simplification of a CFG. For
1280// example, it adjusts branches to branches to eliminate the extra hop, it
1281// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +00001282// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +00001283//
1284// WARNING: The entry node of a function may not be simplified.
1285//
Chris Lattnerf7703df2004-01-09 06:12:26 +00001286bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001287 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001288 Function *M = BB->getParent();
1289
1290 assert(BB && BB->getParent() && "Block not embedded in function!");
1291 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Dan Gohmanecb7a772007-03-22 16:38:57 +00001292 assert(&BB->getParent()->getEntryBlock() != BB &&
1293 "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +00001294
Chris Lattner01d1ee32002-05-21 20:50:24 +00001295 // Remove basic blocks that have no predecessors... which are unreachable.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001296 if ((pred_begin(BB) == pred_end(BB)) ||
1297 (*pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB))) {
Bill Wendling0d45a092006-11-26 10:17:54 +00001298 DOUT << "Removing BB: \n" << *BB;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001299
1300 // Loop through all of our successors and make sure they know that one
1301 // of their predecessors is going away.
Chris Lattner151c80b2005-04-12 18:51:33 +00001302 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1303 SI->removePredecessor(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00001304
1305 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +00001306 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +00001307 // If this instruction is used, replace uses with an arbitrary
Chris Lattnerf5e982d2005-08-02 23:29:23 +00001308 // value. Because control flow can't get here, we don't care
Misha Brukmanfd939082005-04-21 23:48:37 +00001309 // what we replace the value with. Note that since this block is
Chris Lattner01d1ee32002-05-21 20:50:24 +00001310 // unreachable, and all values contained within it must dominate their
1311 // uses, that all uses will eventually be removed.
Misha Brukmanfd939082005-04-21 23:48:37 +00001312 if (!I.use_empty())
Chris Lattnerf5e982d2005-08-02 23:29:23 +00001313 // Make all users of this instruction use undef instead
1314 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Misha Brukmanfd939082005-04-21 23:48:37 +00001315
Chris Lattner01d1ee32002-05-21 20:50:24 +00001316 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +00001317 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +00001318 }
Chris Lattner18961502002-06-25 16:12:52 +00001319 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +00001320 return true;
1321 }
1322
Chris Lattner694e37f2003-08-17 19:41:53 +00001323 // Check to see if we can constant propagate this terminator instruction
1324 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +00001325 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +00001326
Dan Gohman882d87d2008-03-11 21:53:06 +00001327 // If there is a trivial two-entry PHI node in this basic block, and we can
1328 // eliminate it, do so now.
1329 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1330 if (PN->getNumIncomingValues() == 2)
1331 Changed |= FoldTwoEntryPHINode(PN);
1332
Chris Lattner19831ec2004-02-16 06:35:48 +00001333 // If this is a returning block with only PHI nodes in it, fold the return
1334 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +00001335 //
1336 // If any predecessor is a conditional branch that just selects among
1337 // different return values, fold the replace the branch/return with a select
1338 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +00001339 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1340 BasicBlock::iterator BBI = BB->getTerminator();
1341 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner147af6b2004-04-02 18:13:43 +00001342 // Find predecessors that end with branches.
Chris Lattner82442432008-02-18 07:42:56 +00001343 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1344 SmallVector<BranchInst*, 8> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +00001345 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1346 TerminatorInst *PTI = (*PI)->getTerminator();
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001347 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
Chris Lattner19831ec2004-02-16 06:35:48 +00001348 if (BI->isUnconditional())
1349 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +00001350 else
1351 CondBranchPreds.push_back(BI);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00001352 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001353 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001354
Chris Lattner19831ec2004-02-16 06:35:48 +00001355 // If we found some, do the transformation!
1356 if (!UncondBranchPreds.empty()) {
1357 while (!UncondBranchPreds.empty()) {
1358 BasicBlock *Pred = UncondBranchPreds.back();
Bill Wendling0d45a092006-11-26 10:17:54 +00001359 DOUT << "FOLDING: " << *BB
1360 << "INTO UNCOND BRANCH PRED: " << *Pred;
Chris Lattner19831ec2004-02-16 06:35:48 +00001361 UncondBranchPreds.pop_back();
1362 Instruction *UncondBranch = Pred->getTerminator();
1363 // Clone the return and add it to the end of the predecessor.
1364 Instruction *NewRet = RI->clone();
1365 Pred->getInstList().push_back(NewRet);
1366
1367 // If the return instruction returns a value, and if the value was a
1368 // PHI node in "BB", propagate the right value into the return.
Chris Lattnerffba5822008-04-28 00:19:07 +00001369 for (unsigned i = 0, e = NewRet->getNumOperands(); i != e; ++i)
1370 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(i)))
Chris Lattner19831ec2004-02-16 06:35:48 +00001371 if (PN->getParent() == BB)
Chris Lattnerffba5822008-04-28 00:19:07 +00001372 NewRet->setOperand(i, PN->getIncomingValueForBlock(Pred));
1373
Chris Lattner19831ec2004-02-16 06:35:48 +00001374 // Update any PHI nodes in the returning block to realize that we no
1375 // longer branch to them.
1376 BB->removePredecessor(Pred);
1377 Pred->getInstList().erase(UncondBranch);
1378 }
1379
1380 // If we eliminated all predecessors of the block, delete the block now.
1381 if (pred_begin(BB) == pred_end(BB))
1382 // We know there are no successors, so just nuke the block.
1383 M->getBasicBlockList().erase(BB);
1384
Chris Lattner19831ec2004-02-16 06:35:48 +00001385 return true;
1386 }
Chris Lattner147af6b2004-04-02 18:13:43 +00001387
1388 // Check out all of the conditional branches going to this return
1389 // instruction. If any of them just select between returns, change the
1390 // branch itself into a select/return pair.
1391 while (!CondBranchPreds.empty()) {
1392 BranchInst *BI = CondBranchPreds.back();
1393 CondBranchPreds.pop_back();
Chris Lattner147af6b2004-04-02 18:13:43 +00001394
1395 // Check to see if the non-BB successor is also a return block.
Chris Lattnerc9e495c2008-04-24 00:01:19 +00001396 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
1397 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
1398 SimplifyCondBranchToTwoReturns(BI))
1399 return true;
Chris Lattner147af6b2004-04-02 18:13:43 +00001400 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001401 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00001402 } else if (isa<UnwindInst>(BB->begin())) {
Chris Lattnere14ea082004-02-24 05:54:22 +00001403 // Check to see if the first instruction in this block is just an unwind.
1404 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001405 // destination with call instructions, and any unconditional branch
1406 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +00001407 //
Chris Lattner82442432008-02-18 07:42:56 +00001408 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnere14ea082004-02-24 05:54:22 +00001409 while (!Preds.empty()) {
1410 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001411 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
Nick Lewycky280a6e62008-04-25 16:53:59 +00001412 if (BI->isUnconditional()) {
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001413 Pred->getInstList().pop_back(); // nuke uncond branch
1414 new UnwindInst(Pred); // Use unwind.
1415 Changed = true;
1416 }
Nick Lewycky3f4cc312008-03-09 07:50:37 +00001417 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +00001418 if (II->getUnwindDest() == BB) {
1419 // Insert a new branch instruction before the invoke, because this
1420 // is now a fall through...
Gabor Greif051a9502008-04-06 20:25:17 +00001421 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattnere14ea082004-02-24 05:54:22 +00001422 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001423
Chris Lattnere14ea082004-02-24 05:54:22 +00001424 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00001425 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00001426 CallInst *CI = CallInst::Create(II->getCalledValue(),
1427 Args.begin(), Args.end(), II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001428 CI->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00001429 CI->setParamAttrs(II->getParamAttrs());
Chris Lattnere14ea082004-02-24 05:54:22 +00001430 // If the invoke produced a value, the Call now does instead
1431 II->replaceAllUsesWith(CI);
1432 delete II;
1433 Changed = true;
1434 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001435
Chris Lattnere14ea082004-02-24 05:54:22 +00001436 Preds.pop_back();
1437 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001438
1439 // If this block is now dead, remove it.
1440 if (pred_begin(BB) == pred_end(BB)) {
1441 // We know there are no successors, so just nuke the block.
1442 M->getBasicBlockList().erase(BB);
1443 return true;
1444 }
1445
Chris Lattner623369a2005-02-24 06:17:52 +00001446 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1447 if (isValueEqualityComparison(SI)) {
1448 // If we only have one predecessor, and if it is a branch on this value,
1449 // see if that predecessor totally determines the outcome of this switch.
1450 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1451 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1452 return SimplifyCFG(BB) || 1;
1453
1454 // If the block only contains the switch, see if we can fold the block
1455 // away into any preds.
1456 if (SI == &BB->front())
1457 if (FoldValueComparisonIntoPredecessors(SI))
1458 return SimplifyCFG(BB) || 1;
1459 }
Chris Lattner542f1492004-02-28 21:28:10 +00001460 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001461 if (BI->isUnconditional()) {
1462 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1463 while (isa<PHINode>(*BBI)) ++BBI;
1464
1465 BasicBlock *Succ = BI->getSuccessor(0);
1466 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1467 Succ != BB) // Don't hurt infinite loops!
1468 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1469 return 1;
1470
1471 } else { // Conditional branch
Reid Spencer3ed469c2006-11-02 20:25:50 +00001472 if (isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001473 // If we only have one predecessor, and if it is a branch on this value,
1474 // see if that predecessor totally determines the outcome of this
1475 // switch.
1476 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1477 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1478 return SimplifyCFG(BB) || 1;
1479
Chris Lattnere67fa052004-05-01 23:35:43 +00001480 // This block must be empty, except for the setcond inst, if it exists.
1481 BasicBlock::iterator I = BB->begin();
1482 if (&*I == BI ||
1483 (&*I == cast<Instruction>(BI->getCondition()) &&
1484 &*++I == BI))
1485 if (FoldValueComparisonIntoPredecessors(BI))
1486 return SimplifyCFG(BB) | true;
1487 }
Chris Lattnereaba3a12005-09-19 23:49:37 +00001488
1489 // If this is a branch on a phi node in the current block, thread control
1490 // through this block if any PHI node entries are constants.
1491 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1492 if (PN->getParent() == BI->getParent())
1493 if (FoldCondBranchOnPHI(BI))
1494 return SimplifyCFG(BB) | true;
Chris Lattnere67fa052004-05-01 23:35:43 +00001495
1496 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1497 // branches to us and one of our successors, fold the setcc into the
1498 // predecessor and use logical operations to pick the right destination.
Chris Lattner12fe2b12004-05-02 05:02:03 +00001499 BasicBlock *TrueDest = BI->getSuccessor(0);
1500 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerdecb0ca2007-04-17 17:47:54 +00001501 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition())) {
1502 BasicBlock::iterator CondIt = Cond;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001503 if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) &&
1504 Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattnerdecb0ca2007-04-17 17:47:54 +00001505 &*++CondIt == BI && Cond->hasOneUse() &&
Chris Lattner12fe2b12004-05-02 05:02:03 +00001506 TrueDest != BB && FalseDest != BB)
Chris Lattnere67fa052004-05-01 23:35:43 +00001507 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1508 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnera1f79fb2004-05-02 01:00:44 +00001509 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001510 BasicBlock *PredBlock = *PI;
Chris Lattnere67fa052004-05-01 23:35:43 +00001511 if (PBI->getSuccessor(0) == FalseDest ||
1512 PBI->getSuccessor(1) == TrueDest) {
1513 // Invert the predecessors condition test (xor it with true),
1514 // which allows us to write this code once.
1515 Value *NewCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001516 BinaryOperator::CreateNot(PBI->getCondition(),
Chris Lattnere67fa052004-05-01 23:35:43 +00001517 PBI->getCondition()->getName()+".not", PBI);
1518 PBI->setCondition(NewCond);
1519 BasicBlock *OldTrue = PBI->getSuccessor(0);
1520 BasicBlock *OldFalse = PBI->getSuccessor(1);
1521 PBI->setSuccessor(0, OldFalse);
1522 PBI->setSuccessor(1, OldTrue);
1523 }
1524
Chris Lattner299520d2006-02-18 00:33:17 +00001525 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1526 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001527 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattnere67fa052004-05-01 23:35:43 +00001528 // two conditions together.
1529 Instruction *New = Cond->clone();
Chris Lattner2636c1b2004-06-21 07:19:01 +00001530 PredBlock->getInstList().insert(PBI, New);
Chris Lattner86cc4232007-02-11 01:37:51 +00001531 New->takeName(Cond);
1532 Cond->setName(New->getName()+".old");
Chris Lattnere67fa052004-05-01 23:35:43 +00001533 Instruction::BinaryOps Opcode =
1534 PBI->getSuccessor(0) == TrueDest ?
1535 Instruction::Or : Instruction::And;
Misha Brukmanfd939082005-04-21 23:48:37 +00001536 Value *NewCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001537 BinaryOperator::Create(Opcode, PBI->getCondition(),
Chris Lattnere67fa052004-05-01 23:35:43 +00001538 New, "bothcond", PBI);
1539 PBI->setCondition(NewCond);
1540 if (PBI->getSuccessor(0) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001541 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +00001542 PBI->setSuccessor(0, TrueDest);
1543 }
1544 if (PBI->getSuccessor(1) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001545 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +00001546 PBI->setSuccessor(1, FalseDest);
1547 }
1548 return SimplifyCFG(BB) | 1;
1549 }
1550 }
Chris Lattnerdecb0ca2007-04-17 17:47:54 +00001551 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001552
Chris Lattnerdecb0ca2007-04-17 17:47:54 +00001553 // Scan predessor blocks for conditional branches.
Chris Lattner2e42e362005-09-20 00:43:16 +00001554 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1555 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner263d1e42005-09-23 18:47:20 +00001556 if (PBI != BI && PBI->isConditional()) {
1557
1558 // If this block ends with a branch instruction, and if there is a
Reid Spencer579dca12007-01-12 04:24:46 +00001559 // predecessor that ends on a branch of the same condition, make
1560 // this conditional branch redundant.
Chris Lattner263d1e42005-09-23 18:47:20 +00001561 if (PBI->getCondition() == BI->getCondition() &&
1562 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1563 // Okay, the outcome of this conditional branch is statically
1564 // knowable. If this block had a single pred, handle specially.
1565 if (BB->getSinglePredecessor()) {
1566 // Turn this into a branch on constant.
1567 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Reid Spencer579dca12007-01-12 04:24:46 +00001568 BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue));
Chris Lattner263d1e42005-09-23 18:47:20 +00001569 return SimplifyCFG(BB); // Nuke the branch on constant.
1570 }
1571
Reid Spencer579dca12007-01-12 04:24:46 +00001572 // Otherwise, if there are multiple predecessors, insert a PHI
1573 // that merges in the constant and simplify the block result.
Chris Lattner263d1e42005-09-23 18:47:20 +00001574 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Gabor Greif051a9502008-04-06 20:25:17 +00001575 PHINode *NewPN = PHINode::Create(Type::Int1Ty,
1576 BI->getCondition()->getName()+".pr",
1577 BB->begin());
Chris Lattner263d1e42005-09-23 18:47:20 +00001578 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1579 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1580 PBI != BI && PBI->isConditional() &&
1581 PBI->getCondition() == BI->getCondition() &&
1582 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1583 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Reid Spencer579dca12007-01-12 04:24:46 +00001584 NewPN->addIncoming(ConstantInt::get(Type::Int1Ty,
1585 CondIsTrue), *PI);
Chris Lattner263d1e42005-09-23 18:47:20 +00001586 } else {
1587 NewPN->addIncoming(BI->getCondition(), *PI);
1588 }
1589
1590 BI->setCondition(NewPN);
1591 // This will thread the branch.
1592 return SimplifyCFG(BB) | true;
1593 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001594 }
1595
Chris Lattner263d1e42005-09-23 18:47:20 +00001596 // If this is a conditional branch in an empty block, and if any
1597 // predecessors is a conditional branch to one of our destinations,
1598 // fold the conditions into logical ops and one cond br.
1599 if (&BB->front() == BI) {
1600 int PBIOp, BIOp;
1601 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1602 PBIOp = BIOp = 0;
1603 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1604 PBIOp = 0; BIOp = 1;
1605 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1606 PBIOp = 1; BIOp = 0;
1607 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1608 PBIOp = BIOp = 1;
1609 } else {
1610 PBIOp = BIOp = -1;
1611 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001612
Chris Lattner299520d2006-02-18 00:33:17 +00001613 // Check to make sure that the other destination of this branch
1614 // isn't BB itself. If so, this is an infinite loop that will
1615 // keep getting unwound.
1616 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1617 PBIOp = BIOp = -1;
Chris Lattner822a8792006-11-18 19:19:36 +00001618
1619 // Do not perform this transformation if it would require
1620 // insertion of a large number of select instructions. For targets
1621 // without predication/cmovs, this is a big pessimization.
1622 if (PBIOp != -1) {
1623 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1624
1625 unsigned NumPhis = 0;
1626 for (BasicBlock::iterator II = CommonDest->begin();
1627 isa<PHINode>(II); ++II, ++NumPhis) {
1628 if (NumPhis > 2) {
1629 // Disable this xform.
1630 PBIOp = -1;
1631 break;
1632 }
1633 }
1634 }
Chris Lattner7f2e1dd2006-06-12 20:18:01 +00001635
Chris Lattner263d1e42005-09-23 18:47:20 +00001636 // Finally, if everything is ok, fold the branches to logical ops.
1637 if (PBIOp != -1) {
1638 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1639 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1640
Chris Lattner7f2e1dd2006-06-12 20:18:01 +00001641 // If OtherDest *is* BB, then this is a basic block with just
1642 // a conditional branch in it, where one edge (OtherDesg) goes
1643 // back to the block. We know that the program doesn't get
1644 // stuck in the infinite loop, so the condition must be such
1645 // that OtherDest isn't branched through. Forward to CommonDest,
1646 // and avoid an infinite loop at optimizer time.
1647 if (OtherDest == BB)
1648 OtherDest = CommonDest;
1649
Bill Wendling0d45a092006-11-26 10:17:54 +00001650 DOUT << "FOLDING BRs:" << *PBI->getParent()
1651 << "AND: " << *BI->getParent();
Chris Lattner263d1e42005-09-23 18:47:20 +00001652
1653 // BI may have other predecessors. Because of this, we leave
1654 // it alone, but modify PBI.
1655
1656 // Make sure we get to CommonDest on True&True directions.
1657 Value *PBICond = PBI->getCondition();
1658 if (PBIOp)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001659 PBICond = BinaryOperator::CreateNot(PBICond,
Chris Lattner263d1e42005-09-23 18:47:20 +00001660 PBICond->getName()+".not",
1661 PBI);
1662 Value *BICond = BI->getCondition();
1663 if (BIOp)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001664 BICond = BinaryOperator::CreateNot(BICond,
Chris Lattner263d1e42005-09-23 18:47:20 +00001665 BICond->getName()+".not",
1666 PBI);
1667 // Merge the conditions.
1668 Value *Cond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001669 BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
Chris Lattner263d1e42005-09-23 18:47:20 +00001670
1671 // Modify PBI to branch on the new condition to the new dests.
1672 PBI->setCondition(Cond);
1673 PBI->setSuccessor(0, CommonDest);
1674 PBI->setSuccessor(1, OtherDest);
1675
1676 // OtherDest may have phi nodes. If so, add an entry from PBI's
1677 // block that are identical to the entries for BI's block.
1678 PHINode *PN;
1679 for (BasicBlock::iterator II = OtherDest->begin();
1680 (PN = dyn_cast<PHINode>(II)); ++II) {
1681 Value *V = PN->getIncomingValueForBlock(BB);
1682 PN->addIncoming(V, PBI->getParent());
1683 }
1684
1685 // We know that the CommonDest already had an edge from PBI to
1686 // it. If it has PHIs though, the PHIs may have different
1687 // entries for BB and PBI's BB. If so, insert a select to make
1688 // them agree.
1689 for (BasicBlock::iterator II = CommonDest->begin();
1690 (PN = dyn_cast<PHINode>(II)); ++II) {
1691 Value * BIV = PN->getIncomingValueForBlock(BB);
1692 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1693 Value *PBIV = PN->getIncomingValue(PBBIdx);
1694 if (BIV != PBIV) {
1695 // Insert a select in PBI to pick the right value.
Gabor Greif051a9502008-04-06 20:25:17 +00001696 Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
1697 PBIV->getName()+".mux", PBI);
Chris Lattner263d1e42005-09-23 18:47:20 +00001698 PN->setIncomingValue(PBBIdx, NV);
1699 }
1700 }
1701
Bill Wendling0d45a092006-11-26 10:17:54 +00001702 DOUT << "INTO: " << *PBI->getParent();
Chris Lattner263d1e42005-09-23 18:47:20 +00001703
1704 // This basic block is probably dead. We know it has at least
1705 // one fewer predecessor.
1706 return SimplifyCFG(BB) | true;
1707 }
Chris Lattner2e42e362005-09-20 00:43:16 +00001708 }
Chris Lattner92da2c22004-05-01 22:36:37 +00001709 }
Chris Lattnerd52c2612004-02-24 07:23:58 +00001710 }
Chris Lattner698f96f2004-10-18 04:07:22 +00001711 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1712 // If there are any instructions immediately before the unreachable that can
1713 // be removed, do so.
1714 Instruction *Unreachable = BB->getTerminator();
1715 while (Unreachable != BB->begin()) {
1716 BasicBlock::iterator BBI = Unreachable;
1717 --BBI;
1718 if (isa<CallInst>(BBI)) break;
1719 // Delete this instruction
1720 BB->getInstList().erase(BBI);
1721 Changed = true;
1722 }
1723
1724 // If the unreachable instruction is the first in the block, take a gander
1725 // at all of the predecessors of this instruction, and simplify them.
1726 if (&BB->front() == Unreachable) {
Chris Lattner82442432008-02-18 07:42:56 +00001727 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner698f96f2004-10-18 04:07:22 +00001728 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1729 TerminatorInst *TI = Preds[i]->getTerminator();
1730
1731 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1732 if (BI->isUnconditional()) {
1733 if (BI->getSuccessor(0) == BB) {
1734 new UnreachableInst(TI);
1735 TI->eraseFromParent();
1736 Changed = true;
1737 }
1738 } else {
1739 if (BI->getSuccessor(0) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00001740 BranchInst::Create(BI->getSuccessor(1), BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00001741 BI->eraseFromParent();
1742 } else if (BI->getSuccessor(1) == BB) {
Gabor Greif051a9502008-04-06 20:25:17 +00001743 BranchInst::Create(BI->getSuccessor(0), BI);
Chris Lattner698f96f2004-10-18 04:07:22 +00001744 BI->eraseFromParent();
1745 Changed = true;
1746 }
1747 }
1748 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1749 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1750 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00001751 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00001752 SI->removeCase(i);
1753 --i; --e;
1754 Changed = true;
1755 }
1756 // If the default value is unreachable, figure out the most popular
1757 // destination and make it the default.
1758 if (SI->getSuccessor(0) == BB) {
1759 std::map<BasicBlock*, unsigned> Popularity;
1760 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1761 Popularity[SI->getSuccessor(i)]++;
1762
1763 // Find the most popular block.
1764 unsigned MaxPop = 0;
1765 BasicBlock *MaxBlock = 0;
1766 for (std::map<BasicBlock*, unsigned>::iterator
1767 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1768 if (I->second > MaxPop) {
1769 MaxPop = I->second;
1770 MaxBlock = I->first;
1771 }
1772 }
1773 if (MaxBlock) {
1774 // Make this the new default, allowing us to delete any explicit
1775 // edges to it.
1776 SI->setSuccessor(0, MaxBlock);
1777 Changed = true;
1778
Chris Lattner42eb7522005-05-20 22:19:54 +00001779 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1780 // it.
1781 if (isa<PHINode>(MaxBlock->begin()))
1782 for (unsigned i = 0; i != MaxPop-1; ++i)
1783 MaxBlock->removePredecessor(SI->getParent());
1784
Chris Lattner698f96f2004-10-18 04:07:22 +00001785 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1786 if (SI->getSuccessor(i) == MaxBlock) {
1787 SI->removeCase(i);
1788 --i; --e;
1789 }
1790 }
1791 }
1792 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1793 if (II->getUnwindDest() == BB) {
1794 // Convert the invoke to a call instruction. This would be a good
1795 // place to note that the call does not throw though.
Gabor Greif051a9502008-04-06 20:25:17 +00001796 BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Chris Lattner698f96f2004-10-18 04:07:22 +00001797 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001798
Chris Lattner698f96f2004-10-18 04:07:22 +00001799 // Insert the call now...
Chris Lattner93e985f2007-02-13 02:10:56 +00001800 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +00001801 CallInst *CI = CallInst::Create(II->getCalledValue(),
1802 Args.begin(), Args.end(),
1803 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001804 CI->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00001805 CI->setParamAttrs(II->getParamAttrs());
Chris Lattner698f96f2004-10-18 04:07:22 +00001806 // If the invoke produced a value, the Call does now instead.
1807 II->replaceAllUsesWith(CI);
1808 delete II;
1809 Changed = true;
1810 }
1811 }
1812 }
1813
1814 // If this block is now dead, remove it.
1815 if (pred_begin(BB) == pred_end(BB)) {
1816 // We know there are no successors, so just nuke the block.
1817 M->getBasicBlockList().erase(BB);
1818 return true;
1819 }
1820 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001821 }
1822
Chris Lattner01d1ee32002-05-21 20:50:24 +00001823 // Merge basic blocks into their predecessor if there is only one distinct
1824 // pred, and if there is only one distinct successor of the predecessor, and
1825 // if there are no PHI nodes.
1826 //
Chris Lattner2355f942004-02-11 01:17:07 +00001827 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1828 BasicBlock *OnlyPred = *PI++;
1829 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1830 if (*PI != OnlyPred) {
1831 OnlyPred = 0; // There are multiple different predecessors...
1832 break;
1833 }
Chris Lattner92da2c22004-05-01 22:36:37 +00001834
Chris Lattner2355f942004-02-11 01:17:07 +00001835 BasicBlock *OnlySucc = 0;
1836 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1837 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1838 // Check to see if there is only one distinct successor...
1839 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1840 OnlySucc = BB;
1841 for (; SI != SE; ++SI)
1842 if (*SI != OnlySucc) {
1843 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner01d1ee32002-05-21 20:50:24 +00001844 break;
1845 }
Chris Lattner2355f942004-02-11 01:17:07 +00001846 }
1847
Nick Lewycky280a6e62008-04-25 16:53:59 +00001848 if (OnlySucc) {
Bill Wendling0d45a092006-11-26 10:17:54 +00001849 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
Chris Lattner2355f942004-02-11 01:17:07 +00001850
1851 // Resolve any PHI nodes at the start of the block. They are all
1852 // guaranteed to have exactly one entry if they exist, unless there are
1853 // multiple duplicate (but guaranteed to be equal) entries for the
1854 // incoming edges. This occurs when there are multiple edges from
1855 // OnlyPred to OnlySucc.
1856 //
1857 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1858 PN->replaceAllUsesWith(PN->getIncomingValue(0));
Chris Lattner86cc4232007-02-11 01:37:51 +00001859 BB->getInstList().pop_front(); // Delete the phi node.
Chris Lattner01d1ee32002-05-21 20:50:24 +00001860 }
1861
Chris Lattner86cc4232007-02-11 01:37:51 +00001862 // Delete the unconditional branch from the predecessor.
Chris Lattner2355f942004-02-11 01:17:07 +00001863 OnlyPred->getInstList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001864
Chris Lattner86cc4232007-02-11 01:37:51 +00001865 // Move all definitions in the successor to the predecessor.
Chris Lattner2355f942004-02-11 01:17:07 +00001866 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Misha Brukmanfd939082005-04-21 23:48:37 +00001867
Chris Lattner2355f942004-02-11 01:17:07 +00001868 // Make all PHI nodes that referred to BB now refer to Pred as their
Chris Lattner86cc4232007-02-11 01:37:51 +00001869 // source.
Chris Lattner2355f942004-02-11 01:17:07 +00001870 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +00001871
Chris Lattner86cc4232007-02-11 01:37:51 +00001872 // Inherit predecessors name if it exists.
1873 if (!OnlyPred->hasName())
1874 OnlyPred->takeName(BB);
1875
1876 // Erase basic block from the function.
Chris Lattner2355f942004-02-11 01:17:07 +00001877 M->getBasicBlockList().erase(BB);
Chris Lattner18961502002-06-25 16:12:52 +00001878
Chris Lattner2355f942004-02-11 01:17:07 +00001879 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001880 }
Chris Lattner723c66d2004-02-11 03:36:04 +00001881
Chris Lattner37dc9382004-11-30 00:29:14 +00001882 // Otherwise, if this block only has a single predecessor, and if that block
1883 // is a conditional branch, see if we can hoist any code from this block up
1884 // into our predecessor.
1885 if (OnlyPred)
Chris Lattner76134372004-12-10 17:42:31 +00001886 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1887 if (BI->isConditional()) {
1888 // Get the other block.
1889 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1890 PI = pred_begin(OtherBB);
1891 ++PI;
1892 if (PI == pred_end(OtherBB)) {
1893 // We have a conditional branch to two blocks that are only reachable
1894 // from the condbr. We know that the condbr dominates the two blocks,
1895 // so see if there is any identical code in the "then" and "else"
1896 // blocks. If so, we can hoist it up to the branching block.
1897 Changed |= HoistThenElseCodeToIf(BI);
1898 }
Chris Lattner37dc9382004-11-30 00:29:14 +00001899 }
Chris Lattner37dc9382004-11-30 00:29:14 +00001900
Chris Lattner0d560082004-02-24 05:38:11 +00001901 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1902 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1903 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1904 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1905 Instruction *Cond = cast<Instruction>(BI->getCondition());
1906 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1907 // 'setne's and'ed together, collect them.
1908 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +00001909 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +00001910 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
Chris Lattner42a75512007-01-15 02:27:26 +00001911 if (CompVal && CompVal->getType()->isInteger()) {
Chris Lattner0d560082004-02-24 05:38:11 +00001912 // There might be duplicate constants in the list, which the switch
1913 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +00001914 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +00001915 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanfd939082005-04-21 23:48:37 +00001916
Chris Lattner0d560082004-02-24 05:38:11 +00001917 // Figure out which block is which destination.
1918 BasicBlock *DefaultBB = BI->getSuccessor(1);
1919 BasicBlock *EdgeBB = BI->getSuccessor(0);
1920 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00001921
Chris Lattner0d560082004-02-24 05:38:11 +00001922 // Create the new switch instruction now.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00001923 SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
1924 Values.size(), BI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001925
Chris Lattner0d560082004-02-24 05:38:11 +00001926 // Add all of the 'cases' to the switch instruction.
1927 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1928 New->addCase(Values[i], EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00001929
Chris Lattner0d560082004-02-24 05:38:11 +00001930 // We added edges from PI to the EdgeBB. As such, if there were any
1931 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1932 // the number of edges added.
1933 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +00001934 isa<PHINode>(BBI); ++BBI) {
1935 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner0d560082004-02-24 05:38:11 +00001936 Value *InVal = PN->getIncomingValueForBlock(*PI);
1937 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1938 PN->addIncoming(InVal, *PI);
1939 }
1940
1941 // Erase the old branch instruction.
1942 (*PI)->getInstList().erase(BI);
1943
1944 // Erase the potentially condition tree that was used to computed the
1945 // branch condition.
1946 ErasePossiblyDeadInstructionTree(Cond);
1947 return true;
1948 }
1949 }
1950
Chris Lattner694e37f2003-08-17 19:41:53 +00001951 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001952}