blob: 55939ae53d9996075f7ef554086a60343a88f4be [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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 Lattner466a0492002-05-21 20:50:24 +000021#include <algorithm>
22#include <functional>
Chris Lattnera2ab4892004-02-24 07:23:58 +000023#include <set>
Chris Lattner5edb2f32004-10-18 04:07:22 +000024#include <map>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000026
Chris Lattner6f4b45a2004-02-24 05:38:11 +000027// PropagatePredecessorsForPHIs - This gets "Succ" ready to have the
28// predecessors from "BB". This is a little tricky because "Succ" has PHI
29// nodes, which need to have extra slots added to them to hold the merge edges
30// from BB's predecessors, and BB itself might have had PHI nodes in it. This
31// function returns true (failure) if the Succ BB already has a predecessor that
32// is a predecessor of BB and incoming PHI arguments would not be discernible.
Chris Lattner466a0492002-05-21 20:50:24 +000033//
34// Assumption: Succ is the single successor for BB.
35//
Misha Brukman632df282002-10-29 23:06:16 +000036static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner466a0492002-05-21 20:50:24 +000037 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner5325c5f2002-09-24 00:09:26 +000038
39 if (!isa<PHINode>(Succ->front()))
40 return false; // We can make the transformation, no problem.
Chris Lattner466a0492002-05-21 20:50:24 +000041
42 // If there is more than one predecessor, and there are PHI nodes in
43 // the successor, then we need to add incoming edges for the PHI nodes
44 //
45 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
46
47 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattner31116ba2003-03-05 21:01:52 +000048 // Succ. If so, we cannot do the transformation if there are any PHI nodes
49 // with incompatible values coming in from the two edges!
Chris Lattner466a0492002-05-21 20:50:24 +000050 //
Chris Lattner31116ba2003-03-05 21:01:52 +000051 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000052 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
Chris Lattner31116ba2003-03-05 21:01:52 +000053 // Loop over all of the PHI nodes checking to see if there are
54 // incompatible values coming in.
Reid Spencer66149462004-09-15 17:06:42 +000055 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
56 PHINode *PN = cast<PHINode>(I);
Chris Lattner31116ba2003-03-05 21:01:52 +000057 // Loop up the entries in the PHI node for BB and for *PI if the values
58 // coming in are non-equal, we cannot merge these two blocks (instead we
59 // should insert a conditional move or something, then merge the
60 // blocks).
61 int Idx1 = PN->getBasicBlockIndex(BB);
62 int Idx2 = PN->getBasicBlockIndex(*PI);
63 assert(Idx1 != -1 && Idx2 != -1 &&
64 "Didn't have entries for my predecessors??");
65 if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
66 return true; // Values are not equal...
67 }
68 }
Chris Lattner466a0492002-05-21 20:50:24 +000069
Chris Lattner9734fd02004-06-20 01:13:18 +000070 // Loop over all of the PHI nodes in the successor BB.
Reid Spencer66149462004-09-15 17:06:42 +000071 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
72 PHINode *PN = cast<PHINode>(I);
Chris Lattnera704ac82002-10-08 21:36:33 +000073 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner466a0492002-05-21 20:50:24 +000074 assert(OldVal && "No entry in PHI for Pred BB!");
75
Chris Lattner9734fd02004-06-20 01:13:18 +000076 // If this incoming value is one of the PHI nodes in BB, the new entries in
77 // the PHI node are the entries from the old PHI.
Chris Lattnere54d2142003-03-05 21:36:33 +000078 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
79 PHINode *OldValPN = cast<PHINode>(OldVal);
Chris Lattner9734fd02004-06-20 01:13:18 +000080 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
81 PN->addIncoming(OldValPN->getIncomingValue(i),
82 OldValPN->getIncomingBlock(i));
Chris Lattnere54d2142003-03-05 21:36:33 +000083 } else {
84 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
85 End = BBPreds.end(); PredI != End; ++PredI) {
86 // Add an incoming value for each of the new incoming values...
87 PN->addIncoming(OldVal, *PredI);
88 }
Chris Lattner466a0492002-05-21 20:50:24 +000089 }
90 }
91 return false;
92}
93
Chris Lattner18d1f192004-02-11 03:36:04 +000094/// GetIfCondition - Given a basic block (BB) with two predecessors (and
95/// presumably PHI nodes in it), check to see if the merge at this block is due
96/// to an "if condition". If so, return the boolean condition that determines
97/// which entry into BB will be taken. Also, return by references the block
98/// that will be entered from if the condition is true, and the block that will
99/// be entered if the condition is false.
100///
101///
102static Value *GetIfCondition(BasicBlock *BB,
103 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
104 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
105 "Function can only handle blocks with 2 predecessors!");
106 BasicBlock *Pred1 = *pred_begin(BB);
107 BasicBlock *Pred2 = *++pred_begin(BB);
108
109 // We can only handle branches. Other control flow will be lowered to
110 // branches if possible anyway.
111 if (!isa<BranchInst>(Pred1->getTerminator()) ||
112 !isa<BranchInst>(Pred2->getTerminator()))
113 return 0;
114 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
115 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
116
117 // Eliminate code duplication by ensuring that Pred1Br is conditional if
118 // either are.
119 if (Pred2Br->isConditional()) {
120 // If both branches are conditional, we don't have an "if statement". In
121 // reality, we could transform this case, but since the condition will be
122 // required anyway, we stand no chance of eliminating it, so the xform is
123 // probably not profitable.
124 if (Pred1Br->isConditional())
125 return 0;
126
127 std::swap(Pred1, Pred2);
128 std::swap(Pred1Br, Pred2Br);
129 }
130
131 if (Pred1Br->isConditional()) {
132 // If we found a conditional branch predecessor, make sure that it branches
133 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
134 if (Pred1Br->getSuccessor(0) == BB &&
135 Pred1Br->getSuccessor(1) == Pred2) {
136 IfTrue = Pred1;
137 IfFalse = Pred2;
138 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
139 Pred1Br->getSuccessor(1) == BB) {
140 IfTrue = Pred2;
141 IfFalse = Pred1;
142 } else {
143 // We know that one arm of the conditional goes to BB, so the other must
144 // go somewhere unrelated, and this must not be an "if statement".
145 return 0;
146 }
147
148 // The only thing we have to watch out for here is to make sure that Pred2
149 // doesn't have incoming edges from other blocks. If it does, the condition
150 // doesn't dominate BB.
151 if (++pred_begin(Pred2) != pred_end(Pred2))
152 return 0;
153
154 return Pred1Br->getCondition();
155 }
156
157 // Ok, if we got here, both predecessors end with an unconditional branch to
158 // BB. Don't panic! If both blocks only have a single (identical)
159 // predecessor, and THAT is a conditional branch, then we're all ok!
160 if (pred_begin(Pred1) == pred_end(Pred1) ||
161 ++pred_begin(Pred1) != pred_end(Pred1) ||
162 pred_begin(Pred2) == pred_end(Pred2) ||
163 ++pred_begin(Pred2) != pred_end(Pred2) ||
164 *pred_begin(Pred1) != *pred_begin(Pred2))
165 return 0;
166
167 // Otherwise, if this is a conditional branch, then we can use it!
168 BasicBlock *CommonPred = *pred_begin(Pred1);
169 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
170 assert(BI->isConditional() && "Two successors but not conditional?");
171 if (BI->getSuccessor(0) == Pred1) {
172 IfTrue = Pred1;
173 IfFalse = Pred2;
174 } else {
175 IfTrue = Pred2;
176 IfFalse = Pred1;
177 }
178 return BI->getCondition();
179 }
180 return 0;
181}
182
183
184// If we have a merge point of an "if condition" as accepted above, return true
185// if the specified value dominates the block. We don't handle the true
186// generality of domination here, just a special case which works well enough
187// for us.
Chris Lattner45c35b12004-10-14 05:13:36 +0000188//
189// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
190// see if V (which must be an instruction) is cheap to compute and is
191// non-trapping. If both are true, the instruction is inserted into the set and
192// true is returned.
193static bool DominatesMergePoint(Value *V, BasicBlock *BB,
194 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000195 Instruction *I = dyn_cast<Instruction>(V);
196 if (!I) return true; // Non-instructions all dominate instructions.
197 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000198
Chris Lattner0aa56562004-04-09 22:50:22 +0000199 // We don't want to allow wierd loops that might have the "if condition" in
200 // the bottom of this block.
201 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000202
Chris Lattner0aa56562004-04-09 22:50:22 +0000203 // If this instruction is defined in a block that contains an unconditional
204 // branch to BB, then it must be in the 'conditional' part of the "if
205 // statement".
206 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
207 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner45c35b12004-10-14 05:13:36 +0000208 if (!AggressiveInsts) return false;
Chris Lattner0aa56562004-04-09 22:50:22 +0000209 // Okay, it looks like the instruction IS in the "condition". Check to
210 // see if its a cheap instruction to unconditionally compute, and if it
211 // only uses stuff defined outside of the condition. If so, hoist it out.
212 switch (I->getOpcode()) {
213 default: return false; // Cannot hoist this out safely.
214 case Instruction::Load:
215 // We can hoist loads that are non-volatile and obviously cannot trap.
216 if (cast<LoadInst>(I)->isVolatile())
217 return false;
218 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spenceref784f02004-07-18 00:32:14 +0000219 !isa<Constant>(I->getOperand(0)))
Chris Lattner0aa56562004-04-09 22:50:22 +0000220 return false;
221
222 // Finally, we have to check to make sure there are no instructions
223 // before the load in its basic block, as we are going to hoist the loop
224 // out to its predecessor.
225 if (PBB->begin() != BasicBlock::iterator(I))
226 return false;
227 break;
228 case Instruction::Add:
229 case Instruction::Sub:
230 case Instruction::And:
231 case Instruction::Or:
232 case Instruction::Xor:
233 case Instruction::Shl:
234 case Instruction::Shr:
235 break; // These are all cheap and non-trapping instructions.
236 }
237
238 // Okay, we can only really hoist these out if their operands are not
239 // defined in the conditional region.
240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner45c35b12004-10-14 05:13:36 +0000241 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner0aa56562004-04-09 22:50:22 +0000242 return false;
Chris Lattner45c35b12004-10-14 05:13:36 +0000243 // Okay, it's safe to do this! Remember this instruction.
244 AggressiveInsts->insert(I);
Chris Lattner0aa56562004-04-09 22:50:22 +0000245 }
246
Chris Lattner18d1f192004-02-11 03:36:04 +0000247 return true;
248}
Chris Lattner466a0492002-05-21 20:50:24 +0000249
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000250// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
251// instructions that compare a value against a constant, return the value being
252// compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000253static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000254 if (Instruction *Inst = dyn_cast<Instruction>(V))
255 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000256 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000257 Values.push_back(C);
258 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000259 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000260 Values.push_back(C);
261 return Inst->getOperand(1);
262 }
263 } else if (Inst->getOpcode() == Instruction::Or) {
264 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
265 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
266 if (LHS == RHS)
267 return LHS;
268 }
269 return 0;
270}
271
272// GatherConstantSetNEs - Given a potentially 'and'd together collection of
273// setne instructions that compare a value against a constant, return the value
274// being compared, and stick the constant into the Values vector.
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000275static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000276 if (Instruction *Inst = dyn_cast<Instruction>(V))
277 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000278 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000279 Values.push_back(C);
280 return Inst->getOperand(0);
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000281 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000282 Values.push_back(C);
283 return Inst->getOperand(1);
284 }
285 } else if (Inst->getOpcode() == Instruction::Cast) {
286 // Cast of X to bool is really a comparison against zero.
287 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000288 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000289 return Inst->getOperand(0);
290 } else if (Inst->getOpcode() == Instruction::And) {
291 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
292 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
293 if (LHS == RHS)
294 return LHS;
295 }
296 return 0;
297}
298
299
300
301/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
302/// bunch of comparisons of one value against constants, return the value and
303/// the constants being compared.
304static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000305 std::vector<ConstantInt*> &Values) {
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000306 if (Cond->getOpcode() == Instruction::Or) {
307 CompVal = GatherConstantSetEQs(Cond, Values);
308
309 // Return true to indicate that the condition is true if the CompVal is
310 // equal to one of the constants.
311 return true;
312 } else if (Cond->getOpcode() == Instruction::And) {
313 CompVal = GatherConstantSetNEs(Cond, Values);
314
315 // Return false to indicate that the condition is false if the CompVal is
316 // equal to one of the constants.
317 return false;
318 }
319 return false;
320}
321
322/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
323/// has no side effects, nuke it. If it uses any instructions that become dead
324/// because the instruction is now gone, nuke them too.
325static void ErasePossiblyDeadInstructionTree(Instruction *I) {
326 if (isInstructionTriviallyDead(I)) {
327 std::vector<Value*> Operands(I->op_begin(), I->op_end());
328 I->getParent()->getInstList().erase(I);
329 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
330 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
331 ErasePossiblyDeadInstructionTree(OpI);
332 }
333}
334
Chris Lattnera2ab4892004-02-24 07:23:58 +0000335/// SafeToMergeTerminators - Return true if it is safe to merge these two
336/// terminator instructions together.
337///
338static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
339 if (SI1 == SI2) return false; // Can't merge with self!
340
341 // It is not safe to merge these two switch instructions if they have a common
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000342 // successor, and if that successor has a PHI node, and if *that* PHI node has
Chris Lattnera2ab4892004-02-24 07:23:58 +0000343 // conflicting incoming values from the two switch blocks.
344 BasicBlock *SI1BB = SI1->getParent();
345 BasicBlock *SI2BB = SI2->getParent();
346 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
347
348 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
349 if (SI1Succs.count(*I))
350 for (BasicBlock::iterator BBI = (*I)->begin();
Reid Spencer66149462004-09-15 17:06:42 +0000351 isa<PHINode>(BBI); ++BBI) {
352 PHINode *PN = cast<PHINode>(BBI);
Chris Lattnera2ab4892004-02-24 07:23:58 +0000353 if (PN->getIncomingValueForBlock(SI1BB) !=
354 PN->getIncomingValueForBlock(SI2BB))
355 return false;
Reid Spencer66149462004-09-15 17:06:42 +0000356 }
Chris Lattnera2ab4892004-02-24 07:23:58 +0000357
358 return true;
359}
360
361/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
362/// now be entries in it from the 'NewPred' block. The values that will be
363/// flowing into the PHI nodes will be the same as those coming in from
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000364/// ExistPred, an existing predecessor of Succ.
Chris Lattnera2ab4892004-02-24 07:23:58 +0000365static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
366 BasicBlock *ExistPred) {
367 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
368 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
369 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
370
Reid Spencer66149462004-09-15 17:06:42 +0000371 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
372 PHINode *PN = cast<PHINode>(I);
Chris Lattnera2ab4892004-02-24 07:23:58 +0000373 Value *V = PN->getIncomingValueForBlock(ExistPred);
374 PN->addIncoming(V, NewPred);
375 }
376}
377
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000378// isValueEqualityComparison - Return true if the specified terminator checks to
379// see if a value is equal to constant integer value.
380static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattnera64923a2004-03-16 19:45:22 +0000381 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
382 // Do not permit merging of large switch instructions into their
383 // predecessors unless there is only one predecessor.
384 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
385 pred_end(SI->getParent())) > 128)
386 return 0;
387
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000388 return SI->getCondition();
Chris Lattnera64923a2004-03-16 19:45:22 +0000389 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000390 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
391 if (BI->isConditional() && BI->getCondition()->hasOneUse())
392 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
393 if ((SCI->getOpcode() == Instruction::SetEQ ||
394 SCI->getOpcode() == Instruction::SetNE) &&
395 isa<ConstantInt>(SCI->getOperand(1)))
396 return SCI->getOperand(0);
397 return 0;
398}
399
400// Given a value comparison instruction, decode all of the 'cases' that it
401// represents and return the 'default' block.
402static BasicBlock *
403GetValueEqualityComparisonCases(TerminatorInst *TI,
404 std::vector<std::pair<ConstantInt*,
405 BasicBlock*> > &Cases) {
406 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
407 Cases.reserve(SI->getNumCases());
408 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
409 Cases.push_back(std::make_pair(cast<ConstantInt>(SI->getCaseValue(i)),
410 SI->getSuccessor(i)));
411 return SI->getDefaultDest();
412 }
413
414 BranchInst *BI = cast<BranchInst>(TI);
415 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
416 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
417 BI->getSuccessor(SCI->getOpcode() ==
418 Instruction::SetNE)));
419 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
420}
421
422
423// FoldValueComparisonIntoPredecessors - The specified terminator is a value
424// equality comparison instruction (either a switch or a branch on "X == c").
425// See if any of the predecessors of the terminator block are value comparisons
426// on the same value. If so, and if safe to do so, fold them together.
427static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
428 BasicBlock *BB = TI->getParent();
429 Value *CV = isValueEqualityComparison(TI); // CondVal
430 assert(CV && "Not a comparison?");
431 bool Changed = false;
432
433 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
434 while (!Preds.empty()) {
435 BasicBlock *Pred = Preds.back();
436 Preds.pop_back();
437
438 // See if the predecessor is a comparison with the same value.
439 TerminatorInst *PTI = Pred->getTerminator();
440 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
441
442 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
443 // Figure out which 'cases' to copy from SI to PSI.
444 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
445 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
446
447 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
448 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
449
450 // Based on whether the default edge from PTI goes to BB or not, fill in
451 // PredCases and PredDefault with the new switch cases we would like to
452 // build.
453 std::vector<BasicBlock*> NewSuccessors;
454
455 if (PredDefault == BB) {
456 // If this is the default destination from PTI, only the edges in TI
457 // that don't occur in PTI, or that branch to BB will be activated.
458 std::set<ConstantInt*> PTIHandled;
459 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
460 if (PredCases[i].second != BB)
461 PTIHandled.insert(PredCases[i].first);
462 else {
463 // The default destination is BB, we don't need explicit targets.
464 std::swap(PredCases[i], PredCases.back());
465 PredCases.pop_back();
466 --i; --e;
467 }
468
469 // Reconstruct the new switch statement we will be building.
470 if (PredDefault != BBDefault) {
471 PredDefault->removePredecessor(Pred);
472 PredDefault = BBDefault;
473 NewSuccessors.push_back(BBDefault);
474 }
475 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
476 if (!PTIHandled.count(BBCases[i].first) &&
477 BBCases[i].second != BBDefault) {
478 PredCases.push_back(BBCases[i]);
479 NewSuccessors.push_back(BBCases[i].second);
480 }
481
482 } else {
483 // If this is not the default destination from PSI, only the edges
484 // in SI that occur in PSI with a destination of BB will be
485 // activated.
486 std::set<ConstantInt*> PTIHandled;
487 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
488 if (PredCases[i].second == BB) {
489 PTIHandled.insert(PredCases[i].first);
490 std::swap(PredCases[i], PredCases.back());
491 PredCases.pop_back();
492 --i; --e;
493 }
494
495 // Okay, now we know which constants were sent to BB from the
496 // predecessor. Figure out where they will all go now.
497 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
498 if (PTIHandled.count(BBCases[i].first)) {
499 // If this is one we are capable of getting...
500 PredCases.push_back(BBCases[i]);
501 NewSuccessors.push_back(BBCases[i].second);
502 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
503 }
504
505 // If there are any constants vectored to BB that TI doesn't handle,
506 // they must go to the default destination of TI.
507 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
508 E = PTIHandled.end(); I != E; ++I) {
509 PredCases.push_back(std::make_pair(*I, BBDefault));
510 NewSuccessors.push_back(BBDefault);
511 }
512 }
513
514 // Okay, at this point, we know which new successor Pred will get. Make
515 // sure we update the number of entries in the PHI nodes for these
516 // successors.
517 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
518 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
519
520 // Now that the successors are updated, create the new Switch instruction.
521 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PTI);
522 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
523 NewSI->addCase(PredCases[i].first, PredCases[i].second);
524 Pred->getInstList().erase(PTI);
525
526 // Okay, last check. If BB is still a successor of PSI, then we must
527 // have an infinite loop case. If so, add an infinitely looping block
528 // to handle the case to preserve the behavior of the code.
529 BasicBlock *InfLoopBlock = 0;
530 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
531 if (NewSI->getSuccessor(i) == BB) {
532 if (InfLoopBlock == 0) {
533 // Insert it at the end of the loop, because it's either code,
534 // or it won't matter if it's hot. :)
535 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
536 new BranchInst(InfLoopBlock, InfLoopBlock);
537 }
538 NewSI->setSuccessor(i, InfLoopBlock);
539 }
540
541 Changed = true;
542 }
543 }
544 return Changed;
545}
546
Chris Lattnerb2b151d2004-06-19 07:02:14 +0000547namespace {
548 /// ConstantIntOrdering - This class implements a stable ordering of constant
549 /// integers that does not depend on their address. This is important for
550 /// applications that sort ConstantInt's to ensure uniqueness.
551 struct ConstantIntOrdering {
552 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
553 return LHS->getRawValue() < RHS->getRawValue();
554 }
555 };
556}
557
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000558
Chris Lattner466a0492002-05-21 20:50:24 +0000559// SimplifyCFG - This function is used to do simplification of a CFG. For
560// example, it adjusts branches to branches to eliminate the extra hop, it
561// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattner31116ba2003-03-05 21:01:52 +0000562// of the CFG. It returns true if a modification was made.
Chris Lattner466a0492002-05-21 20:50:24 +0000563//
564// WARNING: The entry node of a function may not be simplified.
565//
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000566bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +0000567 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +0000568 Function *M = BB->getParent();
569
570 assert(BB && BB->getParent() && "Block not embedded in function!");
571 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattnerfda72b12002-06-25 16:12:52 +0000572 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner466a0492002-05-21 20:50:24 +0000573
Chris Lattner466a0492002-05-21 20:50:24 +0000574 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnera2ab4892004-02-24 07:23:58 +0000575 if (pred_begin(BB) == pred_end(BB) ||
576 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner32c518e2004-07-15 02:06:12 +0000577 DEBUG(std::cerr << "Removing BB: \n" << *BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000578
579 // Loop through all of our successors and make sure they know that one
580 // of their predecessors is going away.
581 for_each(succ_begin(BB), succ_end(BB),
582 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
583
584 while (!BB->empty()) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000585 Instruction &I = BB->back();
Chris Lattner466a0492002-05-21 20:50:24 +0000586 // If this instruction is used, replace uses with an arbitrary
587 // constant value. Because control flow can't get here, we don't care
588 // what we replace the value with. Note that since this block is
589 // unreachable, and all values contained within it must dominate their
590 // uses, that all uses will eventually be removed.
Chris Lattnerfda72b12002-06-25 16:12:52 +0000591 if (!I.use_empty())
Chris Lattner466a0492002-05-21 20:50:24 +0000592 // Make all users of this instruction reference the constant instead
Chris Lattnerfda72b12002-06-25 16:12:52 +0000593 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
Chris Lattner466a0492002-05-21 20:50:24 +0000594
595 // Remove the instruction from the basic block
Chris Lattnerfda72b12002-06-25 16:12:52 +0000596 BB->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +0000597 }
Chris Lattnerfda72b12002-06-25 16:12:52 +0000598 M->getBasicBlockList().erase(BB);
Chris Lattner466a0492002-05-21 20:50:24 +0000599 return true;
600 }
601
Chris Lattner031340a2003-08-17 19:41:53 +0000602 // Check to see if we can constant propagate this terminator instruction
603 // away...
Chris Lattner3f5823f2003-08-24 18:36:16 +0000604 Changed |= ConstantFoldTerminator(BB);
Chris Lattner031340a2003-08-17 19:41:53 +0000605
Chris Lattnere54d2142003-03-05 21:36:33 +0000606 // Check to see if this block has no non-phi instructions and only a single
607 // successor. If so, replace references to this basic block with references
608 // to the successor.
Chris Lattner466a0492002-05-21 20:50:24 +0000609 succ_iterator SI(succ_begin(BB));
610 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattnere54d2142003-03-05 21:36:33 +0000611 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
612 while (isa<PHINode>(*BBI)) ++BBI;
613
Chris Lattner93d1e392004-11-01 06:53:58 +0000614 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor.
615 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
616 Succ != BB) { // Don't hurt infinite loops!
617 // If our successor has PHI nodes, then we need to update them to include
618 // entries for BB's predecessors, not for BB itself. Be careful though,
619 // if this transformation fails (returns true) then we cannot do this
620 // transformation!
621 //
622 if (!PropagatePredecessorsForPHIs(BB, Succ)) {
623 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
624
625 if (isa<PHINode>(&BB->front())) {
Chris Lattner569a57f2003-03-07 18:13:41 +0000626 std::vector<BasicBlock*>
627 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
Chris Lattner93d1e392004-11-01 06:53:58 +0000628
Chris Lattnere54d2142003-03-05 21:36:33 +0000629 // Move all PHI nodes in BB to Succ if they are alive, otherwise
630 // delete them.
631 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
632 if (PN->use_empty())
Chris Lattner93d1e392004-11-01 06:53:58 +0000633 BB->getInstList().erase(BB->begin()); // Nuke instruction.
Chris Lattnere54d2142003-03-05 21:36:33 +0000634 else {
635 // The instruction is alive, so this means that Succ must have
636 // *ONLY* had BB as a predecessor, and the PHI node is still valid
Chris Lattner569a57f2003-03-07 18:13:41 +0000637 // now. Simply move it into Succ, because we know that BB
638 // strictly dominated Succ.
Chris Lattnere54d2142003-03-05 21:36:33 +0000639 BB->getInstList().remove(BB->begin());
640 Succ->getInstList().push_front(PN);
Chris Lattner93d1e392004-11-01 06:53:58 +0000641
Chris Lattner569a57f2003-03-07 18:13:41 +0000642 // We need to add new entries for the PHI node to account for
643 // predecessors of Succ that the PHI node does not take into
644 // account. At this point, since we know that BB dominated succ,
645 // this means that we should any newly added incoming edges should
646 // use the PHI node as the value for these edges, because they are
647 // loop back edges.
Chris Lattner569a57f2003-03-07 18:13:41 +0000648 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
649 if (OldSuccPreds[i] != BB)
650 PN->addIncoming(PN, OldSuccPreds[i]);
Chris Lattnere54d2142003-03-05 21:36:33 +0000651 }
Chris Lattner93d1e392004-11-01 06:53:58 +0000652 }
653
654 // Everything that jumped to BB now goes to Succ.
655 std::string OldName = BB->getName();
656 BB->replaceAllUsesWith(Succ);
657 BB->eraseFromParent(); // Delete the old basic block.
Chris Lattnere54d2142003-03-05 21:36:33 +0000658
Chris Lattner93d1e392004-11-01 06:53:58 +0000659 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
660 Succ->setName(OldName);
661 return true;
Chris Lattner466a0492002-05-21 20:50:24 +0000662 }
663 }
664 }
665
Chris Lattnere42732e2004-02-16 06:35:48 +0000666 // If this is a returning block with only PHI nodes in it, fold the return
667 // instruction into any unconditional branch predecessors.
Chris Lattner9f0db322004-04-02 18:13:43 +0000668 //
669 // If any predecessor is a conditional branch that just selects among
670 // different return values, fold the replace the branch/return with a select
671 // and return.
Chris Lattnere42732e2004-02-16 06:35:48 +0000672 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
673 BasicBlock::iterator BBI = BB->getTerminator();
674 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner9f0db322004-04-02 18:13:43 +0000675 // Find predecessors that end with branches.
Chris Lattnere42732e2004-02-16 06:35:48 +0000676 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner9f0db322004-04-02 18:13:43 +0000677 std::vector<BranchInst*> CondBranchPreds;
Chris Lattnere42732e2004-02-16 06:35:48 +0000678 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
679 TerminatorInst *PTI = (*PI)->getTerminator();
680 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
681 if (BI->isUnconditional())
682 UncondBranchPreds.push_back(*PI);
Chris Lattner9f0db322004-04-02 18:13:43 +0000683 else
684 CondBranchPreds.push_back(BI);
Chris Lattnere42732e2004-02-16 06:35:48 +0000685 }
686
687 // If we found some, do the transformation!
688 if (!UncondBranchPreds.empty()) {
689 while (!UncondBranchPreds.empty()) {
690 BasicBlock *Pred = UncondBranchPreds.back();
691 UncondBranchPreds.pop_back();
692 Instruction *UncondBranch = Pred->getTerminator();
693 // Clone the return and add it to the end of the predecessor.
694 Instruction *NewRet = RI->clone();
695 Pred->getInstList().push_back(NewRet);
696
697 // If the return instruction returns a value, and if the value was a
698 // PHI node in "BB", propagate the right value into the return.
699 if (NewRet->getNumOperands() == 1)
700 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
701 if (PN->getParent() == BB)
702 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
703 // Update any PHI nodes in the returning block to realize that we no
704 // longer branch to them.
705 BB->removePredecessor(Pred);
706 Pred->getInstList().erase(UncondBranch);
707 }
708
709 // If we eliminated all predecessors of the block, delete the block now.
710 if (pred_begin(BB) == pred_end(BB))
711 // We know there are no successors, so just nuke the block.
712 M->getBasicBlockList().erase(BB);
713
Chris Lattnere42732e2004-02-16 06:35:48 +0000714 return true;
715 }
Chris Lattner9f0db322004-04-02 18:13:43 +0000716
717 // Check out all of the conditional branches going to this return
718 // instruction. If any of them just select between returns, change the
719 // branch itself into a select/return pair.
720 while (!CondBranchPreds.empty()) {
721 BranchInst *BI = CondBranchPreds.back();
722 CondBranchPreds.pop_back();
723 BasicBlock *TrueSucc = BI->getSuccessor(0);
724 BasicBlock *FalseSucc = BI->getSuccessor(1);
725 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
726
727 // Check to see if the non-BB successor is also a return block.
728 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
729 // Check to see if there are only PHI instructions in this block.
730 BasicBlock::iterator OSI = OtherSucc->getTerminator();
731 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
732 // Okay, we found a branch that is going to two return nodes. If
733 // there is no return value for this function, just change the
734 // branch into a return.
735 if (RI->getNumOperands() == 0) {
736 TrueSucc->removePredecessor(BI->getParent());
737 FalseSucc->removePredecessor(BI->getParent());
738 new ReturnInst(0, BI);
739 BI->getParent()->getInstList().erase(BI);
740 return true;
741 }
742
743 // Otherwise, figure out what the true and false return values are
744 // so we can insert a new select instruction.
745 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
746 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
747
748 // Unwrap any PHI nodes in the return blocks.
749 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
750 if (TVPN->getParent() == TrueSucc)
751 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
752 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
753 if (FVPN->getParent() == FalseSucc)
754 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
755
Chris Lattnereed034b2004-04-02 18:15:10 +0000756 TrueSucc->removePredecessor(BI->getParent());
757 FalseSucc->removePredecessor(BI->getParent());
758
Chris Lattner9f0db322004-04-02 18:13:43 +0000759 // Insert a new select instruction.
Chris Lattner879ce782004-09-29 05:43:32 +0000760 Value *NewRetVal;
761 Value *BrCond = BI->getCondition();
762 if (TrueValue != FalseValue)
763 NewRetVal = new SelectInst(BrCond, TrueValue,
764 FalseValue, "retval", BI);
765 else
766 NewRetVal = TrueValue;
767
Chris Lattner9f0db322004-04-02 18:13:43 +0000768 new ReturnInst(NewRetVal, BI);
769 BI->getParent()->getInstList().erase(BI);
Chris Lattner879ce782004-09-29 05:43:32 +0000770 if (BrCond->use_empty())
771 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
772 BrCondI->getParent()->getInstList().erase(BrCondI);
Chris Lattner9f0db322004-04-02 18:13:43 +0000773 return true;
774 }
775 }
776 }
Chris Lattnere42732e2004-02-16 06:35:48 +0000777 }
Chris Lattner3cd98f02004-02-24 05:54:22 +0000778 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
779 // Check to see if the first instruction in this block is just an unwind.
780 // If so, replace any invoke instructions which use this as an exception
Chris Lattner5823ac12004-07-20 01:17:38 +0000781 // destination with call instructions, and any unconditional branch
782 // predecessor with an unwind.
Chris Lattner3cd98f02004-02-24 05:54:22 +0000783 //
784 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
785 while (!Preds.empty()) {
786 BasicBlock *Pred = Preds.back();
Chris Lattner5823ac12004-07-20 01:17:38 +0000787 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
788 if (BI->isUnconditional()) {
789 Pred->getInstList().pop_back(); // nuke uncond branch
790 new UnwindInst(Pred); // Use unwind.
791 Changed = true;
792 }
793 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattner3cd98f02004-02-24 05:54:22 +0000794 if (II->getUnwindDest() == BB) {
795 // Insert a new branch instruction before the invoke, because this
796 // is now a fall through...
797 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
798 Pred->getInstList().remove(II); // Take out of symbol table
799
800 // Insert the call now...
801 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
802 CallInst *CI = new CallInst(II->getCalledValue(), Args,
803 II->getName(), BI);
804 // If the invoke produced a value, the Call now does instead
805 II->replaceAllUsesWith(CI);
806 delete II;
807 Changed = true;
808 }
809
810 Preds.pop_back();
811 }
Chris Lattner90ea78e2004-02-24 16:09:21 +0000812
813 // If this block is now dead, remove it.
814 if (pred_begin(BB) == pred_end(BB)) {
815 // We know there are no successors, so just nuke the block.
816 M->getBasicBlockList().erase(BB);
817 return true;
818 }
819
Chris Lattnera2ab4892004-02-24 07:23:58 +0000820 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->begin())) {
Chris Lattnera078f472004-03-17 02:02:47 +0000821 if (isValueEqualityComparison(SI))
822 if (FoldValueComparisonIntoPredecessors(SI))
823 return SimplifyCFG(BB) || 1;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000824 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner88da6f72004-05-01 22:36:37 +0000825 if (BI->isConditional()) {
Chris Lattner2e93c422004-05-01 23:35:43 +0000826 if (Value *CompVal = isValueEqualityComparison(BI)) {
827 // This block must be empty, except for the setcond inst, if it exists.
828 BasicBlock::iterator I = BB->begin();
829 if (&*I == BI ||
830 (&*I == cast<Instruction>(BI->getCondition()) &&
831 &*++I == BI))
832 if (FoldValueComparisonIntoPredecessors(BI))
833 return SimplifyCFG(BB) | true;
834 }
835
836 // If this basic block is ONLY a setcc and a branch, and if a predecessor
837 // branches to us and one of our successors, fold the setcc into the
838 // predecessor and use logical operations to pick the right destination.
Chris Lattner51a6dbc2004-05-02 05:02:03 +0000839 BasicBlock *TrueDest = BI->getSuccessor(0);
840 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbe6f0682004-05-02 05:19:36 +0000841 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattner2e93c422004-05-01 23:35:43 +0000842 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner51a6dbc2004-05-02 05:02:03 +0000843 Cond->getNext() == BI && Cond->hasOneUse() &&
844 TrueDest != BB && FalseDest != BB)
Chris Lattner2e93c422004-05-01 23:35:43 +0000845 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
846 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner1e94ed62004-05-02 01:00:44 +0000847 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000848 BasicBlock *PredBlock = *PI;
Chris Lattner2e93c422004-05-01 23:35:43 +0000849 if (PBI->getSuccessor(0) == FalseDest ||
850 PBI->getSuccessor(1) == TrueDest) {
851 // Invert the predecessors condition test (xor it with true),
852 // which allows us to write this code once.
853 Value *NewCond =
854 BinaryOperator::createNot(PBI->getCondition(),
855 PBI->getCondition()->getName()+".not", PBI);
856 PBI->setCondition(NewCond);
857 BasicBlock *OldTrue = PBI->getSuccessor(0);
858 BasicBlock *OldFalse = PBI->getSuccessor(1);
859 PBI->setSuccessor(0, OldFalse);
860 PBI->setSuccessor(1, OldTrue);
861 }
862
863 if (PBI->getSuccessor(0) == TrueDest ||
864 PBI->getSuccessor(1) == FalseDest) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000865 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattner2e93c422004-05-01 23:35:43 +0000866 // two conditions together.
867 Instruction *New = Cond->clone();
868 New->setName(Cond->getName());
869 Cond->setName(Cond->getName()+".old");
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000870 PredBlock->getInstList().insert(PBI, New);
Chris Lattner2e93c422004-05-01 23:35:43 +0000871 Instruction::BinaryOps Opcode =
872 PBI->getSuccessor(0) == TrueDest ?
873 Instruction::Or : Instruction::And;
874 Value *NewCond =
875 BinaryOperator::create(Opcode, PBI->getCondition(),
876 New, "bothcond", PBI);
877 PBI->setCondition(NewCond);
878 if (PBI->getSuccessor(0) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000879 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +0000880 PBI->setSuccessor(0, TrueDest);
881 }
882 if (PBI->getSuccessor(1) == BB) {
Chris Lattnerf12c4a32004-06-21 07:19:01 +0000883 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattner2e93c422004-05-01 23:35:43 +0000884 PBI->setSuccessor(1, FalseDest);
885 }
886 return SimplifyCFG(BB) | 1;
887 }
888 }
Chris Lattner2e93c422004-05-01 23:35:43 +0000889
Chris Lattner88da6f72004-05-01 22:36:37 +0000890 // If this block ends with a branch instruction, and if there is one
891 // predecessor, see if the previous block ended with a branch on the same
892 // condition, which makes this conditional branch redundant.
893 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
894 BasicBlock *OnlyPred = *PI++;
895 for (; PI != PE; ++PI)// Search all predecessors, see if they are all same
896 if (*PI != OnlyPred) {
897 OnlyPred = 0; // There are multiple different predecessors...
898 break;
899 }
900
901 if (OnlyPred)
902 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
903 if (PBI->isConditional() &&
904 PBI->getCondition() == BI->getCondition() &&
Chris Lattner4cbd1602004-05-01 22:41:51 +0000905 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
Chris Lattner88da6f72004-05-01 22:36:37 +0000906 // Okay, the outcome of this conditional branch is statically
907 // knowable. Delete the outgoing CFG edge that is impossible to
908 // execute.
909 bool CondIsTrue = PBI->getSuccessor(0) == BB;
910 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
911 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
912 BB->getInstList().erase(BI);
913 return SimplifyCFG(BB) | true;
914 }
Chris Lattnera2ab4892004-02-24 07:23:58 +0000915 }
Chris Lattner5edb2f32004-10-18 04:07:22 +0000916 } else if (isa<UnreachableInst>(BB->getTerminator())) {
917 // If there are any instructions immediately before the unreachable that can
918 // be removed, do so.
919 Instruction *Unreachable = BB->getTerminator();
920 while (Unreachable != BB->begin()) {
921 BasicBlock::iterator BBI = Unreachable;
922 --BBI;
923 if (isa<CallInst>(BBI)) break;
924 // Delete this instruction
925 BB->getInstList().erase(BBI);
926 Changed = true;
927 }
928
929 // If the unreachable instruction is the first in the block, take a gander
930 // at all of the predecessors of this instruction, and simplify them.
931 if (&BB->front() == Unreachable) {
932 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
933 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
934 TerminatorInst *TI = Preds[i]->getTerminator();
935
936 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
937 if (BI->isUnconditional()) {
938 if (BI->getSuccessor(0) == BB) {
939 new UnreachableInst(TI);
940 TI->eraseFromParent();
941 Changed = true;
942 }
943 } else {
944 if (BI->getSuccessor(0) == BB) {
945 new BranchInst(BI->getSuccessor(1), BI);
946 BI->eraseFromParent();
947 } else if (BI->getSuccessor(1) == BB) {
948 new BranchInst(BI->getSuccessor(0), BI);
949 BI->eraseFromParent();
950 Changed = true;
951 }
952 }
953 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
954 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
955 if (SI->getSuccessor(i) == BB) {
956 SI->removeCase(i);
957 --i; --e;
958 Changed = true;
959 }
960 // If the default value is unreachable, figure out the most popular
961 // destination and make it the default.
962 if (SI->getSuccessor(0) == BB) {
963 std::map<BasicBlock*, unsigned> Popularity;
964 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
965 Popularity[SI->getSuccessor(i)]++;
966
967 // Find the most popular block.
968 unsigned MaxPop = 0;
969 BasicBlock *MaxBlock = 0;
970 for (std::map<BasicBlock*, unsigned>::iterator
971 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
972 if (I->second > MaxPop) {
973 MaxPop = I->second;
974 MaxBlock = I->first;
975 }
976 }
977 if (MaxBlock) {
978 // Make this the new default, allowing us to delete any explicit
979 // edges to it.
980 SI->setSuccessor(0, MaxBlock);
981 Changed = true;
982
983 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
984 if (SI->getSuccessor(i) == MaxBlock) {
985 SI->removeCase(i);
986 --i; --e;
987 }
988 }
989 }
990 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
991 if (II->getUnwindDest() == BB) {
992 // Convert the invoke to a call instruction. This would be a good
993 // place to note that the call does not throw though.
994 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
995 II->removeFromParent(); // Take out of symbol table
996
997 // Insert the call now...
998 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
999 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1000 II->getName(), BI);
1001 // If the invoke produced a value, the Call does now instead.
1002 II->replaceAllUsesWith(CI);
1003 delete II;
1004 Changed = true;
1005 }
1006 }
1007 }
1008
1009 // If this block is now dead, remove it.
1010 if (pred_begin(BB) == pred_end(BB)) {
1011 // We know there are no successors, so just nuke the block.
1012 M->getBasicBlockList().erase(BB);
1013 return true;
1014 }
1015 }
Chris Lattnere42732e2004-02-16 06:35:48 +00001016 }
1017
Chris Lattner466a0492002-05-21 20:50:24 +00001018 // Merge basic blocks into their predecessor if there is only one distinct
1019 // pred, and if there is only one distinct successor of the predecessor, and
1020 // if there are no PHI nodes.
1021 //
Chris Lattner838b8452004-02-11 01:17:07 +00001022 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1023 BasicBlock *OnlyPred = *PI++;
1024 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1025 if (*PI != OnlyPred) {
1026 OnlyPred = 0; // There are multiple different predecessors...
1027 break;
1028 }
Chris Lattner88da6f72004-05-01 22:36:37 +00001029
Chris Lattner838b8452004-02-11 01:17:07 +00001030 BasicBlock *OnlySucc = 0;
1031 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1032 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1033 // Check to see if there is only one distinct successor...
1034 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1035 OnlySucc = BB;
1036 for (; SI != SE; ++SI)
1037 if (*SI != OnlySucc) {
1038 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner466a0492002-05-21 20:50:24 +00001039 break;
1040 }
Chris Lattner838b8452004-02-11 01:17:07 +00001041 }
1042
1043 if (OnlySucc) {
Chris Lattner32c518e2004-07-15 02:06:12 +00001044 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
Chris Lattner838b8452004-02-11 01:17:07 +00001045 TerminatorInst *Term = OnlyPred->getTerminator();
1046
1047 // Resolve any PHI nodes at the start of the block. They are all
1048 // guaranteed to have exactly one entry if they exist, unless there are
1049 // multiple duplicate (but guaranteed to be equal) entries for the
1050 // incoming edges. This occurs when there are multiple edges from
1051 // OnlyPred to OnlySucc.
1052 //
1053 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1054 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1055 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner466a0492002-05-21 20:50:24 +00001056 }
1057
Chris Lattner838b8452004-02-11 01:17:07 +00001058 // Delete the unconditional branch from the predecessor...
1059 OnlyPred->getInstList().pop_back();
Chris Lattner466a0492002-05-21 20:50:24 +00001060
Chris Lattner838b8452004-02-11 01:17:07 +00001061 // Move all definitions in the successor to the predecessor...
1062 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Chris Lattnerfda72b12002-06-25 16:12:52 +00001063
Chris Lattner838b8452004-02-11 01:17:07 +00001064 // Make all PHI nodes that referred to BB now refer to Pred as their
1065 // source...
1066 BB->replaceAllUsesWith(OnlyPred);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001067
Chris Lattner838b8452004-02-11 01:17:07 +00001068 std::string OldName = BB->getName();
Chris Lattnerfda72b12002-06-25 16:12:52 +00001069
Chris Lattner838b8452004-02-11 01:17:07 +00001070 // Erase basic block from the function...
1071 M->getBasicBlockList().erase(BB);
Chris Lattnerfda72b12002-06-25 16:12:52 +00001072
Chris Lattner838b8452004-02-11 01:17:07 +00001073 // Inherit predecessors name if it exists...
1074 if (!OldName.empty() && !OnlyPred->hasName())
1075 OnlyPred->setName(OldName);
Chris Lattner466a0492002-05-21 20:50:24 +00001076
Chris Lattner838b8452004-02-11 01:17:07 +00001077 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00001078 }
Chris Lattner18d1f192004-02-11 03:36:04 +00001079
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001080 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1081 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1082 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1083 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1084 Instruction *Cond = cast<Instruction>(BI->getCondition());
1085 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1086 // 'setne's and'ed together, collect them.
1087 Value *CompVal = 0;
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001088 std::vector<ConstantInt*> Values;
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001089 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1090 if (CompVal && CompVal->getType()->isInteger()) {
1091 // There might be duplicate constants in the list, which the switch
1092 // instruction can't handle, remove them now.
Chris Lattnerb2b151d2004-06-19 07:02:14 +00001093 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001094 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1095
1096 // Figure out which block is which destination.
1097 BasicBlock *DefaultBB = BI->getSuccessor(1);
1098 BasicBlock *EdgeBB = BI->getSuccessor(0);
1099 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1100
1101 // Create the new switch instruction now.
1102 SwitchInst *New = new SwitchInst(CompVal, DefaultBB, BI);
1103
1104 // Add all of the 'cases' to the switch instruction.
1105 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1106 New->addCase(Values[i], EdgeBB);
1107
1108 // We added edges from PI to the EdgeBB. As such, if there were any
1109 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1110 // the number of edges added.
1111 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer66149462004-09-15 17:06:42 +00001112 isa<PHINode>(BBI); ++BBI) {
1113 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner6f4b45a2004-02-24 05:38:11 +00001114 Value *InVal = PN->getIncomingValueForBlock(*PI);
1115 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1116 PN->addIncoming(InVal, *PI);
1117 }
1118
1119 // Erase the old branch instruction.
1120 (*PI)->getInstList().erase(BI);
1121
1122 // Erase the potentially condition tree that was used to computed the
1123 // branch condition.
1124 ErasePossiblyDeadInstructionTree(Cond);
1125 return true;
1126 }
1127 }
1128
Chris Lattner18d1f192004-02-11 03:36:04 +00001129 // If there is a trivial two-entry PHI node in this basic block, and we can
1130 // eliminate it, do so now.
1131 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1132 if (PN->getNumIncomingValues() == 2) {
1133 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1134 // statement", which has a very simple dominance structure. Basically, we
1135 // are trying to find the condition that is being branched on, which
1136 // subsequently causes this merge to happen. We really want control
1137 // dependence information for this check, but simplifycfg can't keep it up
1138 // to date, and this catches most of the cases we care about anyway.
1139 //
1140 BasicBlock *IfTrue, *IfFalse;
1141 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
Chris Lattner9734fd02004-06-20 01:13:18 +00001142 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1143 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattner18d1f192004-02-11 03:36:04 +00001144
Chris Lattner45c35b12004-10-14 05:13:36 +00001145 // Loop over the PHI's seeing if we can promote them all to select
1146 // instructions. While we are at it, keep track of the instructions
1147 // that need to be moved to the dominating block.
1148 std::set<Instruction*> AggressiveInsts;
1149 bool CanPromote = true;
1150
Chris Lattner18d1f192004-02-11 03:36:04 +00001151 BasicBlock::iterator AfterPHIIt = BB->begin();
Chris Lattner45c35b12004-10-14 05:13:36 +00001152 while (isa<PHINode>(AfterPHIIt)) {
1153 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1154 if (PN->getIncomingValue(0) == PN->getIncomingValue(1))
1155 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1156 else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1157 &AggressiveInsts) ||
1158 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1159 &AggressiveInsts)) {
1160 CanPromote = false;
1161 break;
1162 }
1163 }
Chris Lattner18d1f192004-02-11 03:36:04 +00001164
Chris Lattner45c35b12004-10-14 05:13:36 +00001165 // Did we eliminate all PHI's?
1166 CanPromote |= AfterPHIIt == BB->begin();
Chris Lattner18d1f192004-02-11 03:36:04 +00001167
Chris Lattner45c35b12004-10-14 05:13:36 +00001168 // If we all PHI nodes are promotable, check to make sure that all
1169 // instructions in the predecessor blocks can be promoted as well. If
1170 // not, we won't be able to get rid of the control flow, so it's not
1171 // worth promoting to select instructions.
Reid Spencerfad217c2004-10-22 16:10:39 +00001172 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
Chris Lattner45c35b12004-10-14 05:13:36 +00001173 if (CanPromote) {
1174 PN = cast<PHINode>(BB->begin());
1175 BasicBlock *Pred = PN->getIncomingBlock(0);
1176 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1177 IfBlock1 = Pred;
1178 DomBlock = *pred_begin(Pred);
1179 for (BasicBlock::iterator I = Pred->begin();
1180 !isa<TerminatorInst>(I); ++I)
1181 if (!AggressiveInsts.count(I)) {
1182 // This is not an aggressive instruction that we can promote.
1183 // Because of this, we won't be able to get rid of the control
1184 // flow, so the xform is not worth it.
1185 CanPromote = false;
1186 break;
1187 }
1188 }
1189
1190 Pred = PN->getIncomingBlock(1);
1191 if (CanPromote &&
1192 cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1193 IfBlock2 = Pred;
1194 DomBlock = *pred_begin(Pred);
1195 for (BasicBlock::iterator I = Pred->begin();
1196 !isa<TerminatorInst>(I); ++I)
1197 if (!AggressiveInsts.count(I)) {
1198 // This is not an aggressive instruction that we can promote.
1199 // Because of this, we won't be able to get rid of the control
1200 // flow, so the xform is not worth it.
1201 CanPromote = false;
1202 break;
1203 }
1204 }
1205 }
1206
1207 // If we can still promote the PHI nodes after this gauntlet of tests,
1208 // do all of the PHI's now.
1209 if (CanPromote) {
1210 // Move all 'aggressive' instructions, which are defined in the
1211 // conditional parts of the if's up to the dominating block.
1212 if (IfBlock1) {
1213 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1214 IfBlock1->getInstList(),
1215 IfBlock1->begin(),
1216 IfBlock1->getTerminator());
1217 }
1218 if (IfBlock2) {
1219 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1220 IfBlock2->getInstList(),
1221 IfBlock2->begin(),
1222 IfBlock2->getTerminator());
1223 }
1224
1225 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1226 // Change the PHI node into a select instruction.
Chris Lattner18d1f192004-02-11 03:36:04 +00001227 Value *TrueVal =
1228 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1229 Value *FalseVal =
1230 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1231
Chris Lattner81bdcb92004-03-30 19:44:05 +00001232 std::string Name = PN->getName(); PN->setName("");
1233 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
Chris Lattner45c35b12004-10-14 05:13:36 +00001234 Name, AfterPHIIt));
Chris Lattner81bdcb92004-03-30 19:44:05 +00001235 BB->getInstList().erase(PN);
Chris Lattner18d1f192004-02-11 03:36:04 +00001236 }
Chris Lattner45c35b12004-10-14 05:13:36 +00001237 Changed = true;
Chris Lattner18d1f192004-02-11 03:36:04 +00001238 }
1239 }
1240 }
Chris Lattner466a0492002-05-21 20:50:24 +00001241
Chris Lattner031340a2003-08-17 19:41:53 +00001242 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00001243}