blob: eecf72db91a7b8ac392a7fbb879c8090a94f088d [file] [log] [blame]
Chris Lattner01d1ee32002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner01d1ee32002-05-21 20:50:24 +00009//
Chris Lattnerbb190ac2002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner01d1ee32002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner218a8222004-06-20 01:13:18 +000014#define DEBUG_TYPE "simplifycfg"
Chris Lattner01d1ee32002-05-21 20:50:24 +000015#include "llvm/Transforms/Utils/Local.h"
Chris Lattner723c66d2004-02-11 03:36:04 +000016#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
Chris Lattner0d560082004-02-24 05:38:11 +000018#include "llvm/Type.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000019#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000020#include "llvm/Support/Debug.h"
Chris Lattner01d1ee32002-05-21 20:50:24 +000021#include <algorithm>
22#include <functional>
Chris Lattnerd52c2612004-02-24 07:23:58 +000023#include <set>
Chris Lattner698f96f2004-10-18 04:07:22 +000024#include <map>
Chris Lattnerf7703df2004-01-09 06:12:26 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner0d560082004-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 Lattner01d1ee32002-05-21 20:50:24 +000033//
34// Assumption: Succ is the single successor for BB.
35//
Misha Brukmana3bbcb52002-10-29 23:06:16 +000036static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000037 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000038
39 if (!isa<PHINode>(Succ->front()))
40 return false; // We can make the transformation, no problem.
Chris Lattner01d1ee32002-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 Lattnere2ca5402003-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 Lattner01d1ee32002-05-21 20:50:24 +000050 //
Chris Lattnere2ca5402003-03-05 21:01:52 +000051 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000052 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
Chris Lattnere2ca5402003-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 Spencer2da5c3d2004-09-15 17:06:42 +000055 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
56 PHINode *PN = cast<PHINode>(I);
Chris Lattnere2ca5402003-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 Lattner01d1ee32002-05-21 20:50:24 +000069
Chris Lattner218a8222004-06-20 01:13:18 +000070 // Loop over all of the PHI nodes in the successor BB.
Reid Spencer2da5c3d2004-09-15 17:06:42 +000071 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
72 PHINode *PN = cast<PHINode>(I);
Chris Lattnerbb190ac2002-10-08 21:36:33 +000073 Value *OldVal = PN->removeIncomingValue(BB, false);
Chris Lattner01d1ee32002-05-21 20:50:24 +000074 assert(OldVal && "No entry in PHI for Pred BB!");
75
Chris Lattner218a8222004-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 Lattner46a5f1f2003-03-05 21:36:33 +000078 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
79 PHINode *OldValPN = cast<PHINode>(OldVal);
Chris Lattner218a8222004-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 Lattner46a5f1f2003-03-05 21:36:33 +000083 } else {
Misha Brukmanfd939082005-04-21 23:48:37 +000084 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
Chris Lattner46a5f1f2003-03-05 21:36:33 +000085 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 Lattner01d1ee32002-05-21 20:50:24 +000089 }
90 }
91 return false;
92}
93
Chris Lattner7e663482005-08-03 00:11:16 +000094/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
95/// branch to Succ, and contains no instructions other than PHI nodes and the
96/// branch. If possible, eliminate BB.
97static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
98 BasicBlock *Succ) {
99 // If our successor has PHI nodes, then we need to update them to include
100 // entries for BB's predecessors, not for BB itself. Be careful though,
101 // if this transformation fails (returns true) then we cannot do this
102 // transformation!
103 //
104 if (PropagatePredecessorsForPHIs(BB, Succ)) return false;
105
106 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
107
108 if (isa<PHINode>(&BB->front())) {
109 std::vector<BasicBlock*>
110 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
111
112 // Move all PHI nodes in BB to Succ if they are alive, otherwise
113 // delete them.
114 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
115 if (PN->use_empty() /*|| Succ->getSinglePredecessor() == 0*/) {
116 // We can only move the PHI node into Succ if BB dominates Succ.
117 // Since BB only has a single successor (Succ), the PHI nodes
118 // will dominate Succ, unless Succ has multiple predecessors. In
119 // this case, the PHIs are either dead, or have references in dead
120 // blocks. In either case, we can just remove them.
121 if (!PN->use_empty()) // Uses in dead block?
122 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
123 PN->eraseFromParent(); // Nuke instruction.
124 } else {
125 // The instruction is alive, so this means that Succ must have
126 // *ONLY* had BB as a predecessor, and the PHI node is still valid
127 // now. Simply move it into Succ, because we know that BB
128 // strictly dominated Succ.
129 BB->getInstList().remove(BB->begin());
130 Succ->getInstList().push_front(PN);
131
132 // We need to add new entries for the PHI node to account for
133 // predecessors of Succ that the PHI node does not take into
134 // account. At this point, since we know that BB dominated succ,
135 // this means that we should any newly added incoming edges should
136 // use the PHI node as the value for these edges, because they are
137 // loop back edges.
138 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
139 if (OldSuccPreds[i] != BB)
140 PN->addIncoming(PN, OldSuccPreds[i]);
141 }
142 }
143
144 // Everything that jumped to BB now goes to Succ.
145 std::string OldName = BB->getName();
146 BB->replaceAllUsesWith(Succ);
147 BB->eraseFromParent(); // Delete the old basic block.
148
149 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
150 Succ->setName(OldName);
151 return true;
152}
153
Chris Lattner723c66d2004-02-11 03:36:04 +0000154/// GetIfCondition - Given a basic block (BB) with two predecessors (and
155/// presumably PHI nodes in it), check to see if the merge at this block is due
156/// to an "if condition". If so, return the boolean condition that determines
157/// which entry into BB will be taken. Also, return by references the block
158/// that will be entered from if the condition is true, and the block that will
159/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000160///
Chris Lattner723c66d2004-02-11 03:36:04 +0000161///
162static Value *GetIfCondition(BasicBlock *BB,
163 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
164 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
165 "Function can only handle blocks with 2 predecessors!");
166 BasicBlock *Pred1 = *pred_begin(BB);
167 BasicBlock *Pred2 = *++pred_begin(BB);
168
169 // We can only handle branches. Other control flow will be lowered to
170 // branches if possible anyway.
171 if (!isa<BranchInst>(Pred1->getTerminator()) ||
172 !isa<BranchInst>(Pred2->getTerminator()))
173 return 0;
174 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
175 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
176
177 // Eliminate code duplication by ensuring that Pred1Br is conditional if
178 // either are.
179 if (Pred2Br->isConditional()) {
180 // If both branches are conditional, we don't have an "if statement". In
181 // reality, we could transform this case, but since the condition will be
182 // required anyway, we stand no chance of eliminating it, so the xform is
183 // probably not profitable.
184 if (Pred1Br->isConditional())
185 return 0;
186
187 std::swap(Pred1, Pred2);
188 std::swap(Pred1Br, Pred2Br);
189 }
190
191 if (Pred1Br->isConditional()) {
192 // If we found a conditional branch predecessor, make sure that it branches
193 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
194 if (Pred1Br->getSuccessor(0) == BB &&
195 Pred1Br->getSuccessor(1) == Pred2) {
196 IfTrue = Pred1;
197 IfFalse = Pred2;
198 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
199 Pred1Br->getSuccessor(1) == BB) {
200 IfTrue = Pred2;
201 IfFalse = Pred1;
202 } else {
203 // We know that one arm of the conditional goes to BB, so the other must
204 // go somewhere unrelated, and this must not be an "if statement".
205 return 0;
206 }
207
208 // The only thing we have to watch out for here is to make sure that Pred2
209 // doesn't have incoming edges from other blocks. If it does, the condition
210 // doesn't dominate BB.
211 if (++pred_begin(Pred2) != pred_end(Pred2))
212 return 0;
213
214 return Pred1Br->getCondition();
215 }
216
217 // Ok, if we got here, both predecessors end with an unconditional branch to
218 // BB. Don't panic! If both blocks only have a single (identical)
219 // predecessor, and THAT is a conditional branch, then we're all ok!
220 if (pred_begin(Pred1) == pred_end(Pred1) ||
221 ++pred_begin(Pred1) != pred_end(Pred1) ||
222 pred_begin(Pred2) == pred_end(Pred2) ||
223 ++pred_begin(Pred2) != pred_end(Pred2) ||
224 *pred_begin(Pred1) != *pred_begin(Pred2))
225 return 0;
226
227 // Otherwise, if this is a conditional branch, then we can use it!
228 BasicBlock *CommonPred = *pred_begin(Pred1);
229 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
230 assert(BI->isConditional() && "Two successors but not conditional?");
231 if (BI->getSuccessor(0) == Pred1) {
232 IfTrue = Pred1;
233 IfFalse = Pred2;
234 } else {
235 IfTrue = Pred2;
236 IfFalse = Pred1;
237 }
238 return BI->getCondition();
239 }
240 return 0;
241}
242
243
244// If we have a merge point of an "if condition" as accepted above, return true
245// if the specified value dominates the block. We don't handle the true
246// generality of domination here, just a special case which works well enough
247// for us.
Chris Lattner9c078662004-10-14 05:13:36 +0000248//
249// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
250// see if V (which must be an instruction) is cheap to compute and is
251// non-trapping. If both are true, the instruction is inserted into the set and
252// true is returned.
253static bool DominatesMergePoint(Value *V, BasicBlock *BB,
254 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000255 Instruction *I = dyn_cast<Instruction>(V);
256 if (!I) return true; // Non-instructions all dominate instructions.
257 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000258
Chris Lattnerda895d62005-02-27 06:18:25 +0000259 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000260 // the bottom of this block.
261 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000262
Chris Lattner570751c2004-04-09 22:50:22 +0000263 // If this instruction is defined in a block that contains an unconditional
264 // branch to BB, then it must be in the 'conditional' part of the "if
265 // statement".
266 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
267 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner9c078662004-10-14 05:13:36 +0000268 if (!AggressiveInsts) return false;
Chris Lattner570751c2004-04-09 22:50:22 +0000269 // Okay, it looks like the instruction IS in the "condition". Check to
270 // see if its a cheap instruction to unconditionally compute, and if it
271 // only uses stuff defined outside of the condition. If so, hoist it out.
272 switch (I->getOpcode()) {
273 default: return false; // Cannot hoist this out safely.
274 case Instruction::Load:
275 // We can hoist loads that are non-volatile and obviously cannot trap.
276 if (cast<LoadInst>(I)->isVolatile())
277 return false;
278 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spencer460f16c2004-07-18 00:32:14 +0000279 !isa<Constant>(I->getOperand(0)))
Chris Lattner570751c2004-04-09 22:50:22 +0000280 return false;
281
282 // Finally, we have to check to make sure there are no instructions
283 // before the load in its basic block, as we are going to hoist the loop
284 // out to its predecessor.
285 if (PBB->begin() != BasicBlock::iterator(I))
286 return false;
287 break;
288 case Instruction::Add:
289 case Instruction::Sub:
290 case Instruction::And:
291 case Instruction::Or:
292 case Instruction::Xor:
293 case Instruction::Shl:
294 case Instruction::Shr:
Chris Lattnerbf5d4fb2005-04-21 05:31:13 +0000295 case Instruction::SetEQ:
296 case Instruction::SetNE:
297 case Instruction::SetLT:
298 case Instruction::SetGT:
299 case Instruction::SetLE:
300 case Instruction::SetGE:
Chris Lattner570751c2004-04-09 22:50:22 +0000301 break; // These are all cheap and non-trapping instructions.
302 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000303
Chris Lattner570751c2004-04-09 22:50:22 +0000304 // Okay, we can only really hoist these out if their operands are not
305 // defined in the conditional region.
306 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner9c078662004-10-14 05:13:36 +0000307 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner570751c2004-04-09 22:50:22 +0000308 return false;
Chris Lattner9c078662004-10-14 05:13:36 +0000309 // Okay, it's safe to do this! Remember this instruction.
310 AggressiveInsts->insert(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000311 }
312
Chris Lattner723c66d2004-02-11 03:36:04 +0000313 return true;
314}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000315
Chris Lattner0d560082004-02-24 05:38:11 +0000316// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
317// instructions that compare a value against a constant, return the value being
318// compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000319static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000320 if (Instruction *Inst = dyn_cast<Instruction>(V))
321 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000322 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000323 Values.push_back(C);
324 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000325 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000326 Values.push_back(C);
327 return Inst->getOperand(1);
328 }
329 } else if (Inst->getOpcode() == Instruction::Or) {
330 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
331 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
332 if (LHS == RHS)
333 return LHS;
334 }
335 return 0;
336}
337
338// GatherConstantSetNEs - Given a potentially 'and'd together collection of
339// setne instructions that compare a value against a constant, return the value
340// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000341static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000342 if (Instruction *Inst = dyn_cast<Instruction>(V))
343 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000344 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000345 Values.push_back(C);
346 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000347 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000348 Values.push_back(C);
349 return Inst->getOperand(1);
350 }
351 } else if (Inst->getOpcode() == Instruction::Cast) {
352 // Cast of X to bool is really a comparison against zero.
353 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattner1654cff2004-06-19 07:02:14 +0000354 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner0d560082004-02-24 05:38:11 +0000355 return Inst->getOperand(0);
356 } else if (Inst->getOpcode() == Instruction::And) {
357 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
358 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
359 if (LHS == RHS)
360 return LHS;
361 }
362 return 0;
363}
364
365
366
367/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
368/// bunch of comparisons of one value against constants, return the value and
369/// the constants being compared.
370static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000371 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000372 if (Cond->getOpcode() == Instruction::Or) {
373 CompVal = GatherConstantSetEQs(Cond, Values);
374
375 // Return true to indicate that the condition is true if the CompVal is
376 // equal to one of the constants.
377 return true;
378 } else if (Cond->getOpcode() == Instruction::And) {
379 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanfd939082005-04-21 23:48:37 +0000380
Chris Lattner0d560082004-02-24 05:38:11 +0000381 // Return false to indicate that the condition is false if the CompVal is
382 // equal to one of the constants.
383 return false;
384 }
385 return false;
386}
387
388/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
389/// has no side effects, nuke it. If it uses any instructions that become dead
390/// because the instruction is now gone, nuke them too.
391static void ErasePossiblyDeadInstructionTree(Instruction *I) {
392 if (isInstructionTriviallyDead(I)) {
393 std::vector<Value*> Operands(I->op_begin(), I->op_end());
394 I->getParent()->getInstList().erase(I);
395 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
396 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
397 ErasePossiblyDeadInstructionTree(OpI);
398 }
399}
400
Chris Lattnerd52c2612004-02-24 07:23:58 +0000401/// SafeToMergeTerminators - Return true if it is safe to merge these two
402/// terminator instructions together.
403///
404static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
405 if (SI1 == SI2) return false; // Can't merge with self!
406
407 // It is not safe to merge these two switch instructions if they have a common
Chris Lattner2636c1b2004-06-21 07:19:01 +0000408 // successor, and if that successor has a PHI node, and if *that* PHI node has
Chris Lattnerd52c2612004-02-24 07:23:58 +0000409 // conflicting incoming values from the two switch blocks.
410 BasicBlock *SI1BB = SI1->getParent();
411 BasicBlock *SI2BB = SI2->getParent();
412 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
413
414 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
415 if (SI1Succs.count(*I))
416 for (BasicBlock::iterator BBI = (*I)->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000417 isa<PHINode>(BBI); ++BBI) {
418 PHINode *PN = cast<PHINode>(BBI);
Chris Lattnerd52c2612004-02-24 07:23:58 +0000419 if (PN->getIncomingValueForBlock(SI1BB) !=
420 PN->getIncomingValueForBlock(SI2BB))
421 return false;
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000422 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000423
Chris Lattnerd52c2612004-02-24 07:23:58 +0000424 return true;
425}
426
427/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
428/// now be entries in it from the 'NewPred' block. The values that will be
429/// flowing into the PHI nodes will be the same as those coming in from
Chris Lattner2636c1b2004-06-21 07:19:01 +0000430/// ExistPred, an existing predecessor of Succ.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000431static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
432 BasicBlock *ExistPred) {
433 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
434 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
435 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
436
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000437 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
438 PHINode *PN = cast<PHINode>(I);
Chris Lattnerd52c2612004-02-24 07:23:58 +0000439 Value *V = PN->getIncomingValueForBlock(ExistPred);
440 PN->addIncoming(V, NewPred);
441 }
442}
443
Chris Lattner542f1492004-02-28 21:28:10 +0000444// isValueEqualityComparison - Return true if the specified terminator checks to
445// see if a value is equal to constant integer value.
446static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000447 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
448 // Do not permit merging of large switch instructions into their
449 // predecessors unless there is only one predecessor.
450 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
451 pred_end(SI->getParent())) > 128)
452 return 0;
453
Chris Lattner542f1492004-02-28 21:28:10 +0000454 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000455 }
Chris Lattner542f1492004-02-28 21:28:10 +0000456 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
457 if (BI->isConditional() && BI->getCondition()->hasOneUse())
458 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
459 if ((SCI->getOpcode() == Instruction::SetEQ ||
Misha Brukmanfd939082005-04-21 23:48:37 +0000460 SCI->getOpcode() == Instruction::SetNE) &&
Chris Lattner542f1492004-02-28 21:28:10 +0000461 isa<ConstantInt>(SCI->getOperand(1)))
462 return SCI->getOperand(0);
463 return 0;
464}
465
466// Given a value comparison instruction, decode all of the 'cases' that it
467// represents and return the 'default' block.
468static BasicBlock *
Misha Brukmanfd939082005-04-21 23:48:37 +0000469GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000470 std::vector<std::pair<ConstantInt*,
471 BasicBlock*> > &Cases) {
472 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
473 Cases.reserve(SI->getNumCases());
474 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000475 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000476 return SI->getDefaultDest();
477 }
478
479 BranchInst *BI = cast<BranchInst>(TI);
480 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
481 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
482 BI->getSuccessor(SCI->getOpcode() ==
483 Instruction::SetNE)));
484 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
485}
486
487
Chris Lattner623369a2005-02-24 06:17:52 +0000488// EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
489// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000490static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000491 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
492 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
493 if (Cases[i].second == BB) {
494 Cases.erase(Cases.begin()+i);
495 --i; --e;
496 }
497}
498
499// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
500// well.
501static bool
502ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
503 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
504 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
505
506 // Make V1 be smaller than V2.
507 if (V1->size() > V2->size())
508 std::swap(V1, V2);
509
510 if (V1->size() == 0) return false;
511 if (V1->size() == 1) {
512 // Just scan V2.
513 ConstantInt *TheVal = (*V1)[0].first;
514 for (unsigned i = 0, e = V2->size(); i != e; ++i)
515 if (TheVal == (*V2)[i].first)
516 return true;
517 }
518
519 // Otherwise, just sort both lists and compare element by element.
520 std::sort(V1->begin(), V1->end());
521 std::sort(V2->begin(), V2->end());
522 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
523 while (i1 != e1 && i2 != e2) {
524 if ((*V1)[i1].first == (*V2)[i2].first)
525 return true;
526 if ((*V1)[i1].first < (*V2)[i2].first)
527 ++i1;
528 else
529 ++i2;
530 }
531 return false;
532}
533
534// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
535// terminator instruction and its block is known to only have a single
536// predecessor block, check to see if that predecessor is also a value
537// comparison with the same value, and if that comparison determines the outcome
538// of this comparison. If so, simplify TI. This does a very limited form of
539// jump threading.
540static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
541 BasicBlock *Pred) {
542 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
543 if (!PredVal) return false; // Not a value comparison in predecessor.
544
545 Value *ThisVal = isValueEqualityComparison(TI);
546 assert(ThisVal && "This isn't a value comparison!!");
547 if (ThisVal != PredVal) return false; // Different predicates.
548
549 // Find out information about when control will move from Pred to TI's block.
550 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
551 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
552 PredCases);
553 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000554
Chris Lattner623369a2005-02-24 06:17:52 +0000555 // Find information about how control leaves this block.
556 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
557 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
558 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
559
560 // If TI's block is the default block from Pred's comparison, potentially
561 // simplify TI based on this knowledge.
562 if (PredDef == TI->getParent()) {
563 // If we are here, we know that the value is none of those cases listed in
564 // PredCases. If there are any cases in ThisCases that are in PredCases, we
565 // can simplify TI.
566 if (ValuesOverlap(PredCases, ThisCases)) {
567 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
568 // Okay, one of the successors of this condbr is dead. Convert it to a
569 // uncond br.
570 assert(ThisCases.size() == 1 && "Branch can only have one case!");
571 Value *Cond = BTI->getCondition();
572 // Insert the new branch.
573 Instruction *NI = new BranchInst(ThisDef, TI);
574
575 // Remove PHI node entries for the dead edge.
576 ThisCases[0].second->removePredecessor(TI->getParent());
577
578 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
579 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
580
581 TI->eraseFromParent(); // Nuke the old one.
582 // If condition is now dead, nuke it.
583 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
584 ErasePossiblyDeadInstructionTree(CondI);
585 return true;
586
587 } else {
588 SwitchInst *SI = cast<SwitchInst>(TI);
589 // Okay, TI has cases that are statically dead, prune them away.
590 std::set<Constant*> DeadCases;
591 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
592 DeadCases.insert(PredCases[i].first);
593
594 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
595 << "Through successor TI: " << *TI);
596
597 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
598 if (DeadCases.count(SI->getCaseValue(i))) {
599 SI->getSuccessor(i)->removePredecessor(TI->getParent());
600 SI->removeCase(i);
601 }
602
603 DEBUG(std::cerr << "Leaving: " << *TI << "\n");
604 return true;
605 }
606 }
607
608 } else {
609 // Otherwise, TI's block must correspond to some matched value. Find out
610 // which value (or set of values) this is.
611 ConstantInt *TIV = 0;
612 BasicBlock *TIBB = TI->getParent();
613 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
614 if (PredCases[i].second == TIBB)
615 if (TIV == 0)
616 TIV = PredCases[i].first;
617 else
618 return false; // Cannot handle multiple values coming to this block.
619 assert(TIV && "No edge from pred to succ?");
620
621 // Okay, we found the one constant that our value can be if we get into TI's
622 // BB. Find out which successor will unconditionally be branched to.
623 BasicBlock *TheRealDest = 0;
624 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
625 if (ThisCases[i].first == TIV) {
626 TheRealDest = ThisCases[i].second;
627 break;
628 }
629
630 // If not handled by any explicit cases, it is handled by the default case.
631 if (TheRealDest == 0) TheRealDest = ThisDef;
632
633 // Remove PHI node entries for dead edges.
634 BasicBlock *CheckEdge = TheRealDest;
635 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
636 if (*SI != CheckEdge)
637 (*SI)->removePredecessor(TIBB);
638 else
639 CheckEdge = 0;
640
641 // Insert the new branch.
642 Instruction *NI = new BranchInst(TheRealDest, TI);
643
644 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
645 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
646 Instruction *Cond = 0;
647 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
648 Cond = dyn_cast<Instruction>(BI->getCondition());
649 TI->eraseFromParent(); // Nuke the old one.
650
651 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
652 return true;
653 }
654 return false;
655}
656
Chris Lattner542f1492004-02-28 21:28:10 +0000657// FoldValueComparisonIntoPredecessors - The specified terminator is a value
658// equality comparison instruction (either a switch or a branch on "X == c").
659// See if any of the predecessors of the terminator block are value comparisons
660// on the same value. If so, and if safe to do so, fold them together.
661static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
662 BasicBlock *BB = TI->getParent();
663 Value *CV = isValueEqualityComparison(TI); // CondVal
664 assert(CV && "Not a comparison?");
665 bool Changed = false;
666
667 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
668 while (!Preds.empty()) {
669 BasicBlock *Pred = Preds.back();
670 Preds.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000671
Chris Lattner542f1492004-02-28 21:28:10 +0000672 // See if the predecessor is a comparison with the same value.
673 TerminatorInst *PTI = Pred->getTerminator();
674 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
675
676 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
677 // Figure out which 'cases' to copy from SI to PSI.
678 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
679 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
680
681 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
682 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
683
684 // Based on whether the default edge from PTI goes to BB or not, fill in
685 // PredCases and PredDefault with the new switch cases we would like to
686 // build.
687 std::vector<BasicBlock*> NewSuccessors;
688
689 if (PredDefault == BB) {
690 // If this is the default destination from PTI, only the edges in TI
691 // that don't occur in PTI, or that branch to BB will be activated.
692 std::set<ConstantInt*> PTIHandled;
693 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
694 if (PredCases[i].second != BB)
695 PTIHandled.insert(PredCases[i].first);
696 else {
697 // The default destination is BB, we don't need explicit targets.
698 std::swap(PredCases[i], PredCases.back());
699 PredCases.pop_back();
700 --i; --e;
701 }
702
703 // Reconstruct the new switch statement we will be building.
704 if (PredDefault != BBDefault) {
705 PredDefault->removePredecessor(Pred);
706 PredDefault = BBDefault;
707 NewSuccessors.push_back(BBDefault);
708 }
709 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
710 if (!PTIHandled.count(BBCases[i].first) &&
711 BBCases[i].second != BBDefault) {
712 PredCases.push_back(BBCases[i]);
713 NewSuccessors.push_back(BBCases[i].second);
714 }
715
716 } else {
717 // If this is not the default destination from PSI, only the edges
718 // in SI that occur in PSI with a destination of BB will be
719 // activated.
720 std::set<ConstantInt*> PTIHandled;
721 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
722 if (PredCases[i].second == BB) {
723 PTIHandled.insert(PredCases[i].first);
724 std::swap(PredCases[i], PredCases.back());
725 PredCases.pop_back();
726 --i; --e;
727 }
728
729 // Okay, now we know which constants were sent to BB from the
730 // predecessor. Figure out where they will all go now.
731 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
732 if (PTIHandled.count(BBCases[i].first)) {
733 // If this is one we are capable of getting...
734 PredCases.push_back(BBCases[i]);
735 NewSuccessors.push_back(BBCases[i].second);
736 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
737 }
738
739 // If there are any constants vectored to BB that TI doesn't handle,
740 // they must go to the default destination of TI.
741 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
742 E = PTIHandled.end(); I != E; ++I) {
743 PredCases.push_back(std::make_pair(*I, BBDefault));
744 NewSuccessors.push_back(BBDefault);
745 }
746 }
747
748 // Okay, at this point, we know which new successor Pred will get. Make
749 // sure we update the number of entries in the PHI nodes for these
750 // successors.
751 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
752 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
753
754 // Now that the successors are updated, create the new Switch instruction.
Chris Lattner37880592005-01-29 00:38:26 +0000755 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000756 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
757 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000758
759 Instruction *DeadCond = 0;
760 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
761 // If PTI is a branch, remember the condition.
762 DeadCond = dyn_cast<Instruction>(BI->getCondition());
Chris Lattner542f1492004-02-28 21:28:10 +0000763 Pred->getInstList().erase(PTI);
764
Chris Lattner13b2f762005-01-01 16:02:12 +0000765 // If the condition is dead now, remove the instruction tree.
766 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
767
Chris Lattner542f1492004-02-28 21:28:10 +0000768 // Okay, last check. If BB is still a successor of PSI, then we must
769 // have an infinite loop case. If so, add an infinitely looping block
770 // to handle the case to preserve the behavior of the code.
771 BasicBlock *InfLoopBlock = 0;
772 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
773 if (NewSI->getSuccessor(i) == BB) {
774 if (InfLoopBlock == 0) {
775 // Insert it at the end of the loop, because it's either code,
776 // or it won't matter if it's hot. :)
777 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
778 new BranchInst(InfLoopBlock, InfLoopBlock);
779 }
780 NewSI->setSuccessor(i, InfLoopBlock);
781 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000782
Chris Lattner542f1492004-02-28 21:28:10 +0000783 Changed = true;
784 }
785 }
786 return Changed;
787}
788
Chris Lattner37dc9382004-11-30 00:29:14 +0000789/// HoistThenElseCodeToIf - Given a conditional branch that codes to BB1 and
790/// BB2, hoist any common code in the two blocks up into the branch block. The
791/// caller of this function guarantees that BI's block dominates BB1 and BB2.
792static bool HoistThenElseCodeToIf(BranchInst *BI) {
793 // This does very trivial matching, with limited scanning, to find identical
794 // instructions in the two blocks. In particular, we don't want to get into
795 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
796 // such, we currently just scan for obviously identical instructions in an
797 // identical order.
798 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
799 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
800
801 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
802 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2))
803 return false;
804
805 // If we get here, we can hoist at least one instruction.
806 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000807
808 do {
809 // If we are hoisting the terminator instruction, don't move one (making a
810 // broken BB), instead clone it, and remove BI.
811 if (isa<TerminatorInst>(I1))
812 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000813
Chris Lattner37dc9382004-11-30 00:29:14 +0000814 // For a normal instruction, we just move one to right before the branch,
815 // then replace all uses of the other with the first. Finally, we remove
816 // the now redundant second instruction.
817 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
818 if (!I2->use_empty())
819 I2->replaceAllUsesWith(I1);
820 BB2->getInstList().erase(I2);
Misha Brukmanfd939082005-04-21 23:48:37 +0000821
Chris Lattner37dc9382004-11-30 00:29:14 +0000822 I1 = BB1->begin();
823 I2 = BB2->begin();
Chris Lattner37dc9382004-11-30 00:29:14 +0000824 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
825
826 return true;
827
828HoistTerminator:
829 // Okay, it is safe to hoist the terminator.
830 Instruction *NT = I1->clone();
831 BIParent->getInstList().insert(BI, NT);
832 if (NT->getType() != Type::VoidTy) {
833 I1->replaceAllUsesWith(NT);
834 I2->replaceAllUsesWith(NT);
835 NT->setName(I1->getName());
836 }
837
838 // Hoisting one of the terminators from our successor is a great thing.
839 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
840 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
841 // nodes, so we insert select instruction to compute the final result.
842 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
843 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
844 PHINode *PN;
845 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000846 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000847 Value *BB1V = PN->getIncomingValueForBlock(BB1);
848 Value *BB2V = PN->getIncomingValueForBlock(BB2);
849 if (BB1V != BB2V) {
850 // These values do not agree. Insert a select instruction before NT
851 // that determines the right value.
852 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
853 if (SI == 0)
854 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
855 BB1V->getName()+"."+BB2V->getName(), NT);
856 // Make the PHI node use the select for all incoming values for BB1/BB2
857 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
858 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
859 PN->setIncomingValue(i, SI);
860 }
861 }
862 }
863
864 // Update any PHI nodes in our new successors.
865 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
866 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000867
Chris Lattner37dc9382004-11-30 00:29:14 +0000868 BI->eraseFromParent();
869 return true;
870}
871
Chris Lattner1654cff2004-06-19 07:02:14 +0000872namespace {
873 /// ConstantIntOrdering - This class implements a stable ordering of constant
874 /// integers that does not depend on their address. This is important for
875 /// applications that sort ConstantInt's to ensure uniqueness.
876 struct ConstantIntOrdering {
877 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
878 return LHS->getRawValue() < RHS->getRawValue();
879 }
880 };
881}
882
Chris Lattner01d1ee32002-05-21 20:50:24 +0000883// SimplifyCFG - This function is used to do simplification of a CFG. For
884// example, it adjusts branches to branches to eliminate the extra hop, it
885// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +0000886// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000887//
888// WARNING: The entry node of a function may not be simplified.
889//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000890bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000891 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000892 Function *M = BB->getParent();
893
894 assert(BB && BB->getParent() && "Block not embedded in function!");
895 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner18961502002-06-25 16:12:52 +0000896 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +0000897
Chris Lattner01d1ee32002-05-21 20:50:24 +0000898 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000899 if (pred_begin(BB) == pred_end(BB) ||
900 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner30b43442004-07-15 02:06:12 +0000901 DEBUG(std::cerr << "Removing BB: \n" << *BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000902
903 // Loop through all of our successors and make sure they know that one
904 // of their predecessors is going away.
Chris Lattner151c80b2005-04-12 18:51:33 +0000905 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
906 SI->removePredecessor(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000907
908 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +0000909 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000910 // If this instruction is used, replace uses with an arbitrary
Chris Lattnerf5e982d2005-08-02 23:29:23 +0000911 // value. Because control flow can't get here, we don't care
Misha Brukmanfd939082005-04-21 23:48:37 +0000912 // what we replace the value with. Note that since this block is
Chris Lattner01d1ee32002-05-21 20:50:24 +0000913 // unreachable, and all values contained within it must dominate their
914 // uses, that all uses will eventually be removed.
Misha Brukmanfd939082005-04-21 23:48:37 +0000915 if (!I.use_empty())
Chris Lattnerf5e982d2005-08-02 23:29:23 +0000916 // Make all users of this instruction use undef instead
917 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Misha Brukmanfd939082005-04-21 23:48:37 +0000918
Chris Lattner01d1ee32002-05-21 20:50:24 +0000919 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +0000920 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000921 }
Chris Lattner18961502002-06-25 16:12:52 +0000922 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000923 return true;
924 }
925
Chris Lattner694e37f2003-08-17 19:41:53 +0000926 // Check to see if we can constant propagate this terminator instruction
927 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000928 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +0000929
Chris Lattner19831ec2004-02-16 06:35:48 +0000930 // If this is a returning block with only PHI nodes in it, fold the return
931 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +0000932 //
933 // If any predecessor is a conditional branch that just selects among
934 // different return values, fold the replace the branch/return with a select
935 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +0000936 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
937 BasicBlock::iterator BBI = BB->getTerminator();
938 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner147af6b2004-04-02 18:13:43 +0000939 // Find predecessors that end with branches.
Chris Lattner19831ec2004-02-16 06:35:48 +0000940 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner147af6b2004-04-02 18:13:43 +0000941 std::vector<BranchInst*> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +0000942 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
943 TerminatorInst *PTI = (*PI)->getTerminator();
944 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
945 if (BI->isUnconditional())
946 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +0000947 else
948 CondBranchPreds.push_back(BI);
Chris Lattner19831ec2004-02-16 06:35:48 +0000949 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000950
Chris Lattner19831ec2004-02-16 06:35:48 +0000951 // If we found some, do the transformation!
952 if (!UncondBranchPreds.empty()) {
953 while (!UncondBranchPreds.empty()) {
954 BasicBlock *Pred = UncondBranchPreds.back();
955 UncondBranchPreds.pop_back();
956 Instruction *UncondBranch = Pred->getTerminator();
957 // Clone the return and add it to the end of the predecessor.
958 Instruction *NewRet = RI->clone();
959 Pred->getInstList().push_back(NewRet);
960
961 // If the return instruction returns a value, and if the value was a
962 // PHI node in "BB", propagate the right value into the return.
963 if (NewRet->getNumOperands() == 1)
964 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
965 if (PN->getParent() == BB)
966 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
967 // Update any PHI nodes in the returning block to realize that we no
968 // longer branch to them.
969 BB->removePredecessor(Pred);
970 Pred->getInstList().erase(UncondBranch);
971 }
972
973 // If we eliminated all predecessors of the block, delete the block now.
974 if (pred_begin(BB) == pred_end(BB))
975 // We know there are no successors, so just nuke the block.
976 M->getBasicBlockList().erase(BB);
977
Chris Lattner19831ec2004-02-16 06:35:48 +0000978 return true;
979 }
Chris Lattner147af6b2004-04-02 18:13:43 +0000980
981 // Check out all of the conditional branches going to this return
982 // instruction. If any of them just select between returns, change the
983 // branch itself into a select/return pair.
984 while (!CondBranchPreds.empty()) {
985 BranchInst *BI = CondBranchPreds.back();
986 CondBranchPreds.pop_back();
987 BasicBlock *TrueSucc = BI->getSuccessor(0);
988 BasicBlock *FalseSucc = BI->getSuccessor(1);
989 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
990
991 // Check to see if the non-BB successor is also a return block.
992 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
993 // Check to see if there are only PHI instructions in this block.
994 BasicBlock::iterator OSI = OtherSucc->getTerminator();
995 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
996 // Okay, we found a branch that is going to two return nodes. If
997 // there is no return value for this function, just change the
998 // branch into a return.
999 if (RI->getNumOperands() == 0) {
1000 TrueSucc->removePredecessor(BI->getParent());
1001 FalseSucc->removePredecessor(BI->getParent());
1002 new ReturnInst(0, BI);
1003 BI->getParent()->getInstList().erase(BI);
1004 return true;
1005 }
1006
1007 // Otherwise, figure out what the true and false return values are
1008 // so we can insert a new select instruction.
1009 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1010 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1011
1012 // Unwrap any PHI nodes in the return blocks.
1013 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1014 if (TVPN->getParent() == TrueSucc)
1015 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1016 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1017 if (FVPN->getParent() == FalseSucc)
1018 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1019
Chris Lattner7aa773b2004-04-02 18:15:10 +00001020 TrueSucc->removePredecessor(BI->getParent());
1021 FalseSucc->removePredecessor(BI->getParent());
1022
Chris Lattner147af6b2004-04-02 18:13:43 +00001023 // Insert a new select instruction.
Chris Lattner0ed7f422004-09-29 05:43:32 +00001024 Value *NewRetVal;
1025 Value *BrCond = BI->getCondition();
1026 if (TrueValue != FalseValue)
1027 NewRetVal = new SelectInst(BrCond, TrueValue,
1028 FalseValue, "retval", BI);
1029 else
1030 NewRetVal = TrueValue;
1031
Chris Lattner147af6b2004-04-02 18:13:43 +00001032 new ReturnInst(NewRetVal, BI);
1033 BI->getParent()->getInstList().erase(BI);
Chris Lattner0ed7f422004-09-29 05:43:32 +00001034 if (BrCond->use_empty())
1035 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1036 BrCondI->getParent()->getInstList().erase(BrCondI);
Chris Lattner147af6b2004-04-02 18:13:43 +00001037 return true;
1038 }
1039 }
1040 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001041 }
Chris Lattnere14ea082004-02-24 05:54:22 +00001042 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
1043 // Check to see if the first instruction in this block is just an unwind.
1044 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001045 // destination with call instructions, and any unconditional branch
1046 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +00001047 //
1048 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1049 while (!Preds.empty()) {
1050 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001051 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1052 if (BI->isUnconditional()) {
1053 Pred->getInstList().pop_back(); // nuke uncond branch
1054 new UnwindInst(Pred); // Use unwind.
1055 Changed = true;
1056 }
1057 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +00001058 if (II->getUnwindDest() == BB) {
1059 // Insert a new branch instruction before the invoke, because this
1060 // is now a fall through...
1061 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1062 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001063
Chris Lattnere14ea082004-02-24 05:54:22 +00001064 // Insert the call now...
1065 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1066 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1067 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001068 CI->setCallingConv(II->getCallingConv());
Chris Lattnere14ea082004-02-24 05:54:22 +00001069 // If the invoke produced a value, the Call now does instead
1070 II->replaceAllUsesWith(CI);
1071 delete II;
1072 Changed = true;
1073 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001074
Chris Lattnere14ea082004-02-24 05:54:22 +00001075 Preds.pop_back();
1076 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001077
1078 // If this block is now dead, remove it.
1079 if (pred_begin(BB) == pred_end(BB)) {
1080 // We know there are no successors, so just nuke the block.
1081 M->getBasicBlockList().erase(BB);
1082 return true;
1083 }
1084
Chris Lattner623369a2005-02-24 06:17:52 +00001085 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1086 if (isValueEqualityComparison(SI)) {
1087 // If we only have one predecessor, and if it is a branch on this value,
1088 // see if that predecessor totally determines the outcome of this switch.
1089 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1090 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1091 return SimplifyCFG(BB) || 1;
1092
1093 // If the block only contains the switch, see if we can fold the block
1094 // away into any preds.
1095 if (SI == &BB->front())
1096 if (FoldValueComparisonIntoPredecessors(SI))
1097 return SimplifyCFG(BB) || 1;
1098 }
Chris Lattner542f1492004-02-28 21:28:10 +00001099 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001100 if (BI->isUnconditional()) {
1101 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1102 while (isa<PHINode>(*BBI)) ++BBI;
1103
1104 BasicBlock *Succ = BI->getSuccessor(0);
1105 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1106 Succ != BB) // Don't hurt infinite loops!
1107 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1108 return 1;
1109
1110 } else { // Conditional branch
Chris Lattnere67fa052004-05-01 23:35:43 +00001111 if (Value *CompVal = isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001112 // If we only have one predecessor, and if it is a branch on this value,
1113 // see if that predecessor totally determines the outcome of this
1114 // switch.
1115 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1116 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1117 return SimplifyCFG(BB) || 1;
1118
Chris Lattnere67fa052004-05-01 23:35:43 +00001119 // This block must be empty, except for the setcond inst, if it exists.
1120 BasicBlock::iterator I = BB->begin();
1121 if (&*I == BI ||
1122 (&*I == cast<Instruction>(BI->getCondition()) &&
1123 &*++I == BI))
1124 if (FoldValueComparisonIntoPredecessors(BI))
1125 return SimplifyCFG(BB) | true;
1126 }
1127
1128 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1129 // branches to us and one of our successors, fold the setcc into the
1130 // predecessor and use logical operations to pick the right destination.
Chris Lattner12fe2b12004-05-02 05:02:03 +00001131 BasicBlock *TrueDest = BI->getSuccessor(0);
1132 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbdcc0b82004-05-02 05:19:36 +00001133 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattnere67fa052004-05-01 23:35:43 +00001134 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner12fe2b12004-05-02 05:02:03 +00001135 Cond->getNext() == BI && Cond->hasOneUse() &&
1136 TrueDest != BB && FalseDest != BB)
Chris Lattnere67fa052004-05-01 23:35:43 +00001137 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1138 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnera1f79fb2004-05-02 01:00:44 +00001139 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001140 BasicBlock *PredBlock = *PI;
Chris Lattnere67fa052004-05-01 23:35:43 +00001141 if (PBI->getSuccessor(0) == FalseDest ||
1142 PBI->getSuccessor(1) == TrueDest) {
1143 // Invert the predecessors condition test (xor it with true),
1144 // which allows us to write this code once.
1145 Value *NewCond =
1146 BinaryOperator::createNot(PBI->getCondition(),
1147 PBI->getCondition()->getName()+".not", PBI);
1148 PBI->setCondition(NewCond);
1149 BasicBlock *OldTrue = PBI->getSuccessor(0);
1150 BasicBlock *OldFalse = PBI->getSuccessor(1);
1151 PBI->setSuccessor(0, OldFalse);
1152 PBI->setSuccessor(1, OldTrue);
1153 }
1154
1155 if (PBI->getSuccessor(0) == TrueDest ||
1156 PBI->getSuccessor(1) == FalseDest) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001157 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattnere67fa052004-05-01 23:35:43 +00001158 // two conditions together.
1159 Instruction *New = Cond->clone();
1160 New->setName(Cond->getName());
1161 Cond->setName(Cond->getName()+".old");
Chris Lattner2636c1b2004-06-21 07:19:01 +00001162 PredBlock->getInstList().insert(PBI, New);
Chris Lattnere67fa052004-05-01 23:35:43 +00001163 Instruction::BinaryOps Opcode =
1164 PBI->getSuccessor(0) == TrueDest ?
1165 Instruction::Or : Instruction::And;
Misha Brukmanfd939082005-04-21 23:48:37 +00001166 Value *NewCond =
Chris Lattnere67fa052004-05-01 23:35:43 +00001167 BinaryOperator::create(Opcode, PBI->getCondition(),
1168 New, "bothcond", PBI);
1169 PBI->setCondition(NewCond);
1170 if (PBI->getSuccessor(0) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001171 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +00001172 PBI->setSuccessor(0, TrueDest);
1173 }
1174 if (PBI->getSuccessor(1) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001175 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +00001176 PBI->setSuccessor(1, FalseDest);
1177 }
1178 return SimplifyCFG(BB) | 1;
1179 }
1180 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001181
Chris Lattner92da2c22004-05-01 22:36:37 +00001182 // If this block ends with a branch instruction, and if there is one
1183 // predecessor, see if the previous block ended with a branch on the same
1184 // condition, which makes this conditional branch redundant.
Chris Lattner7e663482005-08-03 00:11:16 +00001185 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Chris Lattner92da2c22004-05-01 22:36:37 +00001186 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1187 if (PBI->isConditional() &&
1188 PBI->getCondition() == BI->getCondition() &&
Chris Lattner951fdb92004-05-01 22:41:51 +00001189 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
Chris Lattner92da2c22004-05-01 22:36:37 +00001190 // Okay, the outcome of this conditional branch is statically
1191 // knowable. Delete the outgoing CFG edge that is impossible to
1192 // execute.
1193 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1194 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
1195 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
1196 BB->getInstList().erase(BI);
1197 return SimplifyCFG(BB) | true;
1198 }
Chris Lattnerd52c2612004-02-24 07:23:58 +00001199 }
Chris Lattner698f96f2004-10-18 04:07:22 +00001200 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1201 // If there are any instructions immediately before the unreachable that can
1202 // be removed, do so.
1203 Instruction *Unreachable = BB->getTerminator();
1204 while (Unreachable != BB->begin()) {
1205 BasicBlock::iterator BBI = Unreachable;
1206 --BBI;
1207 if (isa<CallInst>(BBI)) break;
1208 // Delete this instruction
1209 BB->getInstList().erase(BBI);
1210 Changed = true;
1211 }
1212
1213 // If the unreachable instruction is the first in the block, take a gander
1214 // at all of the predecessors of this instruction, and simplify them.
1215 if (&BB->front() == Unreachable) {
1216 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1217 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1218 TerminatorInst *TI = Preds[i]->getTerminator();
1219
1220 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1221 if (BI->isUnconditional()) {
1222 if (BI->getSuccessor(0) == BB) {
1223 new UnreachableInst(TI);
1224 TI->eraseFromParent();
1225 Changed = true;
1226 }
1227 } else {
1228 if (BI->getSuccessor(0) == BB) {
1229 new BranchInst(BI->getSuccessor(1), BI);
1230 BI->eraseFromParent();
1231 } else if (BI->getSuccessor(1) == BB) {
1232 new BranchInst(BI->getSuccessor(0), BI);
1233 BI->eraseFromParent();
1234 Changed = true;
1235 }
1236 }
1237 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1238 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1239 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00001240 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00001241 SI->removeCase(i);
1242 --i; --e;
1243 Changed = true;
1244 }
1245 // If the default value is unreachable, figure out the most popular
1246 // destination and make it the default.
1247 if (SI->getSuccessor(0) == BB) {
1248 std::map<BasicBlock*, unsigned> Popularity;
1249 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1250 Popularity[SI->getSuccessor(i)]++;
1251
1252 // Find the most popular block.
1253 unsigned MaxPop = 0;
1254 BasicBlock *MaxBlock = 0;
1255 for (std::map<BasicBlock*, unsigned>::iterator
1256 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1257 if (I->second > MaxPop) {
1258 MaxPop = I->second;
1259 MaxBlock = I->first;
1260 }
1261 }
1262 if (MaxBlock) {
1263 // Make this the new default, allowing us to delete any explicit
1264 // edges to it.
1265 SI->setSuccessor(0, MaxBlock);
1266 Changed = true;
1267
Chris Lattner42eb7522005-05-20 22:19:54 +00001268 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1269 // it.
1270 if (isa<PHINode>(MaxBlock->begin()))
1271 for (unsigned i = 0; i != MaxPop-1; ++i)
1272 MaxBlock->removePredecessor(SI->getParent());
1273
Chris Lattner698f96f2004-10-18 04:07:22 +00001274 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1275 if (SI->getSuccessor(i) == MaxBlock) {
1276 SI->removeCase(i);
1277 --i; --e;
1278 }
1279 }
1280 }
1281 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1282 if (II->getUnwindDest() == BB) {
1283 // Convert the invoke to a call instruction. This would be a good
1284 // place to note that the call does not throw though.
1285 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1286 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001287
Chris Lattner698f96f2004-10-18 04:07:22 +00001288 // Insert the call now...
1289 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1290 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1291 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001292 CI->setCallingConv(II->getCallingConv());
Chris Lattner698f96f2004-10-18 04:07:22 +00001293 // If the invoke produced a value, the Call does now instead.
1294 II->replaceAllUsesWith(CI);
1295 delete II;
1296 Changed = true;
1297 }
1298 }
1299 }
1300
1301 // If this block is now dead, remove it.
1302 if (pred_begin(BB) == pred_end(BB)) {
1303 // We know there are no successors, so just nuke the block.
1304 M->getBasicBlockList().erase(BB);
1305 return true;
1306 }
1307 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001308 }
1309
Chris Lattner01d1ee32002-05-21 20:50:24 +00001310 // Merge basic blocks into their predecessor if there is only one distinct
1311 // pred, and if there is only one distinct successor of the predecessor, and
1312 // if there are no PHI nodes.
1313 //
Chris Lattner2355f942004-02-11 01:17:07 +00001314 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1315 BasicBlock *OnlyPred = *PI++;
1316 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1317 if (*PI != OnlyPred) {
1318 OnlyPred = 0; // There are multiple different predecessors...
1319 break;
1320 }
Chris Lattner92da2c22004-05-01 22:36:37 +00001321
Chris Lattner2355f942004-02-11 01:17:07 +00001322 BasicBlock *OnlySucc = 0;
1323 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1324 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1325 // Check to see if there is only one distinct successor...
1326 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1327 OnlySucc = BB;
1328 for (; SI != SE; ++SI)
1329 if (*SI != OnlySucc) {
1330 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner01d1ee32002-05-21 20:50:24 +00001331 break;
1332 }
Chris Lattner2355f942004-02-11 01:17:07 +00001333 }
1334
1335 if (OnlySucc) {
Chris Lattner30b43442004-07-15 02:06:12 +00001336 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
Chris Lattner2355f942004-02-11 01:17:07 +00001337 TerminatorInst *Term = OnlyPred->getTerminator();
1338
1339 // Resolve any PHI nodes at the start of the block. They are all
1340 // guaranteed to have exactly one entry if they exist, unless there are
1341 // multiple duplicate (but guaranteed to be equal) entries for the
1342 // incoming edges. This occurs when there are multiple edges from
1343 // OnlyPred to OnlySucc.
1344 //
1345 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1346 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1347 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner01d1ee32002-05-21 20:50:24 +00001348 }
1349
Chris Lattner2355f942004-02-11 01:17:07 +00001350 // Delete the unconditional branch from the predecessor...
1351 OnlyPred->getInstList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001352
Chris Lattner2355f942004-02-11 01:17:07 +00001353 // Move all definitions in the successor to the predecessor...
1354 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Misha Brukmanfd939082005-04-21 23:48:37 +00001355
Chris Lattner2355f942004-02-11 01:17:07 +00001356 // Make all PHI nodes that referred to BB now refer to Pred as their
1357 // source...
1358 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +00001359
Chris Lattner2355f942004-02-11 01:17:07 +00001360 std::string OldName = BB->getName();
Chris Lattner18961502002-06-25 16:12:52 +00001361
Misha Brukmanfd939082005-04-21 23:48:37 +00001362 // Erase basic block from the function...
Chris Lattner2355f942004-02-11 01:17:07 +00001363 M->getBasicBlockList().erase(BB);
Chris Lattner18961502002-06-25 16:12:52 +00001364
Chris Lattner2355f942004-02-11 01:17:07 +00001365 // Inherit predecessors name if it exists...
1366 if (!OldName.empty() && !OnlyPred->hasName())
1367 OnlyPred->setName(OldName);
Misha Brukmanfd939082005-04-21 23:48:37 +00001368
Chris Lattner2355f942004-02-11 01:17:07 +00001369 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001370 }
Chris Lattner723c66d2004-02-11 03:36:04 +00001371
Chris Lattner37dc9382004-11-30 00:29:14 +00001372 // Otherwise, if this block only has a single predecessor, and if that block
1373 // is a conditional branch, see if we can hoist any code from this block up
1374 // into our predecessor.
1375 if (OnlyPred)
Chris Lattner76134372004-12-10 17:42:31 +00001376 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1377 if (BI->isConditional()) {
1378 // Get the other block.
1379 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1380 PI = pred_begin(OtherBB);
1381 ++PI;
1382 if (PI == pred_end(OtherBB)) {
1383 // We have a conditional branch to two blocks that are only reachable
1384 // from the condbr. We know that the condbr dominates the two blocks,
1385 // so see if there is any identical code in the "then" and "else"
1386 // blocks. If so, we can hoist it up to the branching block.
1387 Changed |= HoistThenElseCodeToIf(BI);
1388 }
Chris Lattner37dc9382004-11-30 00:29:14 +00001389 }
Chris Lattner37dc9382004-11-30 00:29:14 +00001390
Chris Lattner0d560082004-02-24 05:38:11 +00001391 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1392 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1393 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1394 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1395 Instruction *Cond = cast<Instruction>(BI->getCondition());
1396 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1397 // 'setne's and'ed together, collect them.
1398 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +00001399 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +00001400 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1401 if (CompVal && CompVal->getType()->isInteger()) {
1402 // There might be duplicate constants in the list, which the switch
1403 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +00001404 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +00001405 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanfd939082005-04-21 23:48:37 +00001406
Chris Lattner0d560082004-02-24 05:38:11 +00001407 // Figure out which block is which destination.
1408 BasicBlock *DefaultBB = BI->getSuccessor(1);
1409 BasicBlock *EdgeBB = BI->getSuccessor(0);
1410 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00001411
Chris Lattner0d560082004-02-24 05:38:11 +00001412 // Create the new switch instruction now.
Chris Lattner37880592005-01-29 00:38:26 +00001413 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001414
Chris Lattner0d560082004-02-24 05:38:11 +00001415 // Add all of the 'cases' to the switch instruction.
1416 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1417 New->addCase(Values[i], EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00001418
Chris Lattner0d560082004-02-24 05:38:11 +00001419 // We added edges from PI to the EdgeBB. As such, if there were any
1420 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1421 // the number of edges added.
1422 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +00001423 isa<PHINode>(BBI); ++BBI) {
1424 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner0d560082004-02-24 05:38:11 +00001425 Value *InVal = PN->getIncomingValueForBlock(*PI);
1426 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1427 PN->addIncoming(InVal, *PI);
1428 }
1429
1430 // Erase the old branch instruction.
1431 (*PI)->getInstList().erase(BI);
1432
1433 // Erase the potentially condition tree that was used to computed the
1434 // branch condition.
1435 ErasePossiblyDeadInstructionTree(Cond);
1436 return true;
1437 }
1438 }
1439
Chris Lattner723c66d2004-02-11 03:36:04 +00001440 // If there is a trivial two-entry PHI node in this basic block, and we can
1441 // eliminate it, do so now.
1442 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1443 if (PN->getNumIncomingValues() == 2) {
1444 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1445 // statement", which has a very simple dominance structure. Basically, we
1446 // are trying to find the condition that is being branched on, which
1447 // subsequently causes this merge to happen. We really want control
1448 // dependence information for this check, but simplifycfg can't keep it up
1449 // to date, and this catches most of the cases we care about anyway.
1450 //
1451 BasicBlock *IfTrue, *IfFalse;
1452 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
Chris Lattner218a8222004-06-20 01:13:18 +00001453 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1454 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattner723c66d2004-02-11 03:36:04 +00001455
Chris Lattner9c078662004-10-14 05:13:36 +00001456 // Loop over the PHI's seeing if we can promote them all to select
1457 // instructions. While we are at it, keep track of the instructions
1458 // that need to be moved to the dominating block.
1459 std::set<Instruction*> AggressiveInsts;
1460 bool CanPromote = true;
1461
Chris Lattner723c66d2004-02-11 03:36:04 +00001462 BasicBlock::iterator AfterPHIIt = BB->begin();
Chris Lattner9c078662004-10-14 05:13:36 +00001463 while (isa<PHINode>(AfterPHIIt)) {
1464 PHINode *PN = cast<PHINode>(AfterPHIIt++);
Chris Lattner02899292005-06-17 01:45:53 +00001465 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1466 if (PN->getIncomingValue(0) != PN)
1467 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1468 else
1469 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1470 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1471 &AggressiveInsts) ||
1472 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1473 &AggressiveInsts)) {
Chris Lattner9c078662004-10-14 05:13:36 +00001474 CanPromote = false;
1475 break;
1476 }
1477 }
Chris Lattner723c66d2004-02-11 03:36:04 +00001478
Chris Lattner9c078662004-10-14 05:13:36 +00001479 // Did we eliminate all PHI's?
1480 CanPromote |= AfterPHIIt == BB->begin();
Chris Lattner723c66d2004-02-11 03:36:04 +00001481
Chris Lattner9c078662004-10-14 05:13:36 +00001482 // If we all PHI nodes are promotable, check to make sure that all
1483 // instructions in the predecessor blocks can be promoted as well. If
1484 // not, we won't be able to get rid of the control flow, so it's not
1485 // worth promoting to select instructions.
Reid Spencer4e073a82004-10-22 16:10:39 +00001486 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
Chris Lattner9c078662004-10-14 05:13:36 +00001487 if (CanPromote) {
1488 PN = cast<PHINode>(BB->begin());
1489 BasicBlock *Pred = PN->getIncomingBlock(0);
1490 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1491 IfBlock1 = Pred;
1492 DomBlock = *pred_begin(Pred);
1493 for (BasicBlock::iterator I = Pred->begin();
1494 !isa<TerminatorInst>(I); ++I)
1495 if (!AggressiveInsts.count(I)) {
1496 // This is not an aggressive instruction that we can promote.
1497 // Because of this, we won't be able to get rid of the control
1498 // flow, so the xform is not worth it.
1499 CanPromote = false;
1500 break;
1501 }
1502 }
1503
1504 Pred = PN->getIncomingBlock(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00001505 if (CanPromote &&
Chris Lattner9c078662004-10-14 05:13:36 +00001506 cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1507 IfBlock2 = Pred;
1508 DomBlock = *pred_begin(Pred);
1509 for (BasicBlock::iterator I = Pred->begin();
1510 !isa<TerminatorInst>(I); ++I)
1511 if (!AggressiveInsts.count(I)) {
1512 // This is not an aggressive instruction that we can promote.
1513 // Because of this, we won't be able to get rid of the control
1514 // flow, so the xform is not worth it.
1515 CanPromote = false;
1516 break;
1517 }
1518 }
1519 }
1520
1521 // If we can still promote the PHI nodes after this gauntlet of tests,
1522 // do all of the PHI's now.
1523 if (CanPromote) {
1524 // Move all 'aggressive' instructions, which are defined in the
1525 // conditional parts of the if's up to the dominating block.
1526 if (IfBlock1) {
1527 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1528 IfBlock1->getInstList(),
1529 IfBlock1->begin(),
1530 IfBlock1->getTerminator());
1531 }
1532 if (IfBlock2) {
1533 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1534 IfBlock2->getInstList(),
1535 IfBlock2->begin(),
1536 IfBlock2->getTerminator());
1537 }
1538
1539 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1540 // Change the PHI node into a select instruction.
Chris Lattner723c66d2004-02-11 03:36:04 +00001541 Value *TrueVal =
1542 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1543 Value *FalseVal =
1544 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1545
Chris Lattner552112f2004-03-30 19:44:05 +00001546 std::string Name = PN->getName(); PN->setName("");
1547 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
Chris Lattner9c078662004-10-14 05:13:36 +00001548 Name, AfterPHIIt));
Chris Lattner552112f2004-03-30 19:44:05 +00001549 BB->getInstList().erase(PN);
Chris Lattner723c66d2004-02-11 03:36:04 +00001550 }
Chris Lattner9c078662004-10-14 05:13:36 +00001551 Changed = true;
Chris Lattner723c66d2004-02-11 03:36:04 +00001552 }
1553 }
1554 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001555
Chris Lattner694e37f2003-08-17 19:41:53 +00001556 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001557}