blob: 7ac944446e2f0ba9cda11fa13229b5aa06e776ed [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner9734fd02004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner466a0492002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner18d1f192004-02-11 03:36:04 +000016#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Chris Lattner6f4b45a2004-02-24 05:38:11 +000018#include "llvm/Type.h"
Chris Lattner466a0492002-05-21 20:50:24 +000019#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000020#include "llvm/Support/Debug.h"
Chris Lattner748f9032005-09-19 23:49:37 +000021#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner466a0492002-05-21 20:50:24 +000022#include <algorithm>
23#include <functional>
Chris Lattnera2ab4892004-02-24 07:23:58 +000024#include <set>
Chris Lattner5edb2f32004-10-18 04:07:22 +000025#include <map>
Chris Lattner469640e2006-01-22 22:53:01 +000026#include <iostream>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000027using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000028
Chris Lattner76dc2042005-08-03 00:19:45 +000029/// SafeToMergeTerminators - Return true if it is safe to merge these two
30/// terminator instructions together.
31///
32static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
33 if (SI1 == SI2) return false; // Can't merge with self!
34
35 // It is not safe to merge these two switch instructions if they have a common
36 // successor, and if that successor has a PHI node, and if *that* PHI node has
37 // conflicting incoming values from the two switch blocks.
38 BasicBlock *SI1BB = SI1->getParent();
39 BasicBlock *SI2BB = SI2->getParent();
40 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
41
42 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
43 if (SI1Succs.count(*I))
44 for (BasicBlock::iterator BBI = (*I)->begin();
45 isa<PHINode>(BBI); ++BBI) {
46 PHINode *PN = cast<PHINode>(BBI);
47 if (PN->getIncomingValueForBlock(SI1BB) !=
48 PN->getIncomingValueForBlock(SI2BB))
49 return false;
50 }
51
52 return true;
53}
54
55/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
56/// now be entries in it from the 'NewPred' block. The values that will be
57/// flowing into the PHI nodes will be the same as those coming in from
58/// ExistPred, an existing predecessor of Succ.
59static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
60 BasicBlock *ExistPred) {
61 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
62 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
63 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
64
65 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
66 PHINode *PN = cast<PHINode>(I);
67 Value *V = PN->getIncomingValueForBlock(ExistPred);
68 PN->addIncoming(V, NewPred);
69 }
70}
71
Chris Lattner982b75c2005-08-03 00:29:26 +000072// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
73// almost-empty BB ending in an unconditional branch to Succ, into succ.
Chris Lattner466a0492002-05-21 20:50:24 +000074//
75// Assumption: Succ is the single successor for BB.
76//
Chris Lattner982b75c2005-08-03 00:29:26 +000077static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000078 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000079
Chris Lattner466a0492002-05-21 20:50:24 +000080 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000081 // Succ. If so, we cannot do the transformation if there are any PHI nodes
82 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000083 //
Chris Lattner90803692005-08-03 00:38:27 +000084 if (isa<PHINode>(Succ->front())) {
85 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner2820b8c2005-12-03 18:25:58 +000086 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
Chris Lattner90803692005-08-03 00:38:27 +000087 PI != PE; ++PI)
88 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
89 // Loop over all of the PHI nodes checking to see if there are
90 // incompatible values coming in.
91 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
92 PHINode *PN = cast<PHINode>(I);
93 // Loop up the entries in the PHI node for BB and for *PI if the
94 // values coming in are non-equal, we cannot merge these two blocks
95 // (instead we should insert a conditional move or something, then
96 // merge the blocks).
97 if (PN->getIncomingValueForBlock(BB) !=
98 PN->getIncomingValueForBlock(*PI))
99 return false; // Values are not equal...
100 }
101 }
102 }
Chris Lattner2dbf1962005-08-03 00:59:12 +0000103
104 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
105 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
106 // fold these blocks, as we don't know whether BB dominates Succ or not to
107 // update the PHI nodes correctly.
108 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000109
Chris Lattner2dbf1962005-08-03 00:59:12 +0000110 // If the predecessors of Succ are only BB and Succ itself, we can handle this.
111 bool IsSafe = true;
112 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
113 if (*PI != Succ && *PI != BB) {
114 IsSafe = false;
115 break;
116 }
117 if (IsSafe) return true;
118
Chris Lattner2820b8c2005-12-03 18:25:58 +0000119 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
120 // BB and Succ have no common predecessors.
Chris Lattner35515552006-05-14 18:45:44 +0000121 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
Chris Lattner2dbf1962005-08-03 00:59:12 +0000122 PHINode *PN = cast<PHINode>(I);
123 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
124 ++UI)
Chris Lattner2820b8c2005-12-03 18:25:58 +0000125 if (cast<Instruction>(*UI)->getParent() != Succ)
126 return false;
Chris Lattner2dbf1962005-08-03 00:59:12 +0000127 }
128
Chris Lattner2820b8c2005-12-03 18:25:58 +0000129 // Scan the predecessor sets of BB and Succ, making sure there are no common
130 // predecessors. Common predecessors would cause us to build a phi node with
131 // differing incoming values, which is not legal.
132 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
133 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
134 if (BBPreds.count(*PI))
135 return false;
136
137 return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000138}
139
Chris Lattner733d6702005-08-03 00:11:16 +0000140/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
141/// branch to Succ, and contains no instructions other than PHI nodes and the
142/// branch. If possible, eliminate BB.
143static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
144 BasicBlock *Succ) {
145 // If our successor has PHI nodes, then we need to update them to include
146 // entries for BB's predecessors, not for BB itself. Be careful though,
147 // if this transformation fails (returns true) then we cannot do this
148 // transformation!
149 //
Chris Lattner982b75c2005-08-03 00:29:26 +0000150 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner733d6702005-08-03 00:11:16 +0000151
152 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
153
Chris Lattner982b75c2005-08-03 00:29:26 +0000154 if (isa<PHINode>(Succ->begin())) {
155 // If there is more than one pred of succ, and there are PHI nodes in
156 // the successor, then we need to add incoming edges for the PHI nodes
157 //
158 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
159
160 // Loop over all of the PHI nodes in the successor of BB.
161 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
162 PHINode *PN = cast<PHINode>(I);
163 Value *OldVal = PN->removeIncomingValue(BB, false);
164 assert(OldVal && "No entry in PHI for Pred BB!");
165
Chris Lattner90803692005-08-03 00:38:27 +0000166 // If this incoming value is one of the PHI nodes in BB, the new entries
167 // in the PHI node are the entries from the old PHI.
Chris Lattner982b75c2005-08-03 00:29:26 +0000168 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
169 PHINode *OldValPN = cast<PHINode>(OldVal);
170 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
171 PN->addIncoming(OldValPN->getIncomingValue(i),
172 OldValPN->getIncomingBlock(i));
173 } else {
174 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
175 End = BBPreds.end(); PredI != End; ++PredI) {
176 // Add an incoming value for each of the new incoming values...
177 PN->addIncoming(OldVal, *PredI);
178 }
179 }
180 }
181 }
182
Chris Lattner733d6702005-08-03 00:11:16 +0000183 if (isa<PHINode>(&BB->front())) {
184 std::vector<BasicBlock*>
185 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
186
187 // Move all PHI nodes in BB to Succ if they are alive, otherwise
188 // delete them.
189 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
Chris Lattner90803692005-08-03 00:38:27 +0000190 if (PN->use_empty()) {
191 // Just remove the dead phi. This happens if Succ's PHIs were the only
192 // users of the PHI nodes.
193 PN->eraseFromParent();
Chris Lattner733d6702005-08-03 00:11:16 +0000194 } else {
195 // The instruction is alive, so this means that Succ must have
196 // *ONLY* had BB as a predecessor, and the PHI node is still valid
197 // now. Simply move it into Succ, because we know that BB
198 // strictly dominated Succ.
Chris Lattner1f047fd2005-08-03 00:23:42 +0000199 Succ->getInstList().splice(Succ->begin(),
200 BB->getInstList(), BB->begin());
Chris Lattner733d6702005-08-03 00:11:16 +0000201
202 // We need to add new entries for the PHI node to account for
203 // predecessors of Succ that the PHI node does not take into
204 // account. At this point, since we know that BB dominated succ,
205 // this means that we should any newly added incoming edges should
206 // use the PHI node as the value for these edges, because they are
207 // loop back edges.
208 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
209 if (OldSuccPreds[i] != BB)
210 PN->addIncoming(PN, OldSuccPreds[i]);
211 }
212 }
213
214 // Everything that jumped to BB now goes to Succ.
215 std::string OldName = BB->getName();
216 BB->replaceAllUsesWith(Succ);
217 BB->eraseFromParent(); // Delete the old basic block.
218
219 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
220 Succ->setName(OldName);
221 return true;
222}
223
Chris Lattner18d1f192004-02-11 03:36:04 +0000224/// GetIfCondition - Given a basic block (BB) with two predecessors (and
225/// presumably PHI nodes in it), check to see if the merge at this block is due
226/// to an "if condition". If so, return the boolean condition that determines
227/// which entry into BB will be taken. Also, return by references the block
228/// that will be entered from if the condition is true, and the block that will
229/// be entered if the condition is false.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000230///
Chris Lattner18d1f192004-02-11 03:36:04 +0000231///
232static Value *GetIfCondition(BasicBlock *BB,
233 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
234 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
235 "Function can only handle blocks with 2 predecessors!");
236 BasicBlock *Pred1 = *pred_begin(BB);
237 BasicBlock *Pred2 = *++pred_begin(BB);
238
239 // We can only handle branches. Other control flow will be lowered to
240 // branches if possible anyway.
241 if (!isa<BranchInst>(Pred1->getTerminator()) ||
242 !isa<BranchInst>(Pred2->getTerminator()))
243 return 0;
244 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
245 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
246
247 // Eliminate code duplication by ensuring that Pred1Br is conditional if
248 // either are.
249 if (Pred2Br->isConditional()) {
250 // If both branches are conditional, we don't have an "if statement". In
251 // reality, we could transform this case, but since the condition will be
252 // required anyway, we stand no chance of eliminating it, so the xform is
253 // probably not profitable.
254 if (Pred1Br->isConditional())
255 return 0;
256
257 std::swap(Pred1, Pred2);
258 std::swap(Pred1Br, Pred2Br);
259 }
260
261 if (Pred1Br->isConditional()) {
262 // If we found a conditional branch predecessor, make sure that it branches
263 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
264 if (Pred1Br->getSuccessor(0) == BB &&
265 Pred1Br->getSuccessor(1) == Pred2) {
266 IfTrue = Pred1;
267 IfFalse = Pred2;
268 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
269 Pred1Br->getSuccessor(1) == BB) {
270 IfTrue = Pred2;
271 IfFalse = Pred1;
272 } else {
273 // We know that one arm of the conditional goes to BB, so the other must
274 // go somewhere unrelated, and this must not be an "if statement".
275 return 0;
276 }
277
278 // The only thing we have to watch out for here is to make sure that Pred2
279 // doesn't have incoming edges from other blocks. If it does, the condition
280 // doesn't dominate BB.
281 if (++pred_begin(Pred2) != pred_end(Pred2))
282 return 0;
283
284 return Pred1Br->getCondition();
285 }
286
287 // Ok, if we got here, both predecessors end with an unconditional branch to
288 // BB. Don't panic! If both blocks only have a single (identical)
289 // predecessor, and THAT is a conditional branch, then we're all ok!
290 if (pred_begin(Pred1) == pred_end(Pred1) ||
291 ++pred_begin(Pred1) != pred_end(Pred1) ||
292 pred_begin(Pred2) == pred_end(Pred2) ||
293 ++pred_begin(Pred2) != pred_end(Pred2) ||
294 *pred_begin(Pred1) != *pred_begin(Pred2))
295 return 0;
296
297 // Otherwise, if this is a conditional branch, then we can use it!
298 BasicBlock *CommonPred = *pred_begin(Pred1);
299 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
300 assert(BI->isConditional() && "Two successors but not conditional?");
301 if (BI->getSuccessor(0) == Pred1) {
302 IfTrue = Pred1;
303 IfFalse = Pred2;
304 } else {
305 IfTrue = Pred2;
306 IfFalse = Pred1;
307 }
308 return BI->getCondition();
309 }
310 return 0;
311}
312
313
314// If we have a merge point of an "if condition" as accepted above, return true
315// if the specified value dominates the block. We don't handle the true
316// generality of domination here, just a special case which works well enough
317// for us.
Chris Lattner45c35b12004-10-14 05:13:36 +0000318//
319// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
320// see if V (which must be an instruction) is cheap to compute and is
321// non-trapping. If both are true, the instruction is inserted into the set and
322// true is returned.
323static bool DominatesMergePoint(Value *V, BasicBlock *BB,
324 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000325 Instruction *I = dyn_cast<Instruction>(V);
326 if (!I) return true; // Non-instructions all dominate instructions.
327 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000328
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000329 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000330 // the bottom of this block.
331 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000332
Chris Lattner0aa56562004-04-09 22:50:22 +0000333 // If this instruction is defined in a block that contains an unconditional
334 // branch to BB, then it must be in the 'conditional' part of the "if
335 // statement".
336 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
337 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner45c35b12004-10-14 05:13:36 +0000338 if (!AggressiveInsts) return false;
Chris Lattner0aa56562004-04-09 22:50:22 +0000339 // Okay, it looks like the instruction IS in the "condition". Check to
340 // see if its a cheap instruction to unconditionally compute, and if it
341 // only uses stuff defined outside of the condition. If so, hoist it out.
342 switch (I->getOpcode()) {
343 default: return false; // Cannot hoist this out safely.
344 case Instruction::Load:
345 // We can hoist loads that are non-volatile and obviously cannot trap.
346 if (cast<LoadInst>(I)->isVolatile())
347 return false;
348 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spenceref784f02004-07-18 00:32:14 +0000349 !isa<Constant>(I->getOperand(0)))
Chris Lattner0aa56562004-04-09 22:50:22 +0000350 return false;
351
352 // Finally, we have to check to make sure there are no instructions
353 // before the load in its basic block, as we are going to hoist the loop
354 // out to its predecessor.
355 if (PBB->begin() != BasicBlock::iterator(I))
356 return false;
357 break;
358 case Instruction::Add:
359 case Instruction::Sub:
360 case Instruction::And:
361 case Instruction::Or:
362 case Instruction::Xor:
363 case Instruction::Shl:
364 case Instruction::Shr:
Chris Lattnerb38b4432005-04-21 05:31:13 +0000365 case Instruction::SetEQ:
366 case Instruction::SetNE:
367 case Instruction::SetLT:
368 case Instruction::SetGT:
369 case Instruction::SetLE:
370 case Instruction::SetGE:
Chris Lattner0aa56562004-04-09 22:50:22 +0000371 break; // These are all cheap and non-trapping instructions.
372 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000373
Chris Lattner0aa56562004-04-09 22:50:22 +0000374 // Okay, we can only really hoist these out if their operands are not
375 // defined in the conditional region.
376 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner45c35b12004-10-14 05:13:36 +0000377 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner0aa56562004-04-09 22:50:22 +0000378 return false;
Chris Lattner45c35b12004-10-14 05:13:36 +0000379 // Okay, it's safe to do this! Remember this instruction.
380 AggressiveInsts->insert(I);
Chris Lattner0aa56562004-04-09 22:50:22 +0000381 }
382
Chris Lattner18d1f192004-02-11 03:36:04 +0000383 return true;
384}
Chris Lattner466a0492002-05-21 20:50:24 +0000385
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000386// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
387// instructions that compare a value against a constant, return the value being
388// compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000389static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000390 if (Instruction *Inst = dyn_cast<Instruction>(V))
391 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000392 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000393 Values.push_back(C);
394 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000395 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000396 Values.push_back(C);
397 return Inst->getOperand(1);
398 }
399 } else if (Inst->getOpcode() == Instruction::Or) {
400 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
401 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
402 if (LHS == RHS)
403 return LHS;
404 }
405 return 0;
406}
407
408// GatherConstantSetNEs - Given a potentially 'and'd together collection of
409// setne instructions that compare a value against a constant, return the value
410// being compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000411static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000412 if (Instruction *Inst = dyn_cast<Instruction>(V))
413 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000414 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000415 Values.push_back(C);
416 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000417 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000418 Values.push_back(C);
419 return Inst->getOperand(1);
420 }
421 } else if (Inst->getOpcode() == Instruction::Cast) {
422 // Cast of X to bool is really a comparison against zero.
423 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000424 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000425 return Inst->getOperand(0);
426 } else if (Inst->getOpcode() == Instruction::And) {
427 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
428 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
429 if (LHS == RHS)
430 return LHS;
431 }
432 return 0;
433}
434
435
436
437/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
438/// bunch of comparisons of one value against constants, return the value and
439/// the constants being compared.
440static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000441 std::vector<ConstantInt*> &Values) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000442 if (Cond->getOpcode() == Instruction::Or) {
443 CompVal = GatherConstantSetEQs(Cond, Values);
444
445 // Return true to indicate that the condition is true if the CompVal is
446 // equal to one of the constants.
447 return true;
448 } else if (Cond->getOpcode() == Instruction::And) {
449 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000450
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000451 // Return false to indicate that the condition is false if the CompVal is
452 // equal to one of the constants.
453 return false;
454 }
455 return false;
456}
457
458/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
459/// has no side effects, nuke it. If it uses any instructions that become dead
460/// because the instruction is now gone, nuke them too.
461static void ErasePossiblyDeadInstructionTree(Instruction *I) {
Chris Lattnerc9009d92006-08-03 21:40:24 +0000462 if (!isInstructionTriviallyDead(I)) return;
463
464 std::vector<Instruction*> InstrsToInspect;
465 InstrsToInspect.push_back(I);
466
467 while (!InstrsToInspect.empty()) {
468 I = InstrsToInspect.back();
469 InstrsToInspect.pop_back();
470
471 if (!isInstructionTriviallyDead(I)) continue;
472
473 // If I is in the work list multiple times, remove previous instances.
474 for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
475 if (InstrsToInspect[i] == I) {
476 InstrsToInspect.erase(InstrsToInspect.begin()+i);
477 --i, --e;
478 }
479
480 // Add operands of dead instruction to worklist.
481 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
482 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
483 InstrsToInspect.push_back(OpI);
484
485 // Remove dead instruction.
486 I->eraseFromParent();
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000487 }
488}
489
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000490// isValueEqualityComparison - Return true if the specified terminator checks to
491// see if a value is equal to constant integer value.
492static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattnera64923a2004-03-16 19:45:22 +0000493 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
494 // Do not permit merging of large switch instructions into their
495 // predecessors unless there is only one predecessor.
496 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
497 pred_end(SI->getParent())) > 128)
498 return 0;
499
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000500 return SI->getCondition();
Chris Lattnera64923a2004-03-16 19:45:22 +0000501 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000502 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
503 if (BI->isConditional() && BI->getCondition()->hasOneUse())
504 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
505 if ((SCI->getOpcode() == Instruction::SetEQ ||
Misha Brukmanb1c93172005-04-21 23:48:37 +0000506 SCI->getOpcode() == Instruction::SetNE) &&
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000507 isa<ConstantInt>(SCI->getOperand(1)))
508 return SCI->getOperand(0);
509 return 0;
510}
511
512// Given a value comparison instruction, decode all of the 'cases' that it
513// represents and return the 'default' block.
514static BasicBlock *
Misha Brukmanb1c93172005-04-21 23:48:37 +0000515GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000516 std::vector<std::pair<ConstantInt*,
517 BasicBlock*> > &Cases) {
518 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
519 Cases.reserve(SI->getNumCases());
520 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnercc6d75f2005-02-26 18:33:28 +0000521 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000522 return SI->getDefaultDest();
523 }
524
525 BranchInst *BI = cast<BranchInst>(TI);
526 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
527 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
528 BI->getSuccessor(SCI->getOpcode() ==
529 Instruction::SetNE)));
530 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
531}
532
533
Chris Lattner1cca9592005-02-24 06:17:52 +0000534// EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
535// in the list that match the specified block.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000536static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner1cca9592005-02-24 06:17:52 +0000537 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
538 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
539 if (Cases[i].second == BB) {
540 Cases.erase(Cases.begin()+i);
541 --i; --e;
542 }
543}
544
545// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
546// well.
547static bool
548ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
549 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
550 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
551
552 // Make V1 be smaller than V2.
553 if (V1->size() > V2->size())
554 std::swap(V1, V2);
555
556 if (V1->size() == 0) return false;
557 if (V1->size() == 1) {
558 // Just scan V2.
559 ConstantInt *TheVal = (*V1)[0].first;
560 for (unsigned i = 0, e = V2->size(); i != e; ++i)
561 if (TheVal == (*V2)[i].first)
562 return true;
563 }
564
565 // Otherwise, just sort both lists and compare element by element.
566 std::sort(V1->begin(), V1->end());
567 std::sort(V2->begin(), V2->end());
568 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
569 while (i1 != e1 && i2 != e2) {
570 if ((*V1)[i1].first == (*V2)[i2].first)
571 return true;
572 if ((*V1)[i1].first < (*V2)[i2].first)
573 ++i1;
574 else
575 ++i2;
576 }
577 return false;
578}
579
580// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
581// terminator instruction and its block is known to only have a single
582// predecessor block, check to see if that predecessor is also a value
583// comparison with the same value, and if that comparison determines the outcome
584// of this comparison. If so, simplify TI. This does a very limited form of
585// jump threading.
586static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
587 BasicBlock *Pred) {
588 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
589 if (!PredVal) return false; // Not a value comparison in predecessor.
590
591 Value *ThisVal = isValueEqualityComparison(TI);
592 assert(ThisVal && "This isn't a value comparison!!");
593 if (ThisVal != PredVal) return false; // Different predicates.
594
595 // Find out information about when control will move from Pred to TI's block.
596 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
597 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
598 PredCases);
599 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000600
Chris Lattner1cca9592005-02-24 06:17:52 +0000601 // Find information about how control leaves this block.
602 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
603 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
604 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
605
606 // If TI's block is the default block from Pred's comparison, potentially
607 // simplify TI based on this knowledge.
608 if (PredDef == TI->getParent()) {
609 // If we are here, we know that the value is none of those cases listed in
610 // PredCases. If there are any cases in ThisCases that are in PredCases, we
611 // can simplify TI.
612 if (ValuesOverlap(PredCases, ThisCases)) {
613 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
614 // Okay, one of the successors of this condbr is dead. Convert it to a
615 // uncond br.
616 assert(ThisCases.size() == 1 && "Branch can only have one case!");
617 Value *Cond = BTI->getCondition();
618 // Insert the new branch.
619 Instruction *NI = new BranchInst(ThisDef, TI);
620
621 // Remove PHI node entries for the dead edge.
622 ThisCases[0].second->removePredecessor(TI->getParent());
623
624 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
625 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
626
627 TI->eraseFromParent(); // Nuke the old one.
628 // If condition is now dead, nuke it.
629 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
630 ErasePossiblyDeadInstructionTree(CondI);
631 return true;
632
633 } else {
634 SwitchInst *SI = cast<SwitchInst>(TI);
635 // Okay, TI has cases that are statically dead, prune them away.
636 std::set<Constant*> DeadCases;
637 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
638 DeadCases.insert(PredCases[i].first);
639
640 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
641 << "Through successor TI: " << *TI);
642
643 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
644 if (DeadCases.count(SI->getCaseValue(i))) {
645 SI->getSuccessor(i)->removePredecessor(TI->getParent());
646 SI->removeCase(i);
647 }
648
649 DEBUG(std::cerr << "Leaving: " << *TI << "\n");
650 return true;
651 }
652 }
653
654 } else {
655 // Otherwise, TI's block must correspond to some matched value. Find out
656 // which value (or set of values) this is.
657 ConstantInt *TIV = 0;
658 BasicBlock *TIBB = TI->getParent();
659 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
660 if (PredCases[i].second == TIBB)
661 if (TIV == 0)
662 TIV = PredCases[i].first;
663 else
664 return false; // Cannot handle multiple values coming to this block.
665 assert(TIV && "No edge from pred to succ?");
666
667 // Okay, we found the one constant that our value can be if we get into TI's
668 // BB. Find out which successor will unconditionally be branched to.
669 BasicBlock *TheRealDest = 0;
670 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
671 if (ThisCases[i].first == TIV) {
672 TheRealDest = ThisCases[i].second;
673 break;
674 }
675
676 // If not handled by any explicit cases, it is handled by the default case.
677 if (TheRealDest == 0) TheRealDest = ThisDef;
678
679 // Remove PHI node entries for dead edges.
680 BasicBlock *CheckEdge = TheRealDest;
681 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
682 if (*SI != CheckEdge)
683 (*SI)->removePredecessor(TIBB);
684 else
685 CheckEdge = 0;
686
687 // Insert the new branch.
688 Instruction *NI = new BranchInst(TheRealDest, TI);
689
690 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
691 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
692 Instruction *Cond = 0;
693 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
694 Cond = dyn_cast<Instruction>(BI->getCondition());
695 TI->eraseFromParent(); // Nuke the old one.
696
697 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
698 return true;
699 }
700 return false;
701}
702
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000703// FoldValueComparisonIntoPredecessors - The specified terminator is a value
704// equality comparison instruction (either a switch or a branch on "X == c").
705// See if any of the predecessors of the terminator block are value comparisons
706// on the same value. If so, and if safe to do so, fold them together.
707static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
708 BasicBlock *BB = TI->getParent();
709 Value *CV = isValueEqualityComparison(TI); // CondVal
710 assert(CV && "Not a comparison?");
711 bool Changed = false;
712
713 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
714 while (!Preds.empty()) {
715 BasicBlock *Pred = Preds.back();
716 Preds.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000717
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000718 // See if the predecessor is a comparison with the same value.
719 TerminatorInst *PTI = Pred->getTerminator();
720 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
721
722 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
723 // Figure out which 'cases' to copy from SI to PSI.
724 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
725 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
726
727 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
728 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
729
730 // Based on whether the default edge from PTI goes to BB or not, fill in
731 // PredCases and PredDefault with the new switch cases we would like to
732 // build.
733 std::vector<BasicBlock*> NewSuccessors;
734
735 if (PredDefault == BB) {
736 // If this is the default destination from PTI, only the edges in TI
737 // that don't occur in PTI, or that branch to BB will be activated.
738 std::set<ConstantInt*> PTIHandled;
739 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
740 if (PredCases[i].second != BB)
741 PTIHandled.insert(PredCases[i].first);
742 else {
743 // The default destination is BB, we don't need explicit targets.
744 std::swap(PredCases[i], PredCases.back());
745 PredCases.pop_back();
746 --i; --e;
747 }
748
749 // Reconstruct the new switch statement we will be building.
750 if (PredDefault != BBDefault) {
751 PredDefault->removePredecessor(Pred);
752 PredDefault = BBDefault;
753 NewSuccessors.push_back(BBDefault);
754 }
755 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
756 if (!PTIHandled.count(BBCases[i].first) &&
757 BBCases[i].second != BBDefault) {
758 PredCases.push_back(BBCases[i]);
759 NewSuccessors.push_back(BBCases[i].second);
760 }
761
762 } else {
763 // If this is not the default destination from PSI, only the edges
764 // in SI that occur in PSI with a destination of BB will be
765 // activated.
766 std::set<ConstantInt*> PTIHandled;
767 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
768 if (PredCases[i].second == BB) {
769 PTIHandled.insert(PredCases[i].first);
770 std::swap(PredCases[i], PredCases.back());
771 PredCases.pop_back();
772 --i; --e;
773 }
774
775 // Okay, now we know which constants were sent to BB from the
776 // predecessor. Figure out where they will all go now.
777 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
778 if (PTIHandled.count(BBCases[i].first)) {
779 // If this is one we are capable of getting...
780 PredCases.push_back(BBCases[i]);
781 NewSuccessors.push_back(BBCases[i].second);
782 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
783 }
784
785 // If there are any constants vectored to BB that TI doesn't handle,
786 // they must go to the default destination of TI.
787 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
788 E = PTIHandled.end(); I != E; ++I) {
789 PredCases.push_back(std::make_pair(*I, BBDefault));
790 NewSuccessors.push_back(BBDefault);
791 }
792 }
793
794 // Okay, at this point, we know which new successor Pred will get. Make
795 // sure we update the number of entries in the PHI nodes for these
796 // successors.
797 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
798 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
799
800 // Now that the successors are updated, create the new Switch instruction.
Chris Lattnera35dfce2005-01-29 00:38:26 +0000801 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000802 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
803 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner3215bb62005-01-01 16:02:12 +0000804
805 Instruction *DeadCond = 0;
806 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
807 // If PTI is a branch, remember the condition.
808 DeadCond = dyn_cast<Instruction>(BI->getCondition());
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000809 Pred->getInstList().erase(PTI);
810
Chris Lattner3215bb62005-01-01 16:02:12 +0000811 // If the condition is dead now, remove the instruction tree.
812 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
813
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000814 // Okay, last check. If BB is still a successor of PSI, then we must
815 // have an infinite loop case. If so, add an infinitely looping block
816 // to handle the case to preserve the behavior of the code.
817 BasicBlock *InfLoopBlock = 0;
818 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
819 if (NewSI->getSuccessor(i) == BB) {
820 if (InfLoopBlock == 0) {
821 // Insert it at the end of the loop, because it's either code,
822 // or it won't matter if it's hot. :)
823 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
824 new BranchInst(InfLoopBlock, InfLoopBlock);
825 }
826 NewSI->setSuccessor(i, InfLoopBlock);
827 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000828
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000829 Changed = true;
830 }
831 }
832 return Changed;
833}
834
Chris Lattnerd683bdd2005-08-03 17:59:45 +0000835/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +0000836/// BB2, hoist any common code in the two blocks up into the branch block. The
837/// caller of this function guarantees that BI's block dominates BB1 and BB2.
838static bool HoistThenElseCodeToIf(BranchInst *BI) {
839 // This does very trivial matching, with limited scanning, to find identical
840 // instructions in the two blocks. In particular, we don't want to get into
841 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
842 // such, we currently just scan for obviously identical instructions in an
843 // identical order.
844 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
845 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
846
847 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
Chris Lattnerd683bdd2005-08-03 17:59:45 +0000848 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2) ||
849 isa<PHINode>(I1))
Chris Lattner389cfac2004-11-30 00:29:14 +0000850 return false;
851
852 // If we get here, we can hoist at least one instruction.
853 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +0000854
855 do {
856 // If we are hoisting the terminator instruction, don't move one (making a
857 // broken BB), instead clone it, and remove BI.
858 if (isa<TerminatorInst>(I1))
859 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000860
Chris Lattner389cfac2004-11-30 00:29:14 +0000861 // For a normal instruction, we just move one to right before the branch,
862 // then replace all uses of the other with the first. Finally, we remove
863 // the now redundant second instruction.
864 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
865 if (!I2->use_empty())
866 I2->replaceAllUsesWith(I1);
867 BB2->getInstList().erase(I2);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000868
Chris Lattner389cfac2004-11-30 00:29:14 +0000869 I1 = BB1->begin();
870 I2 = BB2->begin();
Chris Lattner389cfac2004-11-30 00:29:14 +0000871 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
872
873 return true;
874
875HoistTerminator:
876 // Okay, it is safe to hoist the terminator.
877 Instruction *NT = I1->clone();
878 BIParent->getInstList().insert(BI, NT);
879 if (NT->getType() != Type::VoidTy) {
880 I1->replaceAllUsesWith(NT);
881 I2->replaceAllUsesWith(NT);
882 NT->setName(I1->getName());
883 }
884
885 // Hoisting one of the terminators from our successor is a great thing.
886 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
887 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
888 // nodes, so we insert select instruction to compute the final result.
889 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
890 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
891 PHINode *PN;
892 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +0000893 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +0000894 Value *BB1V = PN->getIncomingValueForBlock(BB1);
895 Value *BB2V = PN->getIncomingValueForBlock(BB2);
896 if (BB1V != BB2V) {
897 // These values do not agree. Insert a select instruction before NT
898 // that determines the right value.
899 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
900 if (SI == 0)
901 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
902 BB1V->getName()+"."+BB2V->getName(), NT);
903 // Make the PHI node use the select for all incoming values for BB1/BB2
904 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
905 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
906 PN->setIncomingValue(i, SI);
907 }
908 }
909 }
910
911 // Update any PHI nodes in our new successors.
912 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
913 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000914
Chris Lattner389cfac2004-11-30 00:29:14 +0000915 BI->eraseFromParent();
916 return true;
917}
918
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000919/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
920/// across this block.
921static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
922 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +0000923 unsigned Size = 0;
924
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000925 // If this basic block contains anything other than a PHI (which controls the
926 // branch) and branch itself, bail out. FIXME: improve this in the future.
Chris Lattner6c701062005-09-20 01:48:40 +0000927 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
928 if (Size > 10) return false; // Don't clone large BB's.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000929
Chris Lattner6c701062005-09-20 01:48:40 +0000930 // We can only support instructions that are do not define values that are
931 // live outside of the current basic block.
932 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
933 UI != E; ++UI) {
934 Instruction *U = cast<Instruction>(*UI);
935 if (U->getParent() != BB || isa<PHINode>(U)) return false;
936 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000937
938 // Looks ok, continue checking.
939 }
Chris Lattner6c701062005-09-20 01:48:40 +0000940
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000941 return true;
942}
943
Chris Lattner748f9032005-09-19 23:49:37 +0000944/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
945/// that is defined in the same block as the branch and if any PHI entries are
946/// constants, thread edges corresponding to that entry to be branches to their
947/// ultimate destination.
948static bool FoldCondBranchOnPHI(BranchInst *BI) {
949 BasicBlock *BB = BI->getParent();
950 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +0000951 // NOTE: we currently cannot transform this case if the PHI node is used
952 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000953 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
954 return false;
Chris Lattner748f9032005-09-19 23:49:37 +0000955
956 // Degenerate case of a single entry PHI.
957 if (PN->getNumIncomingValues() == 1) {
958 if (PN->getIncomingValue(0) != PN)
959 PN->replaceAllUsesWith(PN->getIncomingValue(0));
960 else
961 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
962 PN->eraseFromParent();
963 return true;
964 }
965
966 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +0000967 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Chris Lattner748f9032005-09-19 23:49:37 +0000968
969 // Okay, this is a simple enough basic block. See if any phi values are
970 // constants.
971 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
972 if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) {
973 // Okay, we now know that all edges from PredBB should be revectored to
974 // branch to RealDest.
975 BasicBlock *PredBB = PN->getIncomingBlock(i);
976 BasicBlock *RealDest = BI->getSuccessor(!CB->getValue());
977
Chris Lattner6c701062005-09-20 01:48:40 +0000978 if (RealDest == BB) continue; // Skip self loops.
Chris Lattner748f9032005-09-19 23:49:37 +0000979
Chris Lattner6c701062005-09-20 01:48:40 +0000980 // The dest block might have PHI nodes, other predecessors and other
981 // difficult cases. Instead of being smart about this, just insert a new
982 // block that jumps to the destination block, effectively splitting
983 // the edge we are about to create.
984 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
985 RealDest->getParent(), RealDest);
986 new BranchInst(RealDest, EdgeBB);
987 PHINode *PN;
988 for (BasicBlock::iterator BBI = RealDest->begin();
989 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
990 Value *V = PN->getIncomingValueForBlock(BB);
991 PN->addIncoming(V, EdgeBB);
992 }
993
994 // BB may have instructions that are being threaded over. Clone these
995 // instructions into EdgeBB. We know that there will be no uses of the
996 // cloned instructions outside of EdgeBB.
997 BasicBlock::iterator InsertPt = EdgeBB->begin();
998 std::map<Value*, Value*> TranslateMap; // Track translated values.
999 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1000 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1001 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1002 } else {
1003 // Clone the instruction.
1004 Instruction *N = BBI->clone();
1005 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1006
1007 // Update operands due to translation.
1008 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1009 std::map<Value*, Value*>::iterator PI =
1010 TranslateMap.find(N->getOperand(i));
1011 if (PI != TranslateMap.end())
1012 N->setOperand(i, PI->second);
1013 }
1014
1015 // Check for trivial simplification.
1016 if (Constant *C = ConstantFoldInstruction(N)) {
Chris Lattner6c701062005-09-20 01:48:40 +00001017 TranslateMap[BBI] = C;
1018 delete N; // Constant folded away, don't need actual inst
1019 } else {
1020 // Insert the new instruction into its new home.
1021 EdgeBB->getInstList().insert(InsertPt, N);
1022 if (!BBI->use_empty())
1023 TranslateMap[BBI] = N;
1024 }
1025 }
1026 }
1027
Chris Lattner748f9032005-09-19 23:49:37 +00001028 // Loop over all of the edges from PredBB to BB, changing them to branch
Chris Lattner6c701062005-09-20 01:48:40 +00001029 // to EdgeBB instead.
Chris Lattner748f9032005-09-19 23:49:37 +00001030 TerminatorInst *PredBBTI = PredBB->getTerminator();
1031 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1032 if (PredBBTI->getSuccessor(i) == BB) {
1033 BB->removePredecessor(PredBB);
Chris Lattner6c701062005-09-20 01:48:40 +00001034 PredBBTI->setSuccessor(i, EdgeBB);
Chris Lattner748f9032005-09-19 23:49:37 +00001035 }
1036
Chris Lattner748f9032005-09-19 23:49:37 +00001037 // Recurse, simplifying any other constants.
1038 return FoldCondBranchOnPHI(BI) | true;
1039 }
1040
1041 return false;
1042}
1043
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001044/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1045/// PHI node, see if we can eliminate it.
1046static bool FoldTwoEntryPHINode(PHINode *PN) {
1047 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1048 // statement", which has a very simple dominance structure. Basically, we
1049 // are trying to find the condition that is being branched on, which
1050 // subsequently causes this merge to happen. We really want control
1051 // dependence information for this check, but simplifycfg can't keep it up
1052 // to date, and this catches most of the cases we care about anyway.
1053 //
1054 BasicBlock *BB = PN->getParent();
1055 BasicBlock *IfTrue, *IfFalse;
1056 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1057 if (!IfCond) return false;
1058
1059 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1060 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1061
1062 // Loop over the PHI's seeing if we can promote them all to select
1063 // instructions. While we are at it, keep track of the instructions
1064 // that need to be moved to the dominating block.
1065 std::set<Instruction*> AggressiveInsts;
1066
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001067 BasicBlock::iterator AfterPHIIt = BB->begin();
1068 while (isa<PHINode>(AfterPHIIt)) {
1069 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1070 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1071 if (PN->getIncomingValue(0) != PN)
1072 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1073 else
1074 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1075 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1076 &AggressiveInsts) ||
1077 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1078 &AggressiveInsts)) {
Chris Lattner3a978bf2005-09-23 07:23:18 +00001079 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001080 }
1081 }
1082
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001083 // If we all PHI nodes are promotable, check to make sure that all
1084 // instructions in the predecessor blocks can be promoted as well. If
1085 // not, we won't be able to get rid of the control flow, so it's not
1086 // worth promoting to select instructions.
1087 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1088 PN = cast<PHINode>(BB->begin());
1089 BasicBlock *Pred = PN->getIncomingBlock(0);
1090 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1091 IfBlock1 = Pred;
1092 DomBlock = *pred_begin(Pred);
1093 for (BasicBlock::iterator I = Pred->begin();
1094 !isa<TerminatorInst>(I); ++I)
1095 if (!AggressiveInsts.count(I)) {
1096 // This is not an aggressive instruction that we can promote.
1097 // Because of this, we won't be able to get rid of the control
1098 // flow, so the xform is not worth it.
1099 return false;
1100 }
1101 }
1102
1103 Pred = PN->getIncomingBlock(1);
1104 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1105 IfBlock2 = Pred;
1106 DomBlock = *pred_begin(Pred);
1107 for (BasicBlock::iterator I = Pred->begin();
1108 !isa<TerminatorInst>(I); ++I)
1109 if (!AggressiveInsts.count(I)) {
1110 // This is not an aggressive instruction that we can promote.
1111 // Because of this, we won't be able to get rid of the control
1112 // flow, so the xform is not worth it.
1113 return false;
1114 }
1115 }
1116
1117 // If we can still promote the PHI nodes after this gauntlet of tests,
1118 // do all of the PHI's now.
1119
1120 // Move all 'aggressive' instructions, which are defined in the
1121 // conditional parts of the if's up to the dominating block.
1122 if (IfBlock1) {
1123 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1124 IfBlock1->getInstList(),
1125 IfBlock1->begin(),
1126 IfBlock1->getTerminator());
1127 }
1128 if (IfBlock2) {
1129 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1130 IfBlock2->getInstList(),
1131 IfBlock2->begin(),
1132 IfBlock2->getTerminator());
1133 }
1134
1135 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1136 // Change the PHI node into a select instruction.
1137 Value *TrueVal =
1138 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1139 Value *FalseVal =
1140 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1141
1142 std::string Name = PN->getName(); PN->setName("");
1143 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1144 Name, AfterPHIIt));
1145 BB->getInstList().erase(PN);
1146 }
1147 return true;
1148}
Chris Lattner748f9032005-09-19 23:49:37 +00001149
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001150namespace {
1151 /// ConstantIntOrdering - This class implements a stable ordering of constant
1152 /// integers that does not depend on their address. This is important for
1153 /// applications that sort ConstantInt's to ensure uniqueness.
1154 struct ConstantIntOrdering {
1155 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1156 return LHS->getRawValue() < RHS->getRawValue();
1157 }
1158 };
1159}
1160
Chris Lattner466a0492002-05-21 20:50:24 +00001161// SimplifyCFG - This function is used to do simplification of a CFG. For
1162// example, it adjusts branches to branches to eliminate the extra hop, it
1163// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +00001164// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +00001165//
1166// WARNING: The entry node of a function may not be simplified.
1167//
Chris Lattnerdf3c3422004-01-09 06:12:26 +00001168bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00001169 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00001170 Function *M = BB->getParent();
1171
1172 assert(BB && BB->getParent() && "Block not embedded in function!");
1173 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +00001174 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +00001175
Chris Lattner466a0492002-05-21 20:50:24 +00001176 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnera2ab4892004-02-24 07:23:58 +00001177 if (pred_begin(BB) == pred_end(BB) ||
1178 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner32c518e2004-07-15 02:06:12 +00001179 DEBUG(std::cerr << "Removing BB: \n" << *BB);
Chris Lattner466a0492002-05-21 20:50:24 +00001180
1181 // Loop through all of our successors and make sure they know that one
1182 // of their predecessors is going away.
Chris Lattner95f16a32005-04-12 18:51:33 +00001183 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1184 SI->removePredecessor(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00001185
1186 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +00001187 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +00001188 // If this instruction is used, replace uses with an arbitrary
Chris Lattnereee90f72005-08-02 23:29:23 +00001189 // value. Because control flow can't get here, we don't care
Misha Brukmanb1c93172005-04-21 23:48:37 +00001190 // what we replace the value with. Note that since this block is
Chris Lattner466a0492002-05-21 20:50:24 +00001191 // unreachable, and all values contained within it must dominate their
1192 // uses, that all uses will eventually be removed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001193 if (!I.use_empty())
Chris Lattnereee90f72005-08-02 23:29:23 +00001194 // Make all users of this instruction use undef instead
1195 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001196
Chris Lattner466a0492002-05-21 20:50:24 +00001197 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +00001198 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +00001199 }
Chris Lattnerfda72b12002-06-25 16:12:52 +00001200 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00001201 return true;
1202 }
1203
Chris Lattner031340a2003-08-17 19:41:53 +00001204 // Check to see if we can constant propagate this terminator instruction
1205 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +00001206 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +00001207
Chris Lattnere42732e2004-02-16 06:35:48 +00001208 // If this is a returning block with only PHI nodes in it, fold the return
1209 // instruction into any unconditional branch predecessors.
Chris Lattner9f0db322004-04-02 18:13:43 +00001210 //
1211 // If any predecessor is a conditional branch that just selects among
1212 // different return values, fold the replace the branch/return with a select
1213 // and return.
Chris Lattnere42732e2004-02-16 06:35:48 +00001214 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1215 BasicBlock::iterator BBI = BB->getTerminator();
1216 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner9f0db322004-04-02 18:13:43 +00001217 // Find predecessors that end with branches.
Chris Lattnere42732e2004-02-16 06:35:48 +00001218 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner9f0db322004-04-02 18:13:43 +00001219 std::vector<BranchInst*> CondBranchPreds;
Chris Lattnere42732e2004-02-16 06:35:48 +00001220 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1221 TerminatorInst *PTI = (*PI)->getTerminator();
1222 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1223 if (BI->isUnconditional())
1224 UncondBranchPreds.push_back(*PI);
Chris Lattner9f0db322004-04-02 18:13:43 +00001225 else
1226 CondBranchPreds.push_back(BI);
Chris Lattnere42732e2004-02-16 06:35:48 +00001227 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001228
Chris Lattnere42732e2004-02-16 06:35:48 +00001229 // If we found some, do the transformation!
1230 if (!UncondBranchPreds.empty()) {
1231 while (!UncondBranchPreds.empty()) {
1232 BasicBlock *Pred = UncondBranchPreds.back();
Chris Lattnerc59a3712005-09-23 18:47:20 +00001233 DEBUG(std::cerr << "FOLDING: " << *BB
1234 << "INTO UNCOND BRANCH PRED: " << *Pred);
Chris Lattnere42732e2004-02-16 06:35:48 +00001235 UncondBranchPreds.pop_back();
1236 Instruction *UncondBranch = Pred->getTerminator();
1237 // Clone the return and add it to the end of the predecessor.
1238 Instruction *NewRet = RI->clone();
1239 Pred->getInstList().push_back(NewRet);
1240
1241 // If the return instruction returns a value, and if the value was a
1242 // PHI node in "BB", propagate the right value into the return.
1243 if (NewRet->getNumOperands() == 1)
1244 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1245 if (PN->getParent() == BB)
1246 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1247 // Update any PHI nodes in the returning block to realize that we no
1248 // longer branch to them.
1249 BB->removePredecessor(Pred);
1250 Pred->getInstList().erase(UncondBranch);
1251 }
1252
1253 // If we eliminated all predecessors of the block, delete the block now.
1254 if (pred_begin(BB) == pred_end(BB))
1255 // We know there are no successors, so just nuke the block.
1256 M->getBasicBlockList().erase(BB);
1257
Chris Lattnere42732e2004-02-16 06:35:48 +00001258 return true;
1259 }
Chris Lattner9f0db322004-04-02 18:13:43 +00001260
1261 // Check out all of the conditional branches going to this return
1262 // instruction. If any of them just select between returns, change the
1263 // branch itself into a select/return pair.
1264 while (!CondBranchPreds.empty()) {
1265 BranchInst *BI = CondBranchPreds.back();
1266 CondBranchPreds.pop_back();
1267 BasicBlock *TrueSucc = BI->getSuccessor(0);
1268 BasicBlock *FalseSucc = BI->getSuccessor(1);
1269 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1270
1271 // Check to see if the non-BB successor is also a return block.
1272 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1273 // Check to see if there are only PHI instructions in this block.
1274 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1275 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1276 // Okay, we found a branch that is going to two return nodes. If
1277 // there is no return value for this function, just change the
1278 // branch into a return.
1279 if (RI->getNumOperands() == 0) {
1280 TrueSucc->removePredecessor(BI->getParent());
1281 FalseSucc->removePredecessor(BI->getParent());
1282 new ReturnInst(0, BI);
1283 BI->getParent()->getInstList().erase(BI);
1284 return true;
1285 }
1286
1287 // Otherwise, figure out what the true and false return values are
1288 // so we can insert a new select instruction.
1289 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1290 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1291
1292 // Unwrap any PHI nodes in the return blocks.
1293 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1294 if (TVPN->getParent() == TrueSucc)
1295 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1296 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1297 if (FVPN->getParent() == FalseSucc)
1298 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1299
Chris Lattnereed034b2004-04-02 18:15:10 +00001300 TrueSucc->removePredecessor(BI->getParent());
1301 FalseSucc->removePredecessor(BI->getParent());
1302
Chris Lattner9f0db322004-04-02 18:13:43 +00001303 // Insert a new select instruction.
Chris Lattner879ce782004-09-29 05:43:32 +00001304 Value *NewRetVal;
1305 Value *BrCond = BI->getCondition();
1306 if (TrueValue != FalseValue)
1307 NewRetVal = new SelectInst(BrCond, TrueValue,
1308 FalseValue, "retval", BI);
1309 else
1310 NewRetVal = TrueValue;
Chris Lattner4c3b2b52005-10-03 23:43:43 +00001311
1312 DEBUG(std::cerr << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1313 << "\n " << *BI << "Select = " << *NewRetVal
1314 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Chris Lattner879ce782004-09-29 05:43:32 +00001315
Chris Lattner9f0db322004-04-02 18:13:43 +00001316 new ReturnInst(NewRetVal, BI);
Chris Lattner4c3b2b52005-10-03 23:43:43 +00001317 BI->eraseFromParent();
1318 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1319 if (isInstructionTriviallyDead(BrCondI))
1320 BrCondI->eraseFromParent();
Chris Lattner9f0db322004-04-02 18:13:43 +00001321 return true;
1322 }
1323 }
1324 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001325 }
Chris Lattner3cd98f02004-02-24 05:54:22 +00001326 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
1327 // Check to see if the first instruction in this block is just an unwind.
1328 // If so, replace any invoke instructions which use this as an exception
Chris Lattner5823ac12004-07-20 01:17:38 +00001329 // destination with call instructions, and any unconditional branch
1330 // predecessor with an unwind.
Chris Lattner3cd98f02004-02-24 05:54:22 +00001331 //
1332 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1333 while (!Preds.empty()) {
1334 BasicBlock *Pred = Preds.back();
Chris Lattner5823ac12004-07-20 01:17:38 +00001335 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1336 if (BI->isUnconditional()) {
1337 Pred->getInstList().pop_back(); // nuke uncond branch
1338 new UnwindInst(Pred); // Use unwind.
1339 Changed = true;
1340 }
1341 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattner3cd98f02004-02-24 05:54:22 +00001342 if (II->getUnwindDest() == BB) {
1343 // Insert a new branch instruction before the invoke, because this
1344 // is now a fall through...
1345 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1346 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanb1c93172005-04-21 23:48:37 +00001347
Chris Lattner3cd98f02004-02-24 05:54:22 +00001348 // Insert the call now...
1349 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1350 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1351 II->getName(), BI);
Chris Lattnerbcefcf82005-05-14 12:21:56 +00001352 CI->setCallingConv(II->getCallingConv());
Chris Lattner3cd98f02004-02-24 05:54:22 +00001353 // If the invoke produced a value, the Call now does instead
1354 II->replaceAllUsesWith(CI);
1355 delete II;
1356 Changed = true;
1357 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001358
Chris Lattner3cd98f02004-02-24 05:54:22 +00001359 Preds.pop_back();
1360 }
Chris Lattner90ea78e2004-02-24 16:09:21 +00001361
1362 // If this block is now dead, remove it.
1363 if (pred_begin(BB) == pred_end(BB)) {
1364 // We know there are no successors, so just nuke the block.
1365 M->getBasicBlockList().erase(BB);
1366 return true;
1367 }
1368
Chris Lattner1cca9592005-02-24 06:17:52 +00001369 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1370 if (isValueEqualityComparison(SI)) {
1371 // If we only have one predecessor, and if it is a branch on this value,
1372 // see if that predecessor totally determines the outcome of this switch.
1373 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1374 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1375 return SimplifyCFG(BB) || 1;
1376
1377 // If the block only contains the switch, see if we can fold the block
1378 // away into any preds.
1379 if (SI == &BB->front())
1380 if (FoldValueComparisonIntoPredecessors(SI))
1381 return SimplifyCFG(BB) || 1;
1382 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001383 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner733d6702005-08-03 00:11:16 +00001384 if (BI->isUnconditional()) {
1385 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1386 while (isa<PHINode>(*BBI)) ++BBI;
1387
1388 BasicBlock *Succ = BI->getSuccessor(0);
1389 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1390 Succ != BB) // Don't hurt infinite loops!
1391 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1392 return 1;
1393
1394 } else { // Conditional branch
Chris Lattner2e93c422004-05-01 23:35:43 +00001395 if (Value *CompVal = isValueEqualityComparison(BI)) {
Chris Lattner1cca9592005-02-24 06:17:52 +00001396 // If we only have one predecessor, and if it is a branch on this value,
1397 // see if that predecessor totally determines the outcome of this
1398 // switch.
1399 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1400 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1401 return SimplifyCFG(BB) || 1;
1402
Chris Lattner2e93c422004-05-01 23:35:43 +00001403 // This block must be empty, except for the setcond inst, if it exists.
1404 BasicBlock::iterator I = BB->begin();
1405 if (&*I == BI ||
1406 (&*I == cast<Instruction>(BI->getCondition()) &&
1407 &*++I == BI))
1408 if (FoldValueComparisonIntoPredecessors(BI))
1409 return SimplifyCFG(BB) | true;
1410 }
Chris Lattner748f9032005-09-19 23:49:37 +00001411
1412 // If this is a branch on a phi node in the current block, thread control
1413 // through this block if any PHI node entries are constants.
1414 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1415 if (PN->getParent() == BI->getParent())
1416 if (FoldCondBranchOnPHI(BI))
1417 return SimplifyCFG(BB) | true;
Chris Lattner2e93c422004-05-01 23:35:43 +00001418
1419 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1420 // branches to us and one of our successors, fold the setcc into the
1421 // predecessor and use logical operations to pick the right destination.
Chris Lattner51a6dbc2004-05-02 05:02:03 +00001422 BasicBlock *TrueDest = BI->getSuccessor(0);
1423 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbe6f0682004-05-02 05:19:36 +00001424 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattner2e93c422004-05-01 23:35:43 +00001425 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner51a6dbc2004-05-02 05:02:03 +00001426 Cond->getNext() == BI && Cond->hasOneUse() &&
1427 TrueDest != BB && FalseDest != BB)
Chris Lattner2e93c422004-05-01 23:35:43 +00001428 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1429 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner1e94ed62004-05-02 01:00:44 +00001430 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001431 BasicBlock *PredBlock = *PI;
Chris Lattner2e93c422004-05-01 23:35:43 +00001432 if (PBI->getSuccessor(0) == FalseDest ||
1433 PBI->getSuccessor(1) == TrueDest) {
1434 // Invert the predecessors condition test (xor it with true),
1435 // which allows us to write this code once.
1436 Value *NewCond =
1437 BinaryOperator::createNot(PBI->getCondition(),
1438 PBI->getCondition()->getName()+".not", PBI);
1439 PBI->setCondition(NewCond);
1440 BasicBlock *OldTrue = PBI->getSuccessor(0);
1441 BasicBlock *OldFalse = PBI->getSuccessor(1);
1442 PBI->setSuccessor(0, OldFalse);
1443 PBI->setSuccessor(1, OldTrue);
1444 }
1445
Chris Lattnerd9566512006-02-18 00:33:17 +00001446 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1447 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001448 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattner2e93c422004-05-01 23:35:43 +00001449 // two conditions together.
1450 Instruction *New = Cond->clone();
1451 New->setName(Cond->getName());
1452 Cond->setName(Cond->getName()+".old");
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001453 PredBlock->getInstList().insert(PBI, New);
Chris Lattner2e93c422004-05-01 23:35:43 +00001454 Instruction::BinaryOps Opcode =
1455 PBI->getSuccessor(0) == TrueDest ?
1456 Instruction::Or : Instruction::And;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001457 Value *NewCond =
Chris Lattner2e93c422004-05-01 23:35:43 +00001458 BinaryOperator::create(Opcode, PBI->getCondition(),
1459 New, "bothcond", PBI);
1460 PBI->setCondition(NewCond);
1461 if (PBI->getSuccessor(0) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001462 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +00001463 PBI->setSuccessor(0, TrueDest);
1464 }
1465 if (PBI->getSuccessor(1) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +00001466 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +00001467 PBI->setSuccessor(1, FalseDest);
1468 }
1469 return SimplifyCFG(BB) | 1;
1470 }
1471 }
Chris Lattner2e93c422004-05-01 23:35:43 +00001472
Chris Lattnerc59a3712005-09-23 18:47:20 +00001473 // Scan predessor blocks for conditional branchs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001474 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1475 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnerc59a3712005-09-23 18:47:20 +00001476 if (PBI != BI && PBI->isConditional()) {
1477
1478 // If this block ends with a branch instruction, and if there is a
1479 // predecessor that ends on a branch of the same condition, make this
1480 // conditional branch redundant.
1481 if (PBI->getCondition() == BI->getCondition() &&
1482 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1483 // Okay, the outcome of this conditional branch is statically
1484 // knowable. If this block had a single pred, handle specially.
1485 if (BB->getSinglePredecessor()) {
1486 // Turn this into a branch on constant.
1487 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1488 BI->setCondition(ConstantBool::get(CondIsTrue));
1489 return SimplifyCFG(BB); // Nuke the branch on constant.
1490 }
1491
1492 // Otherwise, if there are multiple predecessors, insert a PHI that
1493 // merges in the constant and simplify the block result.
1494 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1495 PHINode *NewPN = new PHINode(Type::BoolTy,
1496 BI->getCondition()->getName()+".pr",
1497 BB->begin());
1498 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1499 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1500 PBI != BI && PBI->isConditional() &&
1501 PBI->getCondition() == BI->getCondition() &&
1502 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1503 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1504 NewPN->addIncoming(ConstantBool::get(CondIsTrue), *PI);
1505 } else {
1506 NewPN->addIncoming(BI->getCondition(), *PI);
1507 }
1508
1509 BI->setCondition(NewPN);
1510 // This will thread the branch.
1511 return SimplifyCFG(BB) | true;
1512 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001513 }
1514
Chris Lattnerc59a3712005-09-23 18:47:20 +00001515 // If this is a conditional branch in an empty block, and if any
1516 // predecessors is a conditional branch to one of our destinations,
1517 // fold the conditions into logical ops and one cond br.
1518 if (&BB->front() == BI) {
1519 int PBIOp, BIOp;
1520 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1521 PBIOp = BIOp = 0;
1522 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1523 PBIOp = 0; BIOp = 1;
1524 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1525 PBIOp = 1; BIOp = 0;
1526 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1527 PBIOp = BIOp = 1;
1528 } else {
1529 PBIOp = BIOp = -1;
1530 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001531
Chris Lattnerd9566512006-02-18 00:33:17 +00001532 // Check to make sure that the other destination of this branch
1533 // isn't BB itself. If so, this is an infinite loop that will
1534 // keep getting unwound.
1535 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1536 PBIOp = BIOp = -1;
Chris Lattnerb5c9d7a2006-06-12 20:18:01 +00001537
Chris Lattnerc59a3712005-09-23 18:47:20 +00001538 // Finally, if everything is ok, fold the branches to logical ops.
1539 if (PBIOp != -1) {
1540 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1541 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1542
Chris Lattnerb5c9d7a2006-06-12 20:18:01 +00001543 // If OtherDest *is* BB, then this is a basic block with just
1544 // a conditional branch in it, where one edge (OtherDesg) goes
1545 // back to the block. We know that the program doesn't get
1546 // stuck in the infinite loop, so the condition must be such
1547 // that OtherDest isn't branched through. Forward to CommonDest,
1548 // and avoid an infinite loop at optimizer time.
1549 if (OtherDest == BB)
1550 OtherDest = CommonDest;
1551
Chris Lattnerc59a3712005-09-23 18:47:20 +00001552 DEBUG(std::cerr << "FOLDING BRs:" << *PBI->getParent()
1553 << "AND: " << *BI->getParent());
1554
1555 // BI may have other predecessors. Because of this, we leave
1556 // it alone, but modify PBI.
1557
1558 // Make sure we get to CommonDest on True&True directions.
1559 Value *PBICond = PBI->getCondition();
1560 if (PBIOp)
1561 PBICond = BinaryOperator::createNot(PBICond,
1562 PBICond->getName()+".not",
1563 PBI);
1564 Value *BICond = BI->getCondition();
1565 if (BIOp)
1566 BICond = BinaryOperator::createNot(BICond,
1567 BICond->getName()+".not",
1568 PBI);
1569 // Merge the conditions.
1570 Value *Cond =
1571 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1572
1573 // Modify PBI to branch on the new condition to the new dests.
1574 PBI->setCondition(Cond);
1575 PBI->setSuccessor(0, CommonDest);
1576 PBI->setSuccessor(1, OtherDest);
1577
1578 // OtherDest may have phi nodes. If so, add an entry from PBI's
1579 // block that are identical to the entries for BI's block.
1580 PHINode *PN;
1581 for (BasicBlock::iterator II = OtherDest->begin();
1582 (PN = dyn_cast<PHINode>(II)); ++II) {
1583 Value *V = PN->getIncomingValueForBlock(BB);
1584 PN->addIncoming(V, PBI->getParent());
1585 }
1586
1587 // We know that the CommonDest already had an edge from PBI to
1588 // it. If it has PHIs though, the PHIs may have different
1589 // entries for BB and PBI's BB. If so, insert a select to make
1590 // them agree.
1591 for (BasicBlock::iterator II = CommonDest->begin();
1592 (PN = dyn_cast<PHINode>(II)); ++II) {
1593 Value * BIV = PN->getIncomingValueForBlock(BB);
1594 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1595 Value *PBIV = PN->getIncomingValue(PBBIdx);
1596 if (BIV != PBIV) {
1597 // Insert a select in PBI to pick the right value.
1598 Value *NV = new SelectInst(PBICond, PBIV, BIV,
1599 PBIV->getName()+".mux", PBI);
1600 PN->setIncomingValue(PBBIdx, NV);
1601 }
1602 }
1603
1604 DEBUG(std::cerr << "INTO: " << *PBI->getParent());
1605
1606 // This basic block is probably dead. We know it has at least
1607 // one fewer predecessor.
1608 return SimplifyCFG(BB) | true;
1609 }
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001610 }
Chris Lattner88da6f72004-05-01 22:36:37 +00001611 }
Chris Lattnera2ab4892004-02-24 07:23:58 +00001612 }
Chris Lattner5edb2f32004-10-18 04:07:22 +00001613 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1614 // If there are any instructions immediately before the unreachable that can
1615 // be removed, do so.
1616 Instruction *Unreachable = BB->getTerminator();
1617 while (Unreachable != BB->begin()) {
1618 BasicBlock::iterator BBI = Unreachable;
1619 --BBI;
1620 if (isa<CallInst>(BBI)) break;
1621 // Delete this instruction
1622 BB->getInstList().erase(BBI);
1623 Changed = true;
1624 }
1625
1626 // If the unreachable instruction is the first in the block, take a gander
1627 // at all of the predecessors of this instruction, and simplify them.
1628 if (&BB->front() == Unreachable) {
1629 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1630 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1631 TerminatorInst *TI = Preds[i]->getTerminator();
1632
1633 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1634 if (BI->isUnconditional()) {
1635 if (BI->getSuccessor(0) == BB) {
1636 new UnreachableInst(TI);
1637 TI->eraseFromParent();
1638 Changed = true;
1639 }
1640 } else {
1641 if (BI->getSuccessor(0) == BB) {
1642 new BranchInst(BI->getSuccessor(1), BI);
1643 BI->eraseFromParent();
1644 } else if (BI->getSuccessor(1) == BB) {
1645 new BranchInst(BI->getSuccessor(0), BI);
1646 BI->eraseFromParent();
1647 Changed = true;
1648 }
1649 }
1650 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1651 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1652 if (SI->getSuccessor(i) == BB) {
Chris Lattner19f9f322005-05-20 22:19:54 +00001653 BB->removePredecessor(SI->getParent());
Chris Lattner5edb2f32004-10-18 04:07:22 +00001654 SI->removeCase(i);
1655 --i; --e;
1656 Changed = true;
1657 }
1658 // If the default value is unreachable, figure out the most popular
1659 // destination and make it the default.
1660 if (SI->getSuccessor(0) == BB) {
1661 std::map<BasicBlock*, unsigned> Popularity;
1662 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1663 Popularity[SI->getSuccessor(i)]++;
1664
1665 // Find the most popular block.
1666 unsigned MaxPop = 0;
1667 BasicBlock *MaxBlock = 0;
1668 for (std::map<BasicBlock*, unsigned>::iterator
1669 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1670 if (I->second > MaxPop) {
1671 MaxPop = I->second;
1672 MaxBlock = I->first;
1673 }
1674 }
1675 if (MaxBlock) {
1676 // Make this the new default, allowing us to delete any explicit
1677 // edges to it.
1678 SI->setSuccessor(0, MaxBlock);
1679 Changed = true;
1680
Chris Lattner19f9f322005-05-20 22:19:54 +00001681 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1682 // it.
1683 if (isa<PHINode>(MaxBlock->begin()))
1684 for (unsigned i = 0; i != MaxPop-1; ++i)
1685 MaxBlock->removePredecessor(SI->getParent());
1686
Chris Lattner5edb2f32004-10-18 04:07:22 +00001687 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1688 if (SI->getSuccessor(i) == MaxBlock) {
1689 SI->removeCase(i);
1690 --i; --e;
1691 }
1692 }
1693 }
1694 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1695 if (II->getUnwindDest() == BB) {
1696 // Convert the invoke to a call instruction. This would be a good
1697 // place to note that the call does not throw though.
1698 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1699 II->removeFromParent(); // Take out of symbol table
Misha Brukmanb1c93172005-04-21 23:48:37 +00001700
Chris Lattner5edb2f32004-10-18 04:07:22 +00001701 // Insert the call now...
1702 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1703 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1704 II->getName(), BI);
Chris Lattnerbcefcf82005-05-14 12:21:56 +00001705 CI->setCallingConv(II->getCallingConv());
Chris Lattner5edb2f32004-10-18 04:07:22 +00001706 // If the invoke produced a value, the Call does now instead.
1707 II->replaceAllUsesWith(CI);
1708 delete II;
1709 Changed = true;
1710 }
1711 }
1712 }
1713
1714 // If this block is now dead, remove it.
1715 if (pred_begin(BB) == pred_end(BB)) {
1716 // We know there are no successors, so just nuke the block.
1717 M->getBasicBlockList().erase(BB);
1718 return true;
1719 }
1720 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001721 }
1722
Chris Lattner466a0492002-05-21 20:50:24 +00001723 // Merge basic blocks into their predecessor if there is only one distinct
1724 // pred, and if there is only one distinct successor of the predecessor, and
1725 // if there are no PHI nodes.
1726 //
Chris Lattner838b8452004-02-11 01:17:07 +00001727 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1728 BasicBlock *OnlyPred = *PI++;
1729 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1730 if (*PI != OnlyPred) {
1731 OnlyPred = 0; // There are multiple different predecessors...
1732 break;
1733 }
Chris Lattner88da6f72004-05-01 22:36:37 +00001734
Chris Lattner838b8452004-02-11 01:17:07 +00001735 BasicBlock *OnlySucc = 0;
1736 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1737 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1738 // Check to see if there is only one distinct successor...
1739 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1740 OnlySucc = BB;
1741 for (; SI != SE; ++SI)
1742 if (*SI != OnlySucc) {
1743 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner466a0492002-05-21 20:50:24 +00001744 break;
1745 }
Chris Lattner838b8452004-02-11 01:17:07 +00001746 }
1747
1748 if (OnlySucc) {
Chris Lattner32c518e2004-07-15 02:06:12 +00001749 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
Chris Lattner838b8452004-02-11 01:17:07 +00001750 TerminatorInst *Term = OnlyPred->getTerminator();
1751
1752 // Resolve any PHI nodes at the start of the block. They are all
1753 // guaranteed to have exactly one entry if they exist, unless there are
1754 // multiple duplicate (but guaranteed to be equal) entries for the
1755 // incoming edges. This occurs when there are multiple edges from
1756 // OnlyPred to OnlySucc.
1757 //
1758 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1759 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1760 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner466a0492002-05-21 20:50:24 +00001761 }
1762
Chris Lattner838b8452004-02-11 01:17:07 +00001763 // Delete the unconditional branch from the predecessor...
1764 OnlyPred->getInstList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001765
Chris Lattner838b8452004-02-11 01:17:07 +00001766 // Move all definitions in the successor to the predecessor...
1767 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001768
Chris Lattner838b8452004-02-11 01:17:07 +00001769 // Make all PHI nodes that referred to BB now refer to Pred as their
1770 // source...
1771 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001772
Chris Lattner838b8452004-02-11 01:17:07 +00001773 std::string OldName = BB->getName();
Chris Lattnerfda72b12002-06-25 16:12:52 +00001774
Misha Brukmanb1c93172005-04-21 23:48:37 +00001775 // Erase basic block from the function...
Chris Lattner838b8452004-02-11 01:17:07 +00001776 M->getBasicBlockList().erase(BB);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001777
Chris Lattner838b8452004-02-11 01:17:07 +00001778 // Inherit predecessors name if it exists...
1779 if (!OldName.empty() && !OnlyPred->hasName())
1780 OnlyPred->setName(OldName);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001781
Chris Lattner838b8452004-02-11 01:17:07 +00001782 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00001783 }
Chris Lattner18d1f192004-02-11 03:36:04 +00001784
Chris Lattner389cfac2004-11-30 00:29:14 +00001785 // Otherwise, if this block only has a single predecessor, and if that block
1786 // is a conditional branch, see if we can hoist any code from this block up
1787 // into our predecessor.
1788 if (OnlyPred)
Chris Lattner4fc998d2004-12-10 17:42:31 +00001789 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1790 if (BI->isConditional()) {
1791 // Get the other block.
1792 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1793 PI = pred_begin(OtherBB);
1794 ++PI;
1795 if (PI == pred_end(OtherBB)) {
1796 // We have a conditional branch to two blocks that are only reachable
1797 // from the condbr. We know that the condbr dominates the two blocks,
1798 // so see if there is any identical code in the "then" and "else"
1799 // blocks. If so, we can hoist it up to the branching block.
1800 Changed |= HoistThenElseCodeToIf(BI);
1801 }
Chris Lattner389cfac2004-11-30 00:29:14 +00001802 }
Chris Lattner389cfac2004-11-30 00:29:14 +00001803
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001804 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1805 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1806 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1807 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1808 Instruction *Cond = cast<Instruction>(BI->getCondition());
1809 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1810 // 'setne's and'ed together, collect them.
1811 Value *CompVal = 0;
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001812 std::vector<ConstantInt*> Values;
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001813 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1814 if (CompVal && CompVal->getType()->isInteger()) {
1815 // There might be duplicate constants in the list, which the switch
1816 // instruction can't handle, remove them now.
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001817 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001818 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001819
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001820 // Figure out which block is which destination.
1821 BasicBlock *DefaultBB = BI->getSuccessor(1);
1822 BasicBlock *EdgeBB = BI->getSuccessor(0);
1823 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001824
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001825 // Create the new switch instruction now.
Chris Lattnera35dfce2005-01-29 00:38:26 +00001826 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001827
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001828 // Add all of the 'cases' to the switch instruction.
1829 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1830 New->addCase(Values[i], EdgeBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001831
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001832 // We added edges from PI to the EdgeBB. As such, if there were any
1833 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1834 // the number of edges added.
1835 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer66149462004-09-15 17:06:42 +00001836 isa<PHINode>(BBI); ++BBI) {
1837 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001838 Value *InVal = PN->getIncomingValueForBlock(*PI);
1839 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1840 PN->addIncoming(InVal, *PI);
1841 }
1842
1843 // Erase the old branch instruction.
1844 (*PI)->getInstList().erase(BI);
1845
1846 // Erase the potentially condition tree that was used to computed the
1847 // branch condition.
1848 ErasePossiblyDeadInstructionTree(Cond);
1849 return true;
1850 }
1851 }
1852
Chris Lattner18d1f192004-02-11 03:36:04 +00001853 // If there is a trivial two-entry PHI node in this basic block, and we can
1854 // eliminate it, do so now.
1855 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001856 if (PN->getNumIncomingValues() == 2)
1857 Changed |= FoldTwoEntryPHINode(PN);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001858
Chris Lattner031340a2003-08-17 19:41:53 +00001859 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00001860}