blob: 742efe6184420fc3ec657fa4ca59d036ca7d800a [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 Lattner2bdcb562005-08-03 00:19:45 +000027/// SafeToMergeTerminators - Return true if it is safe to merge these two
28/// terminator instructions together.
29///
30static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
31 if (SI1 == SI2) return false; // Can't merge with self!
32
33 // It is not safe to merge these two switch instructions if they have a common
34 // successor, and if that successor has a PHI node, and if *that* PHI node has
35 // conflicting incoming values from the two switch blocks.
36 BasicBlock *SI1BB = SI1->getParent();
37 BasicBlock *SI2BB = SI2->getParent();
38 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
39
40 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
41 if (SI1Succs.count(*I))
42 for (BasicBlock::iterator BBI = (*I)->begin();
43 isa<PHINode>(BBI); ++BBI) {
44 PHINode *PN = cast<PHINode>(BBI);
45 if (PN->getIncomingValueForBlock(SI1BB) !=
46 PN->getIncomingValueForBlock(SI2BB))
47 return false;
48 }
49
50 return true;
51}
52
53/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
54/// now be entries in it from the 'NewPred' block. The values that will be
55/// flowing into the PHI nodes will be the same as those coming in from
56/// ExistPred, an existing predecessor of Succ.
57static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
58 BasicBlock *ExistPred) {
59 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
60 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
61 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
62
63 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
64 PHINode *PN = cast<PHINode>(I);
65 Value *V = PN->getIncomingValueForBlock(ExistPred);
66 PN->addIncoming(V, NewPred);
67 }
68}
69
Chris Lattner3b3efc72005-08-03 00:29:26 +000070// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
71// almost-empty BB ending in an unconditional branch to Succ, into succ.
Chris Lattner01d1ee32002-05-21 20:50:24 +000072//
73// Assumption: Succ is the single successor for BB.
74//
Chris Lattner3b3efc72005-08-03 00:29:26 +000075static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner01d1ee32002-05-21 20:50:24 +000076 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattner3abb95d2002-09-24 00:09:26 +000077
Chris Lattner01d1ee32002-05-21 20:50:24 +000078 // Check to see if one of the predecessors of BB is already a predecessor of
Chris Lattnere2ca5402003-03-05 21:01:52 +000079 // Succ. If so, we cannot do the transformation if there are any PHI nodes
80 // with incompatible values coming in from the two edges!
Chris Lattner01d1ee32002-05-21 20:50:24 +000081 //
Chris Lattnerdc88dbe2005-08-03 00:38:27 +000082 if (isa<PHINode>(Succ->front())) {
83 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
84 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);\
85 PI != PE; ++PI)
86 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
87 // Loop over all of the PHI nodes checking to see if there are
88 // incompatible values coming in.
89 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
90 PHINode *PN = cast<PHINode>(I);
91 // Loop up the entries in the PHI node for BB and for *PI if the
92 // values coming in are non-equal, we cannot merge these two blocks
93 // (instead we should insert a conditional move or something, then
94 // merge the blocks).
95 if (PN->getIncomingValueForBlock(BB) !=
96 PN->getIncomingValueForBlock(*PI))
97 return false; // Values are not equal...
98 }
99 }
100 }
Chris Lattner1aad9212005-08-03 00:59:12 +0000101
102 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
103 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
104 // fold these blocks, as we don't know whether BB dominates Succ or not to
105 // update the PHI nodes correctly.
106 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000107
Chris Lattner1aad9212005-08-03 00:59:12 +0000108 // If the predecessors of Succ are only BB and Succ itself, we can handle this.
109 bool IsSafe = true;
110 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
111 if (*PI != Succ && *PI != BB) {
112 IsSafe = false;
113 break;
114 }
115 if (IsSafe) return true;
116
117 // If the PHI nodes in BB are only used by instructions in Succ, we are ok.
118 IsSafe = true;
119 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I) && IsSafe; ++I) {
120 PHINode *PN = cast<PHINode>(I);
121 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
122 ++UI)
123 if (cast<Instruction>(*UI)->getParent() != Succ) {
124 IsSafe = false;
125 break;
126 }
127 }
128
129 return IsSafe;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000130}
131
Chris Lattner7e663482005-08-03 00:11:16 +0000132/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
133/// branch to Succ, and contains no instructions other than PHI nodes and the
134/// branch. If possible, eliminate BB.
135static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
136 BasicBlock *Succ) {
137 // If our successor has PHI nodes, then we need to update them to include
138 // entries for BB's predecessors, not for BB itself. Be careful though,
139 // if this transformation fails (returns true) then we cannot do this
140 // transformation!
141 //
Chris Lattner3b3efc72005-08-03 00:29:26 +0000142 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
Chris Lattner7e663482005-08-03 00:11:16 +0000143
144 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
145
Chris Lattner3b3efc72005-08-03 00:29:26 +0000146 if (isa<PHINode>(Succ->begin())) {
147 // If there is more than one pred of succ, and there are PHI nodes in
148 // the successor, then we need to add incoming edges for the PHI nodes
149 //
150 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
151
152 // Loop over all of the PHI nodes in the successor of BB.
153 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
154 PHINode *PN = cast<PHINode>(I);
155 Value *OldVal = PN->removeIncomingValue(BB, false);
156 assert(OldVal && "No entry in PHI for Pred BB!");
157
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000158 // If this incoming value is one of the PHI nodes in BB, the new entries
159 // in the PHI node are the entries from the old PHI.
Chris Lattner3b3efc72005-08-03 00:29:26 +0000160 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
161 PHINode *OldValPN = cast<PHINode>(OldVal);
162 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
163 PN->addIncoming(OldValPN->getIncomingValue(i),
164 OldValPN->getIncomingBlock(i));
165 } else {
166 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
167 End = BBPreds.end(); PredI != End; ++PredI) {
168 // Add an incoming value for each of the new incoming values...
169 PN->addIncoming(OldVal, *PredI);
170 }
171 }
172 }
173 }
174
Chris Lattner7e663482005-08-03 00:11:16 +0000175 if (isa<PHINode>(&BB->front())) {
176 std::vector<BasicBlock*>
177 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
178
179 // Move all PHI nodes in BB to Succ if they are alive, otherwise
180 // delete them.
181 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
Chris Lattnerdc88dbe2005-08-03 00:38:27 +0000182 if (PN->use_empty()) {
183 // Just remove the dead phi. This happens if Succ's PHIs were the only
184 // users of the PHI nodes.
185 PN->eraseFromParent();
Chris Lattner7e663482005-08-03 00:11:16 +0000186 } else {
187 // The instruction is alive, so this means that Succ must have
188 // *ONLY* had BB as a predecessor, and the PHI node is still valid
189 // now. Simply move it into Succ, because we know that BB
190 // strictly dominated Succ.
Chris Lattnerd423b8b2005-08-03 00:23:42 +0000191 Succ->getInstList().splice(Succ->begin(),
192 BB->getInstList(), BB->begin());
Chris Lattner7e663482005-08-03 00:11:16 +0000193
194 // We need to add new entries for the PHI node to account for
195 // predecessors of Succ that the PHI node does not take into
196 // account. At this point, since we know that BB dominated succ,
197 // this means that we should any newly added incoming edges should
198 // use the PHI node as the value for these edges, because they are
199 // loop back edges.
200 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
201 if (OldSuccPreds[i] != BB)
202 PN->addIncoming(PN, OldSuccPreds[i]);
203 }
204 }
205
206 // Everything that jumped to BB now goes to Succ.
207 std::string OldName = BB->getName();
208 BB->replaceAllUsesWith(Succ);
209 BB->eraseFromParent(); // Delete the old basic block.
210
211 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
212 Succ->setName(OldName);
213 return true;
214}
215
Chris Lattner723c66d2004-02-11 03:36:04 +0000216/// GetIfCondition - Given a basic block (BB) with two predecessors (and
217/// presumably PHI nodes in it), check to see if the merge at this block is due
218/// to an "if condition". If so, return the boolean condition that determines
219/// which entry into BB will be taken. Also, return by references the block
220/// that will be entered from if the condition is true, and the block that will
221/// be entered if the condition is false.
Misha Brukmanfd939082005-04-21 23:48:37 +0000222///
Chris Lattner723c66d2004-02-11 03:36:04 +0000223///
224static Value *GetIfCondition(BasicBlock *BB,
225 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
226 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
227 "Function can only handle blocks with 2 predecessors!");
228 BasicBlock *Pred1 = *pred_begin(BB);
229 BasicBlock *Pred2 = *++pred_begin(BB);
230
231 // We can only handle branches. Other control flow will be lowered to
232 // branches if possible anyway.
233 if (!isa<BranchInst>(Pred1->getTerminator()) ||
234 !isa<BranchInst>(Pred2->getTerminator()))
235 return 0;
236 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
237 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
238
239 // Eliminate code duplication by ensuring that Pred1Br is conditional if
240 // either are.
241 if (Pred2Br->isConditional()) {
242 // If both branches are conditional, we don't have an "if statement". In
243 // reality, we could transform this case, but since the condition will be
244 // required anyway, we stand no chance of eliminating it, so the xform is
245 // probably not profitable.
246 if (Pred1Br->isConditional())
247 return 0;
248
249 std::swap(Pred1, Pred2);
250 std::swap(Pred1Br, Pred2Br);
251 }
252
253 if (Pred1Br->isConditional()) {
254 // If we found a conditional branch predecessor, make sure that it branches
255 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
256 if (Pred1Br->getSuccessor(0) == BB &&
257 Pred1Br->getSuccessor(1) == Pred2) {
258 IfTrue = Pred1;
259 IfFalse = Pred2;
260 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
261 Pred1Br->getSuccessor(1) == BB) {
262 IfTrue = Pred2;
263 IfFalse = Pred1;
264 } else {
265 // We know that one arm of the conditional goes to BB, so the other must
266 // go somewhere unrelated, and this must not be an "if statement".
267 return 0;
268 }
269
270 // The only thing we have to watch out for here is to make sure that Pred2
271 // doesn't have incoming edges from other blocks. If it does, the condition
272 // doesn't dominate BB.
273 if (++pred_begin(Pred2) != pred_end(Pred2))
274 return 0;
275
276 return Pred1Br->getCondition();
277 }
278
279 // Ok, if we got here, both predecessors end with an unconditional branch to
280 // BB. Don't panic! If both blocks only have a single (identical)
281 // predecessor, and THAT is a conditional branch, then we're all ok!
282 if (pred_begin(Pred1) == pred_end(Pred1) ||
283 ++pred_begin(Pred1) != pred_end(Pred1) ||
284 pred_begin(Pred2) == pred_end(Pred2) ||
285 ++pred_begin(Pred2) != pred_end(Pred2) ||
286 *pred_begin(Pred1) != *pred_begin(Pred2))
287 return 0;
288
289 // Otherwise, if this is a conditional branch, then we can use it!
290 BasicBlock *CommonPred = *pred_begin(Pred1);
291 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
292 assert(BI->isConditional() && "Two successors but not conditional?");
293 if (BI->getSuccessor(0) == Pred1) {
294 IfTrue = Pred1;
295 IfFalse = Pred2;
296 } else {
297 IfTrue = Pred2;
298 IfFalse = Pred1;
299 }
300 return BI->getCondition();
301 }
302 return 0;
303}
304
305
306// If we have a merge point of an "if condition" as accepted above, return true
307// if the specified value dominates the block. We don't handle the true
308// generality of domination here, just a special case which works well enough
309// for us.
Chris Lattner9c078662004-10-14 05:13:36 +0000310//
311// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
312// see if V (which must be an instruction) is cheap to compute and is
313// non-trapping. If both are true, the instruction is inserted into the set and
314// true is returned.
315static bool DominatesMergePoint(Value *V, BasicBlock *BB,
316 std::set<Instruction*> *AggressiveInsts) {
Chris Lattner570751c2004-04-09 22:50:22 +0000317 Instruction *I = dyn_cast<Instruction>(V);
318 if (!I) return true; // Non-instructions all dominate instructions.
319 BasicBlock *PBB = I->getParent();
Chris Lattner723c66d2004-02-11 03:36:04 +0000320
Chris Lattnerda895d62005-02-27 06:18:25 +0000321 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner570751c2004-04-09 22:50:22 +0000322 // the bottom of this block.
323 if (PBB == BB) return false;
Chris Lattner723c66d2004-02-11 03:36:04 +0000324
Chris Lattner570751c2004-04-09 22:50:22 +0000325 // If this instruction is defined in a block that contains an unconditional
326 // branch to BB, then it must be in the 'conditional' part of the "if
327 // statement".
328 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
329 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
Chris Lattner9c078662004-10-14 05:13:36 +0000330 if (!AggressiveInsts) return false;
Chris Lattner570751c2004-04-09 22:50:22 +0000331 // Okay, it looks like the instruction IS in the "condition". Check to
332 // see if its a cheap instruction to unconditionally compute, and if it
333 // only uses stuff defined outside of the condition. If so, hoist it out.
334 switch (I->getOpcode()) {
335 default: return false; // Cannot hoist this out safely.
336 case Instruction::Load:
337 // We can hoist loads that are non-volatile and obviously cannot trap.
338 if (cast<LoadInst>(I)->isVolatile())
339 return false;
340 if (!isa<AllocaInst>(I->getOperand(0)) &&
Reid Spencer460f16c2004-07-18 00:32:14 +0000341 !isa<Constant>(I->getOperand(0)))
Chris Lattner570751c2004-04-09 22:50:22 +0000342 return false;
343
344 // Finally, we have to check to make sure there are no instructions
345 // before the load in its basic block, as we are going to hoist the loop
346 // out to its predecessor.
347 if (PBB->begin() != BasicBlock::iterator(I))
348 return false;
349 break;
350 case Instruction::Add:
351 case Instruction::Sub:
352 case Instruction::And:
353 case Instruction::Or:
354 case Instruction::Xor:
355 case Instruction::Shl:
356 case Instruction::Shr:
Chris Lattnerbf5d4fb2005-04-21 05:31:13 +0000357 case Instruction::SetEQ:
358 case Instruction::SetNE:
359 case Instruction::SetLT:
360 case Instruction::SetGT:
361 case Instruction::SetLE:
362 case Instruction::SetGE:
Chris Lattner570751c2004-04-09 22:50:22 +0000363 break; // These are all cheap and non-trapping instructions.
364 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000365
Chris Lattner570751c2004-04-09 22:50:22 +0000366 // Okay, we can only really hoist these out if their operands are not
367 // defined in the conditional region.
368 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Chris Lattner9c078662004-10-14 05:13:36 +0000369 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
Chris Lattner570751c2004-04-09 22:50:22 +0000370 return false;
Chris Lattner9c078662004-10-14 05:13:36 +0000371 // Okay, it's safe to do this! Remember this instruction.
372 AggressiveInsts->insert(I);
Chris Lattner570751c2004-04-09 22:50:22 +0000373 }
374
Chris Lattner723c66d2004-02-11 03:36:04 +0000375 return true;
376}
Chris Lattner01d1ee32002-05-21 20:50:24 +0000377
Chris Lattner0d560082004-02-24 05:38:11 +0000378// GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
379// instructions that compare a value against a constant, return the value being
380// compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000381static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000382 if (Instruction *Inst = dyn_cast<Instruction>(V))
383 if (Inst->getOpcode() == Instruction::SetEQ) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000384 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000385 Values.push_back(C);
386 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000387 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000388 Values.push_back(C);
389 return Inst->getOperand(1);
390 }
391 } else if (Inst->getOpcode() == Instruction::Or) {
392 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
393 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
394 if (LHS == RHS)
395 return LHS;
396 }
397 return 0;
398}
399
400// GatherConstantSetNEs - Given a potentially 'and'd together collection of
401// setne instructions that compare a value against a constant, return the value
402// being compared, and stick the constant into the Values vector.
Chris Lattner1654cff2004-06-19 07:02:14 +0000403static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
Chris Lattner0d560082004-02-24 05:38:11 +0000404 if (Instruction *Inst = dyn_cast<Instruction>(V))
405 if (Inst->getOpcode() == Instruction::SetNE) {
Chris Lattner1654cff2004-06-19 07:02:14 +0000406 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000407 Values.push_back(C);
408 return Inst->getOperand(0);
Chris Lattner1654cff2004-06-19 07:02:14 +0000409 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
Chris Lattner0d560082004-02-24 05:38:11 +0000410 Values.push_back(C);
411 return Inst->getOperand(1);
412 }
413 } else if (Inst->getOpcode() == Instruction::Cast) {
414 // Cast of X to bool is really a comparison against zero.
415 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
Chris Lattner1654cff2004-06-19 07:02:14 +0000416 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
Chris Lattner0d560082004-02-24 05:38:11 +0000417 return Inst->getOperand(0);
418 } else if (Inst->getOpcode() == Instruction::And) {
419 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
420 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
421 if (LHS == RHS)
422 return LHS;
423 }
424 return 0;
425}
426
427
428
429/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
430/// bunch of comparisons of one value against constants, return the value and
431/// the constants being compared.
432static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
Chris Lattner1654cff2004-06-19 07:02:14 +0000433 std::vector<ConstantInt*> &Values) {
Chris Lattner0d560082004-02-24 05:38:11 +0000434 if (Cond->getOpcode() == Instruction::Or) {
435 CompVal = GatherConstantSetEQs(Cond, Values);
436
437 // Return true to indicate that the condition is true if the CompVal is
438 // equal to one of the constants.
439 return true;
440 } else if (Cond->getOpcode() == Instruction::And) {
441 CompVal = GatherConstantSetNEs(Cond, Values);
Misha Brukmanfd939082005-04-21 23:48:37 +0000442
Chris Lattner0d560082004-02-24 05:38:11 +0000443 // Return false to indicate that the condition is false if the CompVal is
444 // equal to one of the constants.
445 return false;
446 }
447 return false;
448}
449
450/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
451/// has no side effects, nuke it. If it uses any instructions that become dead
452/// because the instruction is now gone, nuke them too.
453static void ErasePossiblyDeadInstructionTree(Instruction *I) {
454 if (isInstructionTriviallyDead(I)) {
455 std::vector<Value*> Operands(I->op_begin(), I->op_end());
456 I->getParent()->getInstList().erase(I);
457 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
458 if (Instruction *OpI = dyn_cast<Instruction>(Operands[i]))
459 ErasePossiblyDeadInstructionTree(OpI);
460 }
461}
462
Chris Lattner542f1492004-02-28 21:28:10 +0000463// isValueEqualityComparison - Return true if the specified terminator checks to
464// see if a value is equal to constant integer value.
465static Value *isValueEqualityComparison(TerminatorInst *TI) {
Chris Lattner4bebf082004-03-16 19:45:22 +0000466 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
467 // Do not permit merging of large switch instructions into their
468 // predecessors unless there is only one predecessor.
469 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
470 pred_end(SI->getParent())) > 128)
471 return 0;
472
Chris Lattner542f1492004-02-28 21:28:10 +0000473 return SI->getCondition();
Chris Lattner4bebf082004-03-16 19:45:22 +0000474 }
Chris Lattner542f1492004-02-28 21:28:10 +0000475 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
476 if (BI->isConditional() && BI->getCondition()->hasOneUse())
477 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
478 if ((SCI->getOpcode() == Instruction::SetEQ ||
Misha Brukmanfd939082005-04-21 23:48:37 +0000479 SCI->getOpcode() == Instruction::SetNE) &&
Chris Lattner542f1492004-02-28 21:28:10 +0000480 isa<ConstantInt>(SCI->getOperand(1)))
481 return SCI->getOperand(0);
482 return 0;
483}
484
485// Given a value comparison instruction, decode all of the 'cases' that it
486// represents and return the 'default' block.
487static BasicBlock *
Misha Brukmanfd939082005-04-21 23:48:37 +0000488GetValueEqualityComparisonCases(TerminatorInst *TI,
Chris Lattner542f1492004-02-28 21:28:10 +0000489 std::vector<std::pair<ConstantInt*,
490 BasicBlock*> > &Cases) {
491 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
492 Cases.reserve(SI->getNumCases());
493 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
Chris Lattnerbe54dcc2005-02-26 18:33:28 +0000494 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
Chris Lattner542f1492004-02-28 21:28:10 +0000495 return SI->getDefaultDest();
496 }
497
498 BranchInst *BI = cast<BranchInst>(TI);
499 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
500 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
501 BI->getSuccessor(SCI->getOpcode() ==
502 Instruction::SetNE)));
503 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
504}
505
506
Chris Lattner623369a2005-02-24 06:17:52 +0000507// EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
508// in the list that match the specified block.
Misha Brukmanfd939082005-04-21 23:48:37 +0000509static void EliminateBlockCases(BasicBlock *BB,
Chris Lattner623369a2005-02-24 06:17:52 +0000510 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
511 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
512 if (Cases[i].second == BB) {
513 Cases.erase(Cases.begin()+i);
514 --i; --e;
515 }
516}
517
518// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
519// well.
520static bool
521ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
522 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
523 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
524
525 // Make V1 be smaller than V2.
526 if (V1->size() > V2->size())
527 std::swap(V1, V2);
528
529 if (V1->size() == 0) return false;
530 if (V1->size() == 1) {
531 // Just scan V2.
532 ConstantInt *TheVal = (*V1)[0].first;
533 for (unsigned i = 0, e = V2->size(); i != e; ++i)
534 if (TheVal == (*V2)[i].first)
535 return true;
536 }
537
538 // Otherwise, just sort both lists and compare element by element.
539 std::sort(V1->begin(), V1->end());
540 std::sort(V2->begin(), V2->end());
541 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
542 while (i1 != e1 && i2 != e2) {
543 if ((*V1)[i1].first == (*V2)[i2].first)
544 return true;
545 if ((*V1)[i1].first < (*V2)[i2].first)
546 ++i1;
547 else
548 ++i2;
549 }
550 return false;
551}
552
553// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
554// terminator instruction and its block is known to only have a single
555// predecessor block, check to see if that predecessor is also a value
556// comparison with the same value, and if that comparison determines the outcome
557// of this comparison. If so, simplify TI. This does a very limited form of
558// jump threading.
559static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
560 BasicBlock *Pred) {
561 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
562 if (!PredVal) return false; // Not a value comparison in predecessor.
563
564 Value *ThisVal = isValueEqualityComparison(TI);
565 assert(ThisVal && "This isn't a value comparison!!");
566 if (ThisVal != PredVal) return false; // Different predicates.
567
568 // Find out information about when control will move from Pred to TI's block.
569 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
570 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
571 PredCases);
572 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanfd939082005-04-21 23:48:37 +0000573
Chris Lattner623369a2005-02-24 06:17:52 +0000574 // Find information about how control leaves this block.
575 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
576 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
577 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
578
579 // If TI's block is the default block from Pred's comparison, potentially
580 // simplify TI based on this knowledge.
581 if (PredDef == TI->getParent()) {
582 // If we are here, we know that the value is none of those cases listed in
583 // PredCases. If there are any cases in ThisCases that are in PredCases, we
584 // can simplify TI.
585 if (ValuesOverlap(PredCases, ThisCases)) {
586 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
587 // Okay, one of the successors of this condbr is dead. Convert it to a
588 // uncond br.
589 assert(ThisCases.size() == 1 && "Branch can only have one case!");
590 Value *Cond = BTI->getCondition();
591 // Insert the new branch.
592 Instruction *NI = new BranchInst(ThisDef, TI);
593
594 // Remove PHI node entries for the dead edge.
595 ThisCases[0].second->removePredecessor(TI->getParent());
596
597 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
598 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
599
600 TI->eraseFromParent(); // Nuke the old one.
601 // If condition is now dead, nuke it.
602 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
603 ErasePossiblyDeadInstructionTree(CondI);
604 return true;
605
606 } else {
607 SwitchInst *SI = cast<SwitchInst>(TI);
608 // Okay, TI has cases that are statically dead, prune them away.
609 std::set<Constant*> DeadCases;
610 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
611 DeadCases.insert(PredCases[i].first);
612
613 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
614 << "Through successor TI: " << *TI);
615
616 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
617 if (DeadCases.count(SI->getCaseValue(i))) {
618 SI->getSuccessor(i)->removePredecessor(TI->getParent());
619 SI->removeCase(i);
620 }
621
622 DEBUG(std::cerr << "Leaving: " << *TI << "\n");
623 return true;
624 }
625 }
626
627 } else {
628 // Otherwise, TI's block must correspond to some matched value. Find out
629 // which value (or set of values) this is.
630 ConstantInt *TIV = 0;
631 BasicBlock *TIBB = TI->getParent();
632 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
633 if (PredCases[i].second == TIBB)
634 if (TIV == 0)
635 TIV = PredCases[i].first;
636 else
637 return false; // Cannot handle multiple values coming to this block.
638 assert(TIV && "No edge from pred to succ?");
639
640 // Okay, we found the one constant that our value can be if we get into TI's
641 // BB. Find out which successor will unconditionally be branched to.
642 BasicBlock *TheRealDest = 0;
643 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
644 if (ThisCases[i].first == TIV) {
645 TheRealDest = ThisCases[i].second;
646 break;
647 }
648
649 // If not handled by any explicit cases, it is handled by the default case.
650 if (TheRealDest == 0) TheRealDest = ThisDef;
651
652 // Remove PHI node entries for dead edges.
653 BasicBlock *CheckEdge = TheRealDest;
654 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
655 if (*SI != CheckEdge)
656 (*SI)->removePredecessor(TIBB);
657 else
658 CheckEdge = 0;
659
660 // Insert the new branch.
661 Instruction *NI = new BranchInst(TheRealDest, TI);
662
663 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
664 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
665 Instruction *Cond = 0;
666 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
667 Cond = dyn_cast<Instruction>(BI->getCondition());
668 TI->eraseFromParent(); // Nuke the old one.
669
670 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
671 return true;
672 }
673 return false;
674}
675
Chris Lattner542f1492004-02-28 21:28:10 +0000676// FoldValueComparisonIntoPredecessors - The specified terminator is a value
677// equality comparison instruction (either a switch or a branch on "X == c").
678// See if any of the predecessors of the terminator block are value comparisons
679// on the same value. If so, and if safe to do so, fold them together.
680static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
681 BasicBlock *BB = TI->getParent();
682 Value *CV = isValueEqualityComparison(TI); // CondVal
683 assert(CV && "Not a comparison?");
684 bool Changed = false;
685
686 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
687 while (!Preds.empty()) {
688 BasicBlock *Pred = Preds.back();
689 Preds.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000690
Chris Lattner542f1492004-02-28 21:28:10 +0000691 // See if the predecessor is a comparison with the same value.
692 TerminatorInst *PTI = Pred->getTerminator();
693 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
694
695 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
696 // Figure out which 'cases' to copy from SI to PSI.
697 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
698 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
699
700 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
701 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
702
703 // Based on whether the default edge from PTI goes to BB or not, fill in
704 // PredCases and PredDefault with the new switch cases we would like to
705 // build.
706 std::vector<BasicBlock*> NewSuccessors;
707
708 if (PredDefault == BB) {
709 // If this is the default destination from PTI, only the edges in TI
710 // that don't occur in PTI, or that branch to BB will be activated.
711 std::set<ConstantInt*> PTIHandled;
712 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
713 if (PredCases[i].second != BB)
714 PTIHandled.insert(PredCases[i].first);
715 else {
716 // The default destination is BB, we don't need explicit targets.
717 std::swap(PredCases[i], PredCases.back());
718 PredCases.pop_back();
719 --i; --e;
720 }
721
722 // Reconstruct the new switch statement we will be building.
723 if (PredDefault != BBDefault) {
724 PredDefault->removePredecessor(Pred);
725 PredDefault = BBDefault;
726 NewSuccessors.push_back(BBDefault);
727 }
728 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
729 if (!PTIHandled.count(BBCases[i].first) &&
730 BBCases[i].second != BBDefault) {
731 PredCases.push_back(BBCases[i]);
732 NewSuccessors.push_back(BBCases[i].second);
733 }
734
735 } else {
736 // If this is not the default destination from PSI, only the edges
737 // in SI that occur in PSI with a destination of BB will be
738 // activated.
739 std::set<ConstantInt*> PTIHandled;
740 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
741 if (PredCases[i].second == BB) {
742 PTIHandled.insert(PredCases[i].first);
743 std::swap(PredCases[i], PredCases.back());
744 PredCases.pop_back();
745 --i; --e;
746 }
747
748 // Okay, now we know which constants were sent to BB from the
749 // predecessor. Figure out where they will all go now.
750 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
751 if (PTIHandled.count(BBCases[i].first)) {
752 // If this is one we are capable of getting...
753 PredCases.push_back(BBCases[i]);
754 NewSuccessors.push_back(BBCases[i].second);
755 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
756 }
757
758 // If there are any constants vectored to BB that TI doesn't handle,
759 // they must go to the default destination of TI.
760 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
761 E = PTIHandled.end(); I != E; ++I) {
762 PredCases.push_back(std::make_pair(*I, BBDefault));
763 NewSuccessors.push_back(BBDefault);
764 }
765 }
766
767 // Okay, at this point, we know which new successor Pred will get. Make
768 // sure we update the number of entries in the PHI nodes for these
769 // successors.
770 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
771 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
772
773 // Now that the successors are updated, create the new Switch instruction.
Chris Lattner37880592005-01-29 00:38:26 +0000774 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
Chris Lattner542f1492004-02-28 21:28:10 +0000775 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
776 NewSI->addCase(PredCases[i].first, PredCases[i].second);
Chris Lattner13b2f762005-01-01 16:02:12 +0000777
778 Instruction *DeadCond = 0;
779 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
780 // If PTI is a branch, remember the condition.
781 DeadCond = dyn_cast<Instruction>(BI->getCondition());
Chris Lattner542f1492004-02-28 21:28:10 +0000782 Pred->getInstList().erase(PTI);
783
Chris Lattner13b2f762005-01-01 16:02:12 +0000784 // If the condition is dead now, remove the instruction tree.
785 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
786
Chris Lattner542f1492004-02-28 21:28:10 +0000787 // Okay, last check. If BB is still a successor of PSI, then we must
788 // have an infinite loop case. If so, add an infinitely looping block
789 // to handle the case to preserve the behavior of the code.
790 BasicBlock *InfLoopBlock = 0;
791 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
792 if (NewSI->getSuccessor(i) == BB) {
793 if (InfLoopBlock == 0) {
794 // Insert it at the end of the loop, because it's either code,
795 // or it won't matter if it's hot. :)
796 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
797 new BranchInst(InfLoopBlock, InfLoopBlock);
798 }
799 NewSI->setSuccessor(i, InfLoopBlock);
800 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000801
Chris Lattner542f1492004-02-28 21:28:10 +0000802 Changed = true;
803 }
804 }
805 return Changed;
806}
807
Chris Lattner37dc9382004-11-30 00:29:14 +0000808/// HoistThenElseCodeToIf - Given a conditional branch that codes to BB1 and
809/// BB2, hoist any common code in the two blocks up into the branch block. The
810/// caller of this function guarantees that BI's block dominates BB1 and BB2.
811static bool HoistThenElseCodeToIf(BranchInst *BI) {
812 // This does very trivial matching, with limited scanning, to find identical
813 // instructions in the two blocks. In particular, we don't want to get into
814 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
815 // such, we currently just scan for obviously identical instructions in an
816 // identical order.
817 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
818 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
819
820 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
821 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2))
822 return false;
823
824 // If we get here, we can hoist at least one instruction.
825 BasicBlock *BIParent = BI->getParent();
Chris Lattner37dc9382004-11-30 00:29:14 +0000826
827 do {
828 // If we are hoisting the terminator instruction, don't move one (making a
829 // broken BB), instead clone it, and remove BI.
830 if (isa<TerminatorInst>(I1))
831 goto HoistTerminator;
Misha Brukmanfd939082005-04-21 23:48:37 +0000832
Chris Lattner37dc9382004-11-30 00:29:14 +0000833 // For a normal instruction, we just move one to right before the branch,
834 // then replace all uses of the other with the first. Finally, we remove
835 // the now redundant second instruction.
836 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
837 if (!I2->use_empty())
838 I2->replaceAllUsesWith(I1);
839 BB2->getInstList().erase(I2);
Misha Brukmanfd939082005-04-21 23:48:37 +0000840
Chris Lattner37dc9382004-11-30 00:29:14 +0000841 I1 = BB1->begin();
842 I2 = BB2->begin();
Chris Lattner37dc9382004-11-30 00:29:14 +0000843 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
844
845 return true;
846
847HoistTerminator:
848 // Okay, it is safe to hoist the terminator.
849 Instruction *NT = I1->clone();
850 BIParent->getInstList().insert(BI, NT);
851 if (NT->getType() != Type::VoidTy) {
852 I1->replaceAllUsesWith(NT);
853 I2->replaceAllUsesWith(NT);
854 NT->setName(I1->getName());
855 }
856
857 // Hoisting one of the terminators from our successor is a great thing.
858 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
859 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
860 // nodes, so we insert select instruction to compute the final result.
861 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
862 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
863 PHINode *PN;
864 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner0f535c62004-11-30 07:47:34 +0000865 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner37dc9382004-11-30 00:29:14 +0000866 Value *BB1V = PN->getIncomingValueForBlock(BB1);
867 Value *BB2V = PN->getIncomingValueForBlock(BB2);
868 if (BB1V != BB2V) {
869 // These values do not agree. Insert a select instruction before NT
870 // that determines the right value.
871 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
872 if (SI == 0)
873 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
874 BB1V->getName()+"."+BB2V->getName(), NT);
875 // Make the PHI node use the select for all incoming values for BB1/BB2
876 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
877 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
878 PN->setIncomingValue(i, SI);
879 }
880 }
881 }
882
883 // Update any PHI nodes in our new successors.
884 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
885 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanfd939082005-04-21 23:48:37 +0000886
Chris Lattner37dc9382004-11-30 00:29:14 +0000887 BI->eraseFromParent();
888 return true;
889}
890
Chris Lattner1654cff2004-06-19 07:02:14 +0000891namespace {
892 /// ConstantIntOrdering - This class implements a stable ordering of constant
893 /// integers that does not depend on their address. This is important for
894 /// applications that sort ConstantInt's to ensure uniqueness.
895 struct ConstantIntOrdering {
896 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
897 return LHS->getRawValue() < RHS->getRawValue();
898 }
899 };
900}
901
Chris Lattner01d1ee32002-05-21 20:50:24 +0000902// SimplifyCFG - This function is used to do simplification of a CFG. For
903// example, it adjusts branches to branches to eliminate the extra hop, it
904// eliminates unreachable basic blocks, and does other "peephole" optimization
Chris Lattnere2ca5402003-03-05 21:01:52 +0000905// of the CFG. It returns true if a modification was made.
Chris Lattner01d1ee32002-05-21 20:50:24 +0000906//
907// WARNING: The entry node of a function may not be simplified.
908//
Chris Lattnerf7703df2004-01-09 06:12:26 +0000909bool llvm::SimplifyCFG(BasicBlock *BB) {
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000910 bool Changed = false;
Chris Lattner01d1ee32002-05-21 20:50:24 +0000911 Function *M = BB->getParent();
912
913 assert(BB && BB->getParent() && "Block not embedded in function!");
914 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner18961502002-06-25 16:12:52 +0000915 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
Chris Lattner01d1ee32002-05-21 20:50:24 +0000916
Chris Lattner01d1ee32002-05-21 20:50:24 +0000917 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerd52c2612004-02-24 07:23:58 +0000918 if (pred_begin(BB) == pred_end(BB) ||
919 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
Chris Lattner30b43442004-07-15 02:06:12 +0000920 DEBUG(std::cerr << "Removing BB: \n" << *BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000921
922 // Loop through all of our successors and make sure they know that one
923 // of their predecessors is going away.
Chris Lattner151c80b2005-04-12 18:51:33 +0000924 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
925 SI->removePredecessor(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000926
927 while (!BB->empty()) {
Chris Lattner18961502002-06-25 16:12:52 +0000928 Instruction &I = BB->back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000929 // If this instruction is used, replace uses with an arbitrary
Chris Lattnerf5e982d2005-08-02 23:29:23 +0000930 // value. Because control flow can't get here, we don't care
Misha Brukmanfd939082005-04-21 23:48:37 +0000931 // what we replace the value with. Note that since this block is
Chris Lattner01d1ee32002-05-21 20:50:24 +0000932 // unreachable, and all values contained within it must dominate their
933 // uses, that all uses will eventually be removed.
Misha Brukmanfd939082005-04-21 23:48:37 +0000934 if (!I.use_empty())
Chris Lattnerf5e982d2005-08-02 23:29:23 +0000935 // Make all users of this instruction use undef instead
936 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Misha Brukmanfd939082005-04-21 23:48:37 +0000937
Chris Lattner01d1ee32002-05-21 20:50:24 +0000938 // Remove the instruction from the basic block
Chris Lattner18961502002-06-25 16:12:52 +0000939 BB->getInstList().pop_back();
Chris Lattner01d1ee32002-05-21 20:50:24 +0000940 }
Chris Lattner18961502002-06-25 16:12:52 +0000941 M->getBasicBlockList().erase(BB);
Chris Lattner01d1ee32002-05-21 20:50:24 +0000942 return true;
943 }
944
Chris Lattner694e37f2003-08-17 19:41:53 +0000945 // Check to see if we can constant propagate this terminator instruction
946 // away...
Chris Lattnerdc3602b2003-08-24 18:36:16 +0000947 Changed |= ConstantFoldTerminator(BB);
Chris Lattner694e37f2003-08-17 19:41:53 +0000948
Chris Lattner19831ec2004-02-16 06:35:48 +0000949 // If this is a returning block with only PHI nodes in it, fold the return
950 // instruction into any unconditional branch predecessors.
Chris Lattner147af6b2004-04-02 18:13:43 +0000951 //
952 // If any predecessor is a conditional branch that just selects among
953 // different return values, fold the replace the branch/return with a select
954 // and return.
Chris Lattner19831ec2004-02-16 06:35:48 +0000955 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
956 BasicBlock::iterator BBI = BB->getTerminator();
957 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
Chris Lattner147af6b2004-04-02 18:13:43 +0000958 // Find predecessors that end with branches.
Chris Lattner19831ec2004-02-16 06:35:48 +0000959 std::vector<BasicBlock*> UncondBranchPreds;
Chris Lattner147af6b2004-04-02 18:13:43 +0000960 std::vector<BranchInst*> CondBranchPreds;
Chris Lattner19831ec2004-02-16 06:35:48 +0000961 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
962 TerminatorInst *PTI = (*PI)->getTerminator();
963 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
964 if (BI->isUnconditional())
965 UncondBranchPreds.push_back(*PI);
Chris Lattner147af6b2004-04-02 18:13:43 +0000966 else
967 CondBranchPreds.push_back(BI);
Chris Lattner19831ec2004-02-16 06:35:48 +0000968 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000969
Chris Lattner19831ec2004-02-16 06:35:48 +0000970 // If we found some, do the transformation!
971 if (!UncondBranchPreds.empty()) {
972 while (!UncondBranchPreds.empty()) {
973 BasicBlock *Pred = UncondBranchPreds.back();
974 UncondBranchPreds.pop_back();
975 Instruction *UncondBranch = Pred->getTerminator();
976 // Clone the return and add it to the end of the predecessor.
977 Instruction *NewRet = RI->clone();
978 Pred->getInstList().push_back(NewRet);
979
980 // If the return instruction returns a value, and if the value was a
981 // PHI node in "BB", propagate the right value into the return.
982 if (NewRet->getNumOperands() == 1)
983 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
984 if (PN->getParent() == BB)
985 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
986 // Update any PHI nodes in the returning block to realize that we no
987 // longer branch to them.
988 BB->removePredecessor(Pred);
989 Pred->getInstList().erase(UncondBranch);
990 }
991
992 // If we eliminated all predecessors of the block, delete the block now.
993 if (pred_begin(BB) == pred_end(BB))
994 // We know there are no successors, so just nuke the block.
995 M->getBasicBlockList().erase(BB);
996
Chris Lattner19831ec2004-02-16 06:35:48 +0000997 return true;
998 }
Chris Lattner147af6b2004-04-02 18:13:43 +0000999
1000 // Check out all of the conditional branches going to this return
1001 // instruction. If any of them just select between returns, change the
1002 // branch itself into a select/return pair.
1003 while (!CondBranchPreds.empty()) {
1004 BranchInst *BI = CondBranchPreds.back();
1005 CondBranchPreds.pop_back();
1006 BasicBlock *TrueSucc = BI->getSuccessor(0);
1007 BasicBlock *FalseSucc = BI->getSuccessor(1);
1008 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1009
1010 // Check to see if the non-BB successor is also a return block.
1011 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1012 // Check to see if there are only PHI instructions in this block.
1013 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1014 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1015 // Okay, we found a branch that is going to two return nodes. If
1016 // there is no return value for this function, just change the
1017 // branch into a return.
1018 if (RI->getNumOperands() == 0) {
1019 TrueSucc->removePredecessor(BI->getParent());
1020 FalseSucc->removePredecessor(BI->getParent());
1021 new ReturnInst(0, BI);
1022 BI->getParent()->getInstList().erase(BI);
1023 return true;
1024 }
1025
1026 // Otherwise, figure out what the true and false return values are
1027 // so we can insert a new select instruction.
1028 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1029 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1030
1031 // Unwrap any PHI nodes in the return blocks.
1032 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1033 if (TVPN->getParent() == TrueSucc)
1034 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1035 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1036 if (FVPN->getParent() == FalseSucc)
1037 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1038
Chris Lattner7aa773b2004-04-02 18:15:10 +00001039 TrueSucc->removePredecessor(BI->getParent());
1040 FalseSucc->removePredecessor(BI->getParent());
1041
Chris Lattner147af6b2004-04-02 18:13:43 +00001042 // Insert a new select instruction.
Chris Lattner0ed7f422004-09-29 05:43:32 +00001043 Value *NewRetVal;
1044 Value *BrCond = BI->getCondition();
1045 if (TrueValue != FalseValue)
1046 NewRetVal = new SelectInst(BrCond, TrueValue,
1047 FalseValue, "retval", BI);
1048 else
1049 NewRetVal = TrueValue;
1050
Chris Lattner147af6b2004-04-02 18:13:43 +00001051 new ReturnInst(NewRetVal, BI);
1052 BI->getParent()->getInstList().erase(BI);
Chris Lattner0ed7f422004-09-29 05:43:32 +00001053 if (BrCond->use_empty())
1054 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1055 BrCondI->getParent()->getInstList().erase(BrCondI);
Chris Lattner147af6b2004-04-02 18:13:43 +00001056 return true;
1057 }
1058 }
1059 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001060 }
Chris Lattnere14ea082004-02-24 05:54:22 +00001061 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
1062 // Check to see if the first instruction in this block is just an unwind.
1063 // If so, replace any invoke instructions which use this as an exception
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001064 // destination with call instructions, and any unconditional branch
1065 // predecessor with an unwind.
Chris Lattnere14ea082004-02-24 05:54:22 +00001066 //
1067 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1068 while (!Preds.empty()) {
1069 BasicBlock *Pred = Preds.back();
Chris Lattneraf17b1d2004-07-20 01:17:38 +00001070 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1071 if (BI->isUnconditional()) {
1072 Pred->getInstList().pop_back(); // nuke uncond branch
1073 new UnwindInst(Pred); // Use unwind.
1074 Changed = true;
1075 }
1076 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
Chris Lattnere14ea082004-02-24 05:54:22 +00001077 if (II->getUnwindDest() == BB) {
1078 // Insert a new branch instruction before the invoke, because this
1079 // is now a fall through...
1080 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1081 Pred->getInstList().remove(II); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001082
Chris Lattnere14ea082004-02-24 05:54:22 +00001083 // Insert the call now...
1084 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1085 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1086 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001087 CI->setCallingConv(II->getCallingConv());
Chris Lattnere14ea082004-02-24 05:54:22 +00001088 // If the invoke produced a value, the Call now does instead
1089 II->replaceAllUsesWith(CI);
1090 delete II;
1091 Changed = true;
1092 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001093
Chris Lattnere14ea082004-02-24 05:54:22 +00001094 Preds.pop_back();
1095 }
Chris Lattner8e509dd2004-02-24 16:09:21 +00001096
1097 // If this block is now dead, remove it.
1098 if (pred_begin(BB) == pred_end(BB)) {
1099 // We know there are no successors, so just nuke the block.
1100 M->getBasicBlockList().erase(BB);
1101 return true;
1102 }
1103
Chris Lattner623369a2005-02-24 06:17:52 +00001104 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1105 if (isValueEqualityComparison(SI)) {
1106 // If we only have one predecessor, and if it is a branch on this value,
1107 // see if that predecessor totally determines the outcome of this switch.
1108 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1109 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1110 return SimplifyCFG(BB) || 1;
1111
1112 // If the block only contains the switch, see if we can fold the block
1113 // away into any preds.
1114 if (SI == &BB->front())
1115 if (FoldValueComparisonIntoPredecessors(SI))
1116 return SimplifyCFG(BB) || 1;
1117 }
Chris Lattner542f1492004-02-28 21:28:10 +00001118 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner7e663482005-08-03 00:11:16 +00001119 if (BI->isUnconditional()) {
1120 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1121 while (isa<PHINode>(*BBI)) ++BBI;
1122
1123 BasicBlock *Succ = BI->getSuccessor(0);
1124 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1125 Succ != BB) // Don't hurt infinite loops!
1126 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1127 return 1;
1128
1129 } else { // Conditional branch
Chris Lattnere67fa052004-05-01 23:35:43 +00001130 if (Value *CompVal = isValueEqualityComparison(BI)) {
Chris Lattner623369a2005-02-24 06:17:52 +00001131 // If we only have one predecessor, and if it is a branch on this value,
1132 // see if that predecessor totally determines the outcome of this
1133 // switch.
1134 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1135 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1136 return SimplifyCFG(BB) || 1;
1137
Chris Lattnere67fa052004-05-01 23:35:43 +00001138 // This block must be empty, except for the setcond inst, if it exists.
1139 BasicBlock::iterator I = BB->begin();
1140 if (&*I == BI ||
1141 (&*I == cast<Instruction>(BI->getCondition()) &&
1142 &*++I == BI))
1143 if (FoldValueComparisonIntoPredecessors(BI))
1144 return SimplifyCFG(BB) | true;
1145 }
1146
1147 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1148 // branches to us and one of our successors, fold the setcc into the
1149 // predecessor and use logical operations to pick the right destination.
Chris Lattner12fe2b12004-05-02 05:02:03 +00001150 BasicBlock *TrueDest = BI->getSuccessor(0);
1151 BasicBlock *FalseDest = BI->getSuccessor(1);
Chris Lattnerbdcc0b82004-05-02 05:19:36 +00001152 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
Chris Lattnere67fa052004-05-01 23:35:43 +00001153 if (Cond->getParent() == BB && &BB->front() == Cond &&
Chris Lattner12fe2b12004-05-02 05:02:03 +00001154 Cond->getNext() == BI && Cond->hasOneUse() &&
1155 TrueDest != BB && FalseDest != BB)
Chris Lattnere67fa052004-05-01 23:35:43 +00001156 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1157 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattnera1f79fb2004-05-02 01:00:44 +00001158 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001159 BasicBlock *PredBlock = *PI;
Chris Lattnere67fa052004-05-01 23:35:43 +00001160 if (PBI->getSuccessor(0) == FalseDest ||
1161 PBI->getSuccessor(1) == TrueDest) {
1162 // Invert the predecessors condition test (xor it with true),
1163 // which allows us to write this code once.
1164 Value *NewCond =
1165 BinaryOperator::createNot(PBI->getCondition(),
1166 PBI->getCondition()->getName()+".not", PBI);
1167 PBI->setCondition(NewCond);
1168 BasicBlock *OldTrue = PBI->getSuccessor(0);
1169 BasicBlock *OldFalse = PBI->getSuccessor(1);
1170 PBI->setSuccessor(0, OldFalse);
1171 PBI->setSuccessor(1, OldTrue);
1172 }
1173
1174 if (PBI->getSuccessor(0) == TrueDest ||
1175 PBI->getSuccessor(1) == FalseDest) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001176 // Clone Cond into the predecessor basic block, and or/and the
Chris Lattnere67fa052004-05-01 23:35:43 +00001177 // two conditions together.
1178 Instruction *New = Cond->clone();
1179 New->setName(Cond->getName());
1180 Cond->setName(Cond->getName()+".old");
Chris Lattner2636c1b2004-06-21 07:19:01 +00001181 PredBlock->getInstList().insert(PBI, New);
Chris Lattnere67fa052004-05-01 23:35:43 +00001182 Instruction::BinaryOps Opcode =
1183 PBI->getSuccessor(0) == TrueDest ?
1184 Instruction::Or : Instruction::And;
Misha Brukmanfd939082005-04-21 23:48:37 +00001185 Value *NewCond =
Chris Lattnere67fa052004-05-01 23:35:43 +00001186 BinaryOperator::create(Opcode, PBI->getCondition(),
1187 New, "bothcond", PBI);
1188 PBI->setCondition(NewCond);
1189 if (PBI->getSuccessor(0) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001190 AddPredecessorToBlock(TrueDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +00001191 PBI->setSuccessor(0, TrueDest);
1192 }
1193 if (PBI->getSuccessor(1) == BB) {
Chris Lattner2636c1b2004-06-21 07:19:01 +00001194 AddPredecessorToBlock(FalseDest, PredBlock, BB);
Chris Lattnere67fa052004-05-01 23:35:43 +00001195 PBI->setSuccessor(1, FalseDest);
1196 }
1197 return SimplifyCFG(BB) | 1;
1198 }
1199 }
Chris Lattnere67fa052004-05-01 23:35:43 +00001200
Chris Lattner92da2c22004-05-01 22:36:37 +00001201 // If this block ends with a branch instruction, and if there is one
1202 // predecessor, see if the previous block ended with a branch on the same
1203 // condition, which makes this conditional branch redundant.
Chris Lattner7e663482005-08-03 00:11:16 +00001204 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Chris Lattner92da2c22004-05-01 22:36:37 +00001205 if (BranchInst *PBI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1206 if (PBI->isConditional() &&
1207 PBI->getCondition() == BI->getCondition() &&
Chris Lattner951fdb92004-05-01 22:41:51 +00001208 (PBI->getSuccessor(0) != BB || PBI->getSuccessor(1) != BB)) {
Chris Lattner92da2c22004-05-01 22:36:37 +00001209 // Okay, the outcome of this conditional branch is statically
1210 // knowable. Delete the outgoing CFG edge that is impossible to
1211 // execute.
1212 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1213 BI->getSuccessor(CondIsTrue)->removePredecessor(BB);
1214 new BranchInst(BI->getSuccessor(!CondIsTrue), BB);
1215 BB->getInstList().erase(BI);
1216 return SimplifyCFG(BB) | true;
1217 }
Chris Lattnerd52c2612004-02-24 07:23:58 +00001218 }
Chris Lattner698f96f2004-10-18 04:07:22 +00001219 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1220 // If there are any instructions immediately before the unreachable that can
1221 // be removed, do so.
1222 Instruction *Unreachable = BB->getTerminator();
1223 while (Unreachable != BB->begin()) {
1224 BasicBlock::iterator BBI = Unreachable;
1225 --BBI;
1226 if (isa<CallInst>(BBI)) break;
1227 // Delete this instruction
1228 BB->getInstList().erase(BBI);
1229 Changed = true;
1230 }
1231
1232 // If the unreachable instruction is the first in the block, take a gander
1233 // at all of the predecessors of this instruction, and simplify them.
1234 if (&BB->front() == Unreachable) {
1235 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1236 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1237 TerminatorInst *TI = Preds[i]->getTerminator();
1238
1239 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1240 if (BI->isUnconditional()) {
1241 if (BI->getSuccessor(0) == BB) {
1242 new UnreachableInst(TI);
1243 TI->eraseFromParent();
1244 Changed = true;
1245 }
1246 } else {
1247 if (BI->getSuccessor(0) == BB) {
1248 new BranchInst(BI->getSuccessor(1), BI);
1249 BI->eraseFromParent();
1250 } else if (BI->getSuccessor(1) == BB) {
1251 new BranchInst(BI->getSuccessor(0), BI);
1252 BI->eraseFromParent();
1253 Changed = true;
1254 }
1255 }
1256 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1257 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1258 if (SI->getSuccessor(i) == BB) {
Chris Lattner42eb7522005-05-20 22:19:54 +00001259 BB->removePredecessor(SI->getParent());
Chris Lattner698f96f2004-10-18 04:07:22 +00001260 SI->removeCase(i);
1261 --i; --e;
1262 Changed = true;
1263 }
1264 // If the default value is unreachable, figure out the most popular
1265 // destination and make it the default.
1266 if (SI->getSuccessor(0) == BB) {
1267 std::map<BasicBlock*, unsigned> Popularity;
1268 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1269 Popularity[SI->getSuccessor(i)]++;
1270
1271 // Find the most popular block.
1272 unsigned MaxPop = 0;
1273 BasicBlock *MaxBlock = 0;
1274 for (std::map<BasicBlock*, unsigned>::iterator
1275 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1276 if (I->second > MaxPop) {
1277 MaxPop = I->second;
1278 MaxBlock = I->first;
1279 }
1280 }
1281 if (MaxBlock) {
1282 // Make this the new default, allowing us to delete any explicit
1283 // edges to it.
1284 SI->setSuccessor(0, MaxBlock);
1285 Changed = true;
1286
Chris Lattner42eb7522005-05-20 22:19:54 +00001287 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1288 // it.
1289 if (isa<PHINode>(MaxBlock->begin()))
1290 for (unsigned i = 0; i != MaxPop-1; ++i)
1291 MaxBlock->removePredecessor(SI->getParent());
1292
Chris Lattner698f96f2004-10-18 04:07:22 +00001293 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1294 if (SI->getSuccessor(i) == MaxBlock) {
1295 SI->removeCase(i);
1296 --i; --e;
1297 }
1298 }
1299 }
1300 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1301 if (II->getUnwindDest() == BB) {
1302 // Convert the invoke to a call instruction. This would be a good
1303 // place to note that the call does not throw though.
1304 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1305 II->removeFromParent(); // Take out of symbol table
Misha Brukmanfd939082005-04-21 23:48:37 +00001306
Chris Lattner698f96f2004-10-18 04:07:22 +00001307 // Insert the call now...
1308 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1309 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1310 II->getName(), BI);
Chris Lattner16d0db22005-05-14 12:21:56 +00001311 CI->setCallingConv(II->getCallingConv());
Chris Lattner698f96f2004-10-18 04:07:22 +00001312 // If the invoke produced a value, the Call does now instead.
1313 II->replaceAllUsesWith(CI);
1314 delete II;
1315 Changed = true;
1316 }
1317 }
1318 }
1319
1320 // If this block is now dead, remove it.
1321 if (pred_begin(BB) == pred_end(BB)) {
1322 // We know there are no successors, so just nuke the block.
1323 M->getBasicBlockList().erase(BB);
1324 return true;
1325 }
1326 }
Chris Lattner19831ec2004-02-16 06:35:48 +00001327 }
1328
Chris Lattner01d1ee32002-05-21 20:50:24 +00001329 // Merge basic blocks into their predecessor if there is only one distinct
1330 // pred, and if there is only one distinct successor of the predecessor, and
1331 // if there are no PHI nodes.
1332 //
Chris Lattner2355f942004-02-11 01:17:07 +00001333 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1334 BasicBlock *OnlyPred = *PI++;
1335 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1336 if (*PI != OnlyPred) {
1337 OnlyPred = 0; // There are multiple different predecessors...
1338 break;
1339 }
Chris Lattner92da2c22004-05-01 22:36:37 +00001340
Chris Lattner2355f942004-02-11 01:17:07 +00001341 BasicBlock *OnlySucc = 0;
1342 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1343 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1344 // Check to see if there is only one distinct successor...
1345 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1346 OnlySucc = BB;
1347 for (; SI != SE; ++SI)
1348 if (*SI != OnlySucc) {
1349 OnlySucc = 0; // There are multiple distinct successors!
Chris Lattner01d1ee32002-05-21 20:50:24 +00001350 break;
1351 }
Chris Lattner2355f942004-02-11 01:17:07 +00001352 }
1353
1354 if (OnlySucc) {
Chris Lattner30b43442004-07-15 02:06:12 +00001355 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
Chris Lattner2355f942004-02-11 01:17:07 +00001356 TerminatorInst *Term = OnlyPred->getTerminator();
1357
1358 // Resolve any PHI nodes at the start of the block. They are all
1359 // guaranteed to have exactly one entry if they exist, unless there are
1360 // multiple duplicate (but guaranteed to be equal) entries for the
1361 // incoming edges. This occurs when there are multiple edges from
1362 // OnlyPred to OnlySucc.
1363 //
1364 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1365 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1366 BB->getInstList().pop_front(); // Delete the phi node...
Chris Lattner01d1ee32002-05-21 20:50:24 +00001367 }
1368
Chris Lattner2355f942004-02-11 01:17:07 +00001369 // Delete the unconditional branch from the predecessor...
1370 OnlyPred->getInstList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001371
Chris Lattner2355f942004-02-11 01:17:07 +00001372 // Move all definitions in the successor to the predecessor...
1373 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
Misha Brukmanfd939082005-04-21 23:48:37 +00001374
Chris Lattner2355f942004-02-11 01:17:07 +00001375 // Make all PHI nodes that referred to BB now refer to Pred as their
1376 // source...
1377 BB->replaceAllUsesWith(OnlyPred);
Chris Lattner18961502002-06-25 16:12:52 +00001378
Chris Lattner2355f942004-02-11 01:17:07 +00001379 std::string OldName = BB->getName();
Chris Lattner18961502002-06-25 16:12:52 +00001380
Misha Brukmanfd939082005-04-21 23:48:37 +00001381 // Erase basic block from the function...
Chris Lattner2355f942004-02-11 01:17:07 +00001382 M->getBasicBlockList().erase(BB);
Chris Lattner18961502002-06-25 16:12:52 +00001383
Chris Lattner2355f942004-02-11 01:17:07 +00001384 // Inherit predecessors name if it exists...
1385 if (!OldName.empty() && !OnlyPred->hasName())
1386 OnlyPred->setName(OldName);
Misha Brukmanfd939082005-04-21 23:48:37 +00001387
Chris Lattner2355f942004-02-11 01:17:07 +00001388 return true;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001389 }
Chris Lattner723c66d2004-02-11 03:36:04 +00001390
Chris Lattner37dc9382004-11-30 00:29:14 +00001391 // Otherwise, if this block only has a single predecessor, and if that block
1392 // is a conditional branch, see if we can hoist any code from this block up
1393 // into our predecessor.
1394 if (OnlyPred)
Chris Lattner76134372004-12-10 17:42:31 +00001395 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1396 if (BI->isConditional()) {
1397 // Get the other block.
1398 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1399 PI = pred_begin(OtherBB);
1400 ++PI;
1401 if (PI == pred_end(OtherBB)) {
1402 // We have a conditional branch to two blocks that are only reachable
1403 // from the condbr. We know that the condbr dominates the two blocks,
1404 // so see if there is any identical code in the "then" and "else"
1405 // blocks. If so, we can hoist it up to the branching block.
1406 Changed |= HoistThenElseCodeToIf(BI);
1407 }
Chris Lattner37dc9382004-11-30 00:29:14 +00001408 }
Chris Lattner37dc9382004-11-30 00:29:14 +00001409
Chris Lattner0d560082004-02-24 05:38:11 +00001410 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1411 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1412 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1413 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1414 Instruction *Cond = cast<Instruction>(BI->getCondition());
1415 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1416 // 'setne's and'ed together, collect them.
1417 Value *CompVal = 0;
Chris Lattner1654cff2004-06-19 07:02:14 +00001418 std::vector<ConstantInt*> Values;
Chris Lattner0d560082004-02-24 05:38:11 +00001419 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1420 if (CompVal && CompVal->getType()->isInteger()) {
1421 // There might be duplicate constants in the list, which the switch
1422 // instruction can't handle, remove them now.
Chris Lattner1654cff2004-06-19 07:02:14 +00001423 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
Chris Lattner0d560082004-02-24 05:38:11 +00001424 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Misha Brukmanfd939082005-04-21 23:48:37 +00001425
Chris Lattner0d560082004-02-24 05:38:11 +00001426 // Figure out which block is which destination.
1427 BasicBlock *DefaultBB = BI->getSuccessor(1);
1428 BasicBlock *EdgeBB = BI->getSuccessor(0);
1429 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00001430
Chris Lattner0d560082004-02-24 05:38:11 +00001431 // Create the new switch instruction now.
Chris Lattner37880592005-01-29 00:38:26 +00001432 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
Misha Brukmanfd939082005-04-21 23:48:37 +00001433
Chris Lattner0d560082004-02-24 05:38:11 +00001434 // Add all of the 'cases' to the switch instruction.
1435 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1436 New->addCase(Values[i], EdgeBB);
Misha Brukmanfd939082005-04-21 23:48:37 +00001437
Chris Lattner0d560082004-02-24 05:38:11 +00001438 // We added edges from PI to the EdgeBB. As such, if there were any
1439 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1440 // the number of edges added.
1441 for (BasicBlock::iterator BBI = EdgeBB->begin();
Reid Spencer2da5c3d2004-09-15 17:06:42 +00001442 isa<PHINode>(BBI); ++BBI) {
1443 PHINode *PN = cast<PHINode>(BBI);
Chris Lattner0d560082004-02-24 05:38:11 +00001444 Value *InVal = PN->getIncomingValueForBlock(*PI);
1445 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1446 PN->addIncoming(InVal, *PI);
1447 }
1448
1449 // Erase the old branch instruction.
1450 (*PI)->getInstList().erase(BI);
1451
1452 // Erase the potentially condition tree that was used to computed the
1453 // branch condition.
1454 ErasePossiblyDeadInstructionTree(Cond);
1455 return true;
1456 }
1457 }
1458
Chris Lattner723c66d2004-02-11 03:36:04 +00001459 // If there is a trivial two-entry PHI node in this basic block, and we can
1460 // eliminate it, do so now.
1461 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1462 if (PN->getNumIncomingValues() == 2) {
1463 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1464 // statement", which has a very simple dominance structure. Basically, we
1465 // are trying to find the condition that is being branched on, which
1466 // subsequently causes this merge to happen. We really want control
1467 // dependence information for this check, but simplifycfg can't keep it up
1468 // to date, and this catches most of the cases we care about anyway.
1469 //
1470 BasicBlock *IfTrue, *IfFalse;
1471 if (Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse)) {
Chris Lattner218a8222004-06-20 01:13:18 +00001472 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1473 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Chris Lattner723c66d2004-02-11 03:36:04 +00001474
Chris Lattner9c078662004-10-14 05:13:36 +00001475 // Loop over the PHI's seeing if we can promote them all to select
1476 // instructions. While we are at it, keep track of the instructions
1477 // that need to be moved to the dominating block.
1478 std::set<Instruction*> AggressiveInsts;
1479 bool CanPromote = true;
1480
Chris Lattner723c66d2004-02-11 03:36:04 +00001481 BasicBlock::iterator AfterPHIIt = BB->begin();
Chris Lattner9c078662004-10-14 05:13:36 +00001482 while (isa<PHINode>(AfterPHIIt)) {
1483 PHINode *PN = cast<PHINode>(AfterPHIIt++);
Chris Lattner02899292005-06-17 01:45:53 +00001484 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1485 if (PN->getIncomingValue(0) != PN)
1486 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1487 else
1488 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1489 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1490 &AggressiveInsts) ||
1491 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1492 &AggressiveInsts)) {
Chris Lattner9c078662004-10-14 05:13:36 +00001493 CanPromote = false;
1494 break;
1495 }
1496 }
Chris Lattner723c66d2004-02-11 03:36:04 +00001497
Chris Lattner9c078662004-10-14 05:13:36 +00001498 // Did we eliminate all PHI's?
1499 CanPromote |= AfterPHIIt == BB->begin();
Chris Lattner723c66d2004-02-11 03:36:04 +00001500
Chris Lattner9c078662004-10-14 05:13:36 +00001501 // If we all PHI nodes are promotable, check to make sure that all
1502 // instructions in the predecessor blocks can be promoted as well. If
1503 // not, we won't be able to get rid of the control flow, so it's not
1504 // worth promoting to select instructions.
Reid Spencer4e073a82004-10-22 16:10:39 +00001505 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
Chris Lattner9c078662004-10-14 05:13:36 +00001506 if (CanPromote) {
1507 PN = cast<PHINode>(BB->begin());
1508 BasicBlock *Pred = PN->getIncomingBlock(0);
1509 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1510 IfBlock1 = Pred;
1511 DomBlock = *pred_begin(Pred);
1512 for (BasicBlock::iterator I = Pred->begin();
1513 !isa<TerminatorInst>(I); ++I)
1514 if (!AggressiveInsts.count(I)) {
1515 // This is not an aggressive instruction that we can promote.
1516 // Because of this, we won't be able to get rid of the control
1517 // flow, so the xform is not worth it.
1518 CanPromote = false;
1519 break;
1520 }
1521 }
1522
1523 Pred = PN->getIncomingBlock(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00001524 if (CanPromote &&
Chris Lattner9c078662004-10-14 05:13:36 +00001525 cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1526 IfBlock2 = Pred;
1527 DomBlock = *pred_begin(Pred);
1528 for (BasicBlock::iterator I = Pred->begin();
1529 !isa<TerminatorInst>(I); ++I)
1530 if (!AggressiveInsts.count(I)) {
1531 // This is not an aggressive instruction that we can promote.
1532 // Because of this, we won't be able to get rid of the control
1533 // flow, so the xform is not worth it.
1534 CanPromote = false;
1535 break;
1536 }
1537 }
1538 }
1539
1540 // If we can still promote the PHI nodes after this gauntlet of tests,
1541 // do all of the PHI's now.
1542 if (CanPromote) {
1543 // Move all 'aggressive' instructions, which are defined in the
1544 // conditional parts of the if's up to the dominating block.
1545 if (IfBlock1) {
1546 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1547 IfBlock1->getInstList(),
1548 IfBlock1->begin(),
1549 IfBlock1->getTerminator());
1550 }
1551 if (IfBlock2) {
1552 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1553 IfBlock2->getInstList(),
1554 IfBlock2->begin(),
1555 IfBlock2->getTerminator());
1556 }
1557
1558 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1559 // Change the PHI node into a select instruction.
Chris Lattner723c66d2004-02-11 03:36:04 +00001560 Value *TrueVal =
1561 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1562 Value *FalseVal =
1563 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1564
Chris Lattner552112f2004-03-30 19:44:05 +00001565 std::string Name = PN->getName(); PN->setName("");
1566 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
Chris Lattner9c078662004-10-14 05:13:36 +00001567 Name, AfterPHIIt));
Chris Lattner552112f2004-03-30 19:44:05 +00001568 BB->getInstList().erase(PN);
Chris Lattner723c66d2004-02-11 03:36:04 +00001569 }
Chris Lattner9c078662004-10-14 05:13:36 +00001570 Changed = true;
Chris Lattner723c66d2004-02-11 03:36:04 +00001571 }
1572 }
1573 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001574
Chris Lattner694e37f2003-08-17 19:41:53 +00001575 return Changed;
Chris Lattner01d1ee32002-05-21 20:50:24 +00001576}