blob: f19adbd263cab789eda6a269b062943bc3da40d2 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Peephole optimize the CFG.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "simplifycfg"
15#include "llvm/Transforms/Utils/Local.h"
16#include "llvm/Constants.h"
17#include "llvm/Instructions.h"
18#include "llvm/Type.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Support/CFG.h"
21#include "llvm/Support/Debug.h"
22#include "llvm/Analysis/ConstantFolding.h"
23#include "llvm/Transforms/Utils/BasicBlockUtils.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include <algorithm>
27#include <functional>
28#include <set>
29#include <map>
30using namespace llvm;
31
32/// SafeToMergeTerminators - Return true if it is safe to merge these two
33/// terminator instructions together.
34///
35static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
36 if (SI1 == SI2) return false; // Can't merge with self!
37
38 // It is not safe to merge these two switch instructions if they have a common
39 // successor, and if that successor has a PHI node, and if *that* PHI node has
40 // conflicting incoming values from the two switch blocks.
41 BasicBlock *SI1BB = SI1->getParent();
42 BasicBlock *SI2BB = SI2->getParent();
43 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
44
45 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
46 if (SI1Succs.count(*I))
47 for (BasicBlock::iterator BBI = (*I)->begin();
48 isa<PHINode>(BBI); ++BBI) {
49 PHINode *PN = cast<PHINode>(BBI);
50 if (PN->getIncomingValueForBlock(SI1BB) !=
51 PN->getIncomingValueForBlock(SI2BB))
52 return false;
53 }
54
55 return true;
56}
57
58/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
59/// now be entries in it from the 'NewPred' block. The values that will be
60/// flowing into the PHI nodes will be the same as those coming in from
61/// ExistPred, an existing predecessor of Succ.
62static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
63 BasicBlock *ExistPred) {
64 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
65 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
66 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
67
68 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
69 PHINode *PN = cast<PHINode>(I);
70 Value *V = PN->getIncomingValueForBlock(ExistPred);
71 PN->addIncoming(V, NewPred);
72 }
73}
74
75// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
76// almost-empty BB ending in an unconditional branch to Succ, into succ.
77//
78// Assumption: Succ is the single successor for BB.
79//
80static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
81 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
82
83 // Check to see if one of the predecessors of BB is already a predecessor of
84 // Succ. If so, we cannot do the transformation if there are any PHI nodes
85 // with incompatible values coming in from the two edges!
86 //
87 if (isa<PHINode>(Succ->front())) {
88 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
89 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
90 PI != PE; ++PI)
91 if (BBPreds.count(*PI)) {
92 // Loop over all of the PHI nodes checking to see if there are
93 // incompatible values coming in.
94 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
95 PHINode *PN = cast<PHINode>(I);
96 // Loop up the entries in the PHI node for BB and for *PI if the
97 // values coming in are non-equal, we cannot merge these two blocks
98 // (instead we should insert a conditional move or something, then
99 // merge the blocks).
100 if (PN->getIncomingValueForBlock(BB) !=
101 PN->getIncomingValueForBlock(*PI))
102 return false; // Values are not equal...
103 }
104 }
105 }
106
107 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
108 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
109 // fold these blocks, as we don't know whether BB dominates Succ or not to
110 // update the PHI nodes correctly.
111 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
112
Devang Patel8bb31412007-12-22 01:32:53 +0000113 // If the predecessors of Succ are only BB, handle it.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 bool IsSafe = true;
115 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
Devang Patel8bb31412007-12-22 01:32:53 +0000116 if (*PI != BB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 IsSafe = false;
118 break;
119 }
120 if (IsSafe) return true;
121
122 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
123 // BB and Succ have no common predecessors.
124 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
125 PHINode *PN = cast<PHINode>(I);
126 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
127 ++UI)
128 if (cast<Instruction>(*UI)->getParent() != Succ)
129 return false;
130 }
131
132 // Scan the predecessor sets of BB and Succ, making sure there are no common
133 // predecessors. Common predecessors would cause us to build a phi node with
134 // differing incoming values, which is not legal.
135 SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
136 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
137 if (BBPreds.count(*PI))
138 return false;
139
140 return true;
141}
142
143/// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
144/// branch to Succ, and contains no instructions other than PHI nodes and the
145/// branch. If possible, eliminate BB.
146static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
147 BasicBlock *Succ) {
148 // If our successor has PHI nodes, then we need to update them to include
149 // entries for BB's predecessors, not for BB itself. Be careful though,
150 // if this transformation fails (returns true) then we cannot do this
151 // transformation!
152 //
153 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
154
155 DOUT << "Killing Trivial BB: \n" << *BB;
156
157 if (isa<PHINode>(Succ->begin())) {
158 // If there is more than one pred of succ, and there are PHI nodes in
159 // the successor, then we need to add incoming edges for the PHI nodes
160 //
161 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
162
163 // Loop over all of the PHI nodes in the successor of BB.
164 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
165 PHINode *PN = cast<PHINode>(I);
166 Value *OldVal = PN->removeIncomingValue(BB, false);
167 assert(OldVal && "No entry in PHI for Pred BB!");
168
169 // If this incoming value is one of the PHI nodes in BB, the new entries
170 // in the PHI node are the entries from the old PHI.
171 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
172 PHINode *OldValPN = cast<PHINode>(OldVal);
173 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
174 PN->addIncoming(OldValPN->getIncomingValue(i),
175 OldValPN->getIncomingBlock(i));
176 } else {
177 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
178 End = BBPreds.end(); PredI != End; ++PredI) {
179 // Add an incoming value for each of the new incoming values...
180 PN->addIncoming(OldVal, *PredI);
181 }
182 }
183 }
184 }
185
186 if (isa<PHINode>(&BB->front())) {
187 std::vector<BasicBlock*>
188 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
189
190 // Move all PHI nodes in BB to Succ if they are alive, otherwise
191 // delete them.
192 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
193 if (PN->use_empty()) {
194 // Just remove the dead phi. This happens if Succ's PHIs were the only
195 // users of the PHI nodes.
196 PN->eraseFromParent();
197 } else {
198 // The instruction is alive, so this means that Succ must have
199 // *ONLY* had BB as a predecessor, and the PHI node is still valid
200 // now. Simply move it into Succ, because we know that BB
201 // strictly dominated Succ.
202 Succ->getInstList().splice(Succ->begin(),
203 BB->getInstList(), BB->begin());
204
205 // We need to add new entries for the PHI node to account for
206 // predecessors of Succ that the PHI node does not take into
207 // account. At this point, since we know that BB dominated succ,
208 // this means that we should any newly added incoming edges should
209 // use the PHI node as the value for these edges, because they are
210 // loop back edges.
211 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
212 if (OldSuccPreds[i] != BB)
213 PN->addIncoming(PN, OldSuccPreds[i]);
214 }
215 }
216
217 // Everything that jumped to BB now goes to Succ.
218 BB->replaceAllUsesWith(Succ);
219 if (!Succ->hasName()) Succ->takeName(BB);
220 BB->eraseFromParent(); // Delete the old basic block.
221 return true;
222}
223
224/// GetIfCondition - Given a basic block (BB) with two predecessors (and
225/// presumably PHI nodes in it), check to see if the merge at this block is due
226/// to an "if condition". If so, return the boolean condition that determines
227/// which entry into BB will be taken. Also, return by references the block
228/// that will be entered from if the condition is true, and the block that will
229/// be entered if the condition is false.
230///
231///
232static Value *GetIfCondition(BasicBlock *BB,
233 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
234 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
235 "Function can only handle blocks with 2 predecessors!");
236 BasicBlock *Pred1 = *pred_begin(BB);
237 BasicBlock *Pred2 = *++pred_begin(BB);
238
239 // We can only handle branches. Other control flow will be lowered to
240 // branches if possible anyway.
241 if (!isa<BranchInst>(Pred1->getTerminator()) ||
242 !isa<BranchInst>(Pred2->getTerminator()))
243 return 0;
244 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
245 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
246
247 // Eliminate code duplication by ensuring that Pred1Br is conditional if
248 // either are.
249 if (Pred2Br->isConditional()) {
250 // If both branches are conditional, we don't have an "if statement". In
251 // reality, we could transform this case, but since the condition will be
252 // required anyway, we stand no chance of eliminating it, so the xform is
253 // probably not profitable.
254 if (Pred1Br->isConditional())
255 return 0;
256
257 std::swap(Pred1, Pred2);
258 std::swap(Pred1Br, Pred2Br);
259 }
260
261 if (Pred1Br->isConditional()) {
262 // If we found a conditional branch predecessor, make sure that it branches
263 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
264 if (Pred1Br->getSuccessor(0) == BB &&
265 Pred1Br->getSuccessor(1) == Pred2) {
266 IfTrue = Pred1;
267 IfFalse = Pred2;
268 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
269 Pred1Br->getSuccessor(1) == BB) {
270 IfTrue = Pred2;
271 IfFalse = Pred1;
272 } else {
273 // We know that one arm of the conditional goes to BB, so the other must
274 // go somewhere unrelated, and this must not be an "if statement".
275 return 0;
276 }
277
278 // The only thing we have to watch out for here is to make sure that Pred2
279 // doesn't have incoming edges from other blocks. If it does, the condition
280 // doesn't dominate BB.
281 if (++pred_begin(Pred2) != pred_end(Pred2))
282 return 0;
283
284 return Pred1Br->getCondition();
285 }
286
287 // Ok, if we got here, both predecessors end with an unconditional branch to
288 // BB. Don't panic! If both blocks only have a single (identical)
289 // predecessor, and THAT is a conditional branch, then we're all ok!
290 if (pred_begin(Pred1) == pred_end(Pred1) ||
291 ++pred_begin(Pred1) != pred_end(Pred1) ||
292 pred_begin(Pred2) == pred_end(Pred2) ||
293 ++pred_begin(Pred2) != pred_end(Pred2) ||
294 *pred_begin(Pred1) != *pred_begin(Pred2))
295 return 0;
296
297 // Otherwise, if this is a conditional branch, then we can use it!
298 BasicBlock *CommonPred = *pred_begin(Pred1);
299 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
300 assert(BI->isConditional() && "Two successors but not conditional?");
301 if (BI->getSuccessor(0) == Pred1) {
302 IfTrue = Pred1;
303 IfFalse = Pred2;
304 } else {
305 IfTrue = Pred2;
306 IfFalse = Pred1;
307 }
308 return BI->getCondition();
309 }
310 return 0;
311}
312
313
314// If we have a merge point of an "if condition" as accepted above, return true
315// if the specified value dominates the block. We don't handle the true
316// generality of domination here, just a special case which works well enough
317// for us.
318//
319// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
320// see if V (which must be an instruction) is cheap to compute and is
321// non-trapping. If both are true, the instruction is inserted into the set and
322// true is returned.
323static bool DominatesMergePoint(Value *V, BasicBlock *BB,
324 std::set<Instruction*> *AggressiveInsts) {
325 Instruction *I = dyn_cast<Instruction>(V);
326 if (!I) {
327 // Non-instructions all dominate instructions, but not all constantexprs
328 // can be executed unconditionally.
329 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
330 if (C->canTrap())
331 return false;
332 return true;
333 }
334 BasicBlock *PBB = I->getParent();
335
336 // We don't want to allow weird loops that might have the "if condition" in
337 // the bottom of this block.
338 if (PBB == BB) return false;
339
340 // If this instruction is defined in a block that contains an unconditional
341 // branch to BB, then it must be in the 'conditional' part of the "if
342 // statement".
343 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
344 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
345 if (!AggressiveInsts) return false;
346 // Okay, it looks like the instruction IS in the "condition". Check to
347 // see if its a cheap instruction to unconditionally compute, and if it
348 // only uses stuff defined outside of the condition. If so, hoist it out.
349 switch (I->getOpcode()) {
350 default: return false; // Cannot hoist this out safely.
351 case Instruction::Load:
352 // We can hoist loads that are non-volatile and obviously cannot trap.
353 if (cast<LoadInst>(I)->isVolatile())
354 return false;
355 if (!isa<AllocaInst>(I->getOperand(0)) &&
356 !isa<Constant>(I->getOperand(0)))
357 return false;
358
359 // Finally, we have to check to make sure there are no instructions
360 // before the load in its basic block, as we are going to hoist the loop
361 // out to its predecessor.
362 if (PBB->begin() != BasicBlock::iterator(I))
363 return false;
364 break;
365 case Instruction::Add:
366 case Instruction::Sub:
367 case Instruction::And:
368 case Instruction::Or:
369 case Instruction::Xor:
370 case Instruction::Shl:
371 case Instruction::LShr:
372 case Instruction::AShr:
373 case Instruction::ICmp:
374 case Instruction::FCmp:
Chris Lattner765db1a2008-01-03 07:25:26 +0000375 if (I->getOperand(0)->getType()->isFPOrFPVector())
376 return false; // FP arithmetic might trap.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 break; // These are all cheap and non-trapping instructions.
378 }
379
380 // Okay, we can only really hoist these out if their operands are not
381 // defined in the conditional region.
382 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
383 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
384 return false;
385 // Okay, it's safe to do this! Remember this instruction.
386 AggressiveInsts->insert(I);
387 }
388
389 return true;
390}
391
392// GatherConstantSetEQs - Given a potentially 'or'd together collection of
393// icmp_eq instructions that compare a value against a constant, return the
394// value being compared, and stick the constant into the Values vector.
395static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
396 if (Instruction *Inst = dyn_cast<Instruction>(V))
397 if (Inst->getOpcode() == Instruction::ICmp &&
398 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
399 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
400 Values.push_back(C);
401 return Inst->getOperand(0);
402 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
403 Values.push_back(C);
404 return Inst->getOperand(1);
405 }
406 } else if (Inst->getOpcode() == Instruction::Or) {
407 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
408 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
409 if (LHS == RHS)
410 return LHS;
411 }
412 return 0;
413}
414
415// GatherConstantSetNEs - Given a potentially 'and'd together collection of
416// setne instructions that compare a value against a constant, return the value
417// being compared, and stick the constant into the Values vector.
418static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
419 if (Instruction *Inst = dyn_cast<Instruction>(V))
420 if (Inst->getOpcode() == Instruction::ICmp &&
421 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
422 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
423 Values.push_back(C);
424 return Inst->getOperand(0);
425 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
426 Values.push_back(C);
427 return Inst->getOperand(1);
428 }
429 } else if (Inst->getOpcode() == Instruction::And) {
430 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
431 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
432 if (LHS == RHS)
433 return LHS;
434 }
435 return 0;
436}
437
438
439
440/// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
441/// bunch of comparisons of one value against constants, return the value and
442/// the constants being compared.
443static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
444 std::vector<ConstantInt*> &Values) {
445 if (Cond->getOpcode() == Instruction::Or) {
446 CompVal = GatherConstantSetEQs(Cond, Values);
447
448 // Return true to indicate that the condition is true if the CompVal is
449 // equal to one of the constants.
450 return true;
451 } else if (Cond->getOpcode() == Instruction::And) {
452 CompVal = GatherConstantSetNEs(Cond, Values);
453
454 // Return false to indicate that the condition is false if the CompVal is
455 // equal to one of the constants.
456 return false;
457 }
458 return false;
459}
460
461/// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
462/// has no side effects, nuke it. If it uses any instructions that become dead
463/// because the instruction is now gone, nuke them too.
464static void ErasePossiblyDeadInstructionTree(Instruction *I) {
465 if (!isInstructionTriviallyDead(I)) return;
466
467 std::vector<Instruction*> InstrsToInspect;
468 InstrsToInspect.push_back(I);
469
470 while (!InstrsToInspect.empty()) {
471 I = InstrsToInspect.back();
472 InstrsToInspect.pop_back();
473
474 if (!isInstructionTriviallyDead(I)) continue;
475
476 // If I is in the work list multiple times, remove previous instances.
477 for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
478 if (InstrsToInspect[i] == I) {
479 InstrsToInspect.erase(InstrsToInspect.begin()+i);
480 --i, --e;
481 }
482
483 // Add operands of dead instruction to worklist.
484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
485 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
486 InstrsToInspect.push_back(OpI);
487
488 // Remove dead instruction.
489 I->eraseFromParent();
490 }
491}
492
493// isValueEqualityComparison - Return true if the specified terminator checks to
494// see if a value is equal to constant integer value.
495static Value *isValueEqualityComparison(TerminatorInst *TI) {
496 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
497 // Do not permit merging of large switch instructions into their
498 // predecessors unless there is only one predecessor.
499 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
500 pred_end(SI->getParent())) > 128)
501 return 0;
502
503 return SI->getCondition();
504 }
505 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
506 if (BI->isConditional() && BI->getCondition()->hasOneUse())
507 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
508 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
509 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
510 isa<ConstantInt>(ICI->getOperand(1)))
511 return ICI->getOperand(0);
512 return 0;
513}
514
515// Given a value comparison instruction, decode all of the 'cases' that it
516// represents and return the 'default' block.
517static BasicBlock *
518GetValueEqualityComparisonCases(TerminatorInst *TI,
519 std::vector<std::pair<ConstantInt*,
520 BasicBlock*> > &Cases) {
521 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
522 Cases.reserve(SI->getNumCases());
523 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
524 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
525 return SI->getDefaultDest();
526 }
527
528 BranchInst *BI = cast<BranchInst>(TI);
529 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
530 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
531 BI->getSuccessor(ICI->getPredicate() ==
532 ICmpInst::ICMP_NE)));
533 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
534}
535
536
537// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
538// in the list that match the specified block.
539static void EliminateBlockCases(BasicBlock *BB,
540 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
541 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
542 if (Cases[i].second == BB) {
543 Cases.erase(Cases.begin()+i);
544 --i; --e;
545 }
546}
547
548// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
549// well.
550static bool
551ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
552 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
553 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
554
555 // Make V1 be smaller than V2.
556 if (V1->size() > V2->size())
557 std::swap(V1, V2);
558
559 if (V1->size() == 0) return false;
560 if (V1->size() == 1) {
561 // Just scan V2.
562 ConstantInt *TheVal = (*V1)[0].first;
563 for (unsigned i = 0, e = V2->size(); i != e; ++i)
564 if (TheVal == (*V2)[i].first)
565 return true;
566 }
567
568 // Otherwise, just sort both lists and compare element by element.
569 std::sort(V1->begin(), V1->end());
570 std::sort(V2->begin(), V2->end());
571 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
572 while (i1 != e1 && i2 != e2) {
573 if ((*V1)[i1].first == (*V2)[i2].first)
574 return true;
575 if ((*V1)[i1].first < (*V2)[i2].first)
576 ++i1;
577 else
578 ++i2;
579 }
580 return false;
581}
582
583// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
584// terminator instruction and its block is known to only have a single
585// predecessor block, check to see if that predecessor is also a value
586// comparison with the same value, and if that comparison determines the outcome
587// of this comparison. If so, simplify TI. This does a very limited form of
588// jump threading.
589static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
590 BasicBlock *Pred) {
591 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
592 if (!PredVal) return false; // Not a value comparison in predecessor.
593
594 Value *ThisVal = isValueEqualityComparison(TI);
595 assert(ThisVal && "This isn't a value comparison!!");
596 if (ThisVal != PredVal) return false; // Different predicates.
597
598 // Find out information about when control will move from Pred to TI's block.
599 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
600 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
601 PredCases);
602 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
603
604 // Find information about how control leaves this block.
605 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
606 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
607 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
608
609 // If TI's block is the default block from Pred's comparison, potentially
610 // simplify TI based on this knowledge.
611 if (PredDef == TI->getParent()) {
612 // If we are here, we know that the value is none of those cases listed in
613 // PredCases. If there are any cases in ThisCases that are in PredCases, we
614 // can simplify TI.
615 if (ValuesOverlap(PredCases, ThisCases)) {
616 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
617 // Okay, one of the successors of this condbr is dead. Convert it to a
618 // uncond br.
619 assert(ThisCases.size() == 1 && "Branch can only have one case!");
620 Value *Cond = BTI->getCondition();
621 // Insert the new branch.
622 Instruction *NI = new BranchInst(ThisDef, TI);
623
624 // Remove PHI node entries for the dead edge.
625 ThisCases[0].second->removePredecessor(TI->getParent());
626
627 DOUT << "Threading pred instr: " << *Pred->getTerminator()
628 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
629
630 TI->eraseFromParent(); // Nuke the old one.
631 // If condition is now dead, nuke it.
632 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
633 ErasePossiblyDeadInstructionTree(CondI);
634 return true;
635
636 } else {
637 SwitchInst *SI = cast<SwitchInst>(TI);
638 // Okay, TI has cases that are statically dead, prune them away.
639 SmallPtrSet<Constant*, 16> DeadCases;
640 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
641 DeadCases.insert(PredCases[i].first);
642
643 DOUT << "Threading pred instr: " << *Pred->getTerminator()
644 << "Through successor TI: " << *TI;
645
646 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
647 if (DeadCases.count(SI->getCaseValue(i))) {
648 SI->getSuccessor(i)->removePredecessor(TI->getParent());
649 SI->removeCase(i);
650 }
651
652 DOUT << "Leaving: " << *TI << "\n";
653 return true;
654 }
655 }
656
657 } else {
658 // Otherwise, TI's block must correspond to some matched value. Find out
659 // which value (or set of values) this is.
660 ConstantInt *TIV = 0;
661 BasicBlock *TIBB = TI->getParent();
662 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
663 if (PredCases[i].second == TIBB)
664 if (TIV == 0)
665 TIV = PredCases[i].first;
666 else
667 return false; // Cannot handle multiple values coming to this block.
668 assert(TIV && "No edge from pred to succ?");
669
670 // Okay, we found the one constant that our value can be if we get into TI's
671 // BB. Find out which successor will unconditionally be branched to.
672 BasicBlock *TheRealDest = 0;
673 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
674 if (ThisCases[i].first == TIV) {
675 TheRealDest = ThisCases[i].second;
676 break;
677 }
678
679 // If not handled by any explicit cases, it is handled by the default case.
680 if (TheRealDest == 0) TheRealDest = ThisDef;
681
682 // Remove PHI node entries for dead edges.
683 BasicBlock *CheckEdge = TheRealDest;
684 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
685 if (*SI != CheckEdge)
686 (*SI)->removePredecessor(TIBB);
687 else
688 CheckEdge = 0;
689
690 // Insert the new branch.
691 Instruction *NI = new BranchInst(TheRealDest, TI);
692
693 DOUT << "Threading pred instr: " << *Pred->getTerminator()
694 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
695 Instruction *Cond = 0;
696 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
697 Cond = dyn_cast<Instruction>(BI->getCondition());
698 TI->eraseFromParent(); // Nuke the old one.
699
700 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
701 return true;
702 }
703 return false;
704}
705
706// FoldValueComparisonIntoPredecessors - The specified terminator is a value
707// equality comparison instruction (either a switch or a branch on "X == c").
708// See if any of the predecessors of the terminator block are value comparisons
709// on the same value. If so, and if safe to do so, fold them together.
710static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
711 BasicBlock *BB = TI->getParent();
712 Value *CV = isValueEqualityComparison(TI); // CondVal
713 assert(CV && "Not a comparison?");
714 bool Changed = false;
715
716 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
717 while (!Preds.empty()) {
718 BasicBlock *Pred = Preds.back();
719 Preds.pop_back();
720
721 // See if the predecessor is a comparison with the same value.
722 TerminatorInst *PTI = Pred->getTerminator();
723 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
724
725 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
726 // Figure out which 'cases' to copy from SI to PSI.
727 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
728 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
729
730 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
731 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
732
733 // Based on whether the default edge from PTI goes to BB or not, fill in
734 // PredCases and PredDefault with the new switch cases we would like to
735 // build.
736 std::vector<BasicBlock*> NewSuccessors;
737
738 if (PredDefault == BB) {
739 // If this is the default destination from PTI, only the edges in TI
740 // that don't occur in PTI, or that branch to BB will be activated.
741 std::set<ConstantInt*> PTIHandled;
742 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
743 if (PredCases[i].second != BB)
744 PTIHandled.insert(PredCases[i].first);
745 else {
746 // The default destination is BB, we don't need explicit targets.
747 std::swap(PredCases[i], PredCases.back());
748 PredCases.pop_back();
749 --i; --e;
750 }
751
752 // Reconstruct the new switch statement we will be building.
753 if (PredDefault != BBDefault) {
754 PredDefault->removePredecessor(Pred);
755 PredDefault = BBDefault;
756 NewSuccessors.push_back(BBDefault);
757 }
758 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
759 if (!PTIHandled.count(BBCases[i].first) &&
760 BBCases[i].second != BBDefault) {
761 PredCases.push_back(BBCases[i]);
762 NewSuccessors.push_back(BBCases[i].second);
763 }
764
765 } else {
766 // If this is not the default destination from PSI, only the edges
767 // in SI that occur in PSI with a destination of BB will be
768 // activated.
769 std::set<ConstantInt*> PTIHandled;
770 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
771 if (PredCases[i].second == BB) {
772 PTIHandled.insert(PredCases[i].first);
773 std::swap(PredCases[i], PredCases.back());
774 PredCases.pop_back();
775 --i; --e;
776 }
777
778 // Okay, now we know which constants were sent to BB from the
779 // predecessor. Figure out where they will all go now.
780 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
781 if (PTIHandled.count(BBCases[i].first)) {
782 // If this is one we are capable of getting...
783 PredCases.push_back(BBCases[i]);
784 NewSuccessors.push_back(BBCases[i].second);
785 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
786 }
787
788 // If there are any constants vectored to BB that TI doesn't handle,
789 // they must go to the default destination of TI.
790 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
791 E = PTIHandled.end(); I != E; ++I) {
792 PredCases.push_back(std::make_pair(*I, BBDefault));
793 NewSuccessors.push_back(BBDefault);
794 }
795 }
796
797 // Okay, at this point, we know which new successor Pred will get. Make
798 // sure we update the number of entries in the PHI nodes for these
799 // successors.
800 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
801 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
802
803 // Now that the successors are updated, create the new Switch instruction.
804 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
805 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
806 NewSI->addCase(PredCases[i].first, PredCases[i].second);
807
808 Instruction *DeadCond = 0;
809 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
810 // If PTI is a branch, remember the condition.
811 DeadCond = dyn_cast<Instruction>(BI->getCondition());
812 Pred->getInstList().erase(PTI);
813
814 // If the condition is dead now, remove the instruction tree.
815 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
816
817 // Okay, last check. If BB is still a successor of PSI, then we must
818 // have an infinite loop case. If so, add an infinitely looping block
819 // to handle the case to preserve the behavior of the code.
820 BasicBlock *InfLoopBlock = 0;
821 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
822 if (NewSI->getSuccessor(i) == BB) {
823 if (InfLoopBlock == 0) {
824 // Insert it at the end of the loop, because it's either code,
825 // or it won't matter if it's hot. :)
826 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
827 new BranchInst(InfLoopBlock, InfLoopBlock);
828 }
829 NewSI->setSuccessor(i, InfLoopBlock);
830 }
831
832 Changed = true;
833 }
834 }
835 return Changed;
836}
837
838/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
839/// BB2, hoist any common code in the two blocks up into the branch block. The
840/// caller of this function guarantees that BI's block dominates BB1 and BB2.
841static bool HoistThenElseCodeToIf(BranchInst *BI) {
842 // This does very trivial matching, with limited scanning, to find identical
843 // instructions in the two blocks. In particular, we don't want to get into
844 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
845 // such, we currently just scan for obviously identical instructions in an
846 // identical order.
847 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
848 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
849
850 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
851 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
852 isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
853 return false;
854
855 // If we get here, we can hoist at least one instruction.
856 BasicBlock *BIParent = BI->getParent();
857
858 do {
859 // If we are hoisting the terminator instruction, don't move one (making a
860 // broken BB), instead clone it, and remove BI.
861 if (isa<TerminatorInst>(I1))
862 goto HoistTerminator;
863
864 // For a normal instruction, we just move one to right before the branch,
865 // then replace all uses of the other with the first. Finally, we remove
866 // the now redundant second instruction.
867 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
868 if (!I2->use_empty())
869 I2->replaceAllUsesWith(I1);
870 BB2->getInstList().erase(I2);
871
872 I1 = BB1->begin();
873 I2 = BB2->begin();
874 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
875
876 return true;
877
878HoistTerminator:
879 // Okay, it is safe to hoist the terminator.
880 Instruction *NT = I1->clone();
881 BIParent->getInstList().insert(BI, NT);
882 if (NT->getType() != Type::VoidTy) {
883 I1->replaceAllUsesWith(NT);
884 I2->replaceAllUsesWith(NT);
885 NT->takeName(I1);
886 }
887
888 // Hoisting one of the terminators from our successor is a great thing.
889 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
890 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
891 // nodes, so we insert select instruction to compute the final result.
892 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
893 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
894 PHINode *PN;
895 for (BasicBlock::iterator BBI = SI->begin();
896 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
897 Value *BB1V = PN->getIncomingValueForBlock(BB1);
898 Value *BB2V = PN->getIncomingValueForBlock(BB2);
899 if (BB1V != BB2V) {
900 // These values do not agree. Insert a select instruction before NT
901 // that determines the right value.
902 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
903 if (SI == 0)
904 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
905 BB1V->getName()+"."+BB2V->getName(), NT);
906 // Make the PHI node use the select for all incoming values for BB1/BB2
907 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
908 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
909 PN->setIncomingValue(i, SI);
910 }
911 }
912 }
913
914 // Update any PHI nodes in our new successors.
915 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
916 AddPredecessorToBlock(*SI, BIParent, BB1);
917
918 BI->eraseFromParent();
919 return true;
920}
921
922/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
923/// across this block.
924static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
925 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
926 unsigned Size = 0;
927
928 // If this basic block contains anything other than a PHI (which controls the
929 // branch) and branch itself, bail out. FIXME: improve this in the future.
930 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
931 if (Size > 10) return false; // Don't clone large BB's.
932
933 // We can only support instructions that are do not define values that are
934 // live outside of the current basic block.
935 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
936 UI != E; ++UI) {
937 Instruction *U = cast<Instruction>(*UI);
938 if (U->getParent() != BB || isa<PHINode>(U)) return false;
939 }
940
941 // Looks ok, continue checking.
942 }
943
944 return true;
945}
946
947/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
948/// that is defined in the same block as the branch and if any PHI entries are
949/// constants, thread edges corresponding to that entry to be branches to their
950/// ultimate destination.
951static bool FoldCondBranchOnPHI(BranchInst *BI) {
952 BasicBlock *BB = BI->getParent();
953 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
954 // NOTE: we currently cannot transform this case if the PHI node is used
955 // outside of the block.
956 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
957 return false;
958
959 // Degenerate case of a single entry PHI.
960 if (PN->getNumIncomingValues() == 1) {
961 if (PN->getIncomingValue(0) != PN)
962 PN->replaceAllUsesWith(PN->getIncomingValue(0));
963 else
964 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
965 PN->eraseFromParent();
966 return true;
967 }
968
969 // Now we know that this block has multiple preds and two succs.
970 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
971
972 // Okay, this is a simple enough basic block. See if any phi values are
973 // constants.
974 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
975 ConstantInt *CB;
976 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
977 CB->getType() == Type::Int1Ty) {
978 // Okay, we now know that all edges from PredBB should be revectored to
979 // branch to RealDest.
980 BasicBlock *PredBB = PN->getIncomingBlock(i);
981 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
982
983 if (RealDest == BB) continue; // Skip self loops.
984
985 // The dest block might have PHI nodes, other predecessors and other
986 // difficult cases. Instead of being smart about this, just insert a new
987 // block that jumps to the destination block, effectively splitting
988 // the edge we are about to create.
989 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
990 RealDest->getParent(), RealDest);
991 new BranchInst(RealDest, EdgeBB);
992 PHINode *PN;
993 for (BasicBlock::iterator BBI = RealDest->begin();
994 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
995 Value *V = PN->getIncomingValueForBlock(BB);
996 PN->addIncoming(V, EdgeBB);
997 }
998
999 // BB may have instructions that are being threaded over. Clone these
1000 // instructions into EdgeBB. We know that there will be no uses of the
1001 // cloned instructions outside of EdgeBB.
1002 BasicBlock::iterator InsertPt = EdgeBB->begin();
1003 std::map<Value*, Value*> TranslateMap; // Track translated values.
1004 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1005 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1006 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1007 } else {
1008 // Clone the instruction.
1009 Instruction *N = BBI->clone();
1010 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1011
1012 // Update operands due to translation.
1013 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1014 std::map<Value*, Value*>::iterator PI =
1015 TranslateMap.find(N->getOperand(i));
1016 if (PI != TranslateMap.end())
1017 N->setOperand(i, PI->second);
1018 }
1019
1020 // Check for trivial simplification.
1021 if (Constant *C = ConstantFoldInstruction(N)) {
1022 TranslateMap[BBI] = C;
1023 delete N; // Constant folded away, don't need actual inst
1024 } else {
1025 // Insert the new instruction into its new home.
1026 EdgeBB->getInstList().insert(InsertPt, N);
1027 if (!BBI->use_empty())
1028 TranslateMap[BBI] = N;
1029 }
1030 }
1031 }
1032
1033 // Loop over all of the edges from PredBB to BB, changing them to branch
1034 // to EdgeBB instead.
1035 TerminatorInst *PredBBTI = PredBB->getTerminator();
1036 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1037 if (PredBBTI->getSuccessor(i) == BB) {
1038 BB->removePredecessor(PredBB);
1039 PredBBTI->setSuccessor(i, EdgeBB);
1040 }
1041
1042 // Recurse, simplifying any other constants.
1043 return FoldCondBranchOnPHI(BI) | true;
1044 }
1045 }
1046
1047 return false;
1048}
1049
1050/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1051/// PHI node, see if we can eliminate it.
1052static bool FoldTwoEntryPHINode(PHINode *PN) {
1053 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1054 // statement", which has a very simple dominance structure. Basically, we
1055 // are trying to find the condition that is being branched on, which
1056 // subsequently causes this merge to happen. We really want control
1057 // dependence information for this check, but simplifycfg can't keep it up
1058 // to date, and this catches most of the cases we care about anyway.
1059 //
1060 BasicBlock *BB = PN->getParent();
1061 BasicBlock *IfTrue, *IfFalse;
1062 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1063 if (!IfCond) return false;
1064
1065 // Okay, we found that we can merge this two-entry phi node into a select.
1066 // Doing so would require us to fold *all* two entry phi nodes in this block.
1067 // At some point this becomes non-profitable (particularly if the target
1068 // doesn't support cmov's). Only do this transformation if there are two or
1069 // fewer PHI nodes in this block.
1070 unsigned NumPhis = 0;
1071 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1072 if (NumPhis > 2)
1073 return false;
1074
1075 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1076 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
1077
1078 // Loop over the PHI's seeing if we can promote them all to select
1079 // instructions. While we are at it, keep track of the instructions
1080 // that need to be moved to the dominating block.
1081 std::set<Instruction*> AggressiveInsts;
1082
1083 BasicBlock::iterator AfterPHIIt = BB->begin();
1084 while (isa<PHINode>(AfterPHIIt)) {
1085 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1086 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1087 if (PN->getIncomingValue(0) != PN)
1088 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1089 else
1090 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1091 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1092 &AggressiveInsts) ||
1093 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1094 &AggressiveInsts)) {
1095 return false;
1096 }
1097 }
1098
1099 // If we all PHI nodes are promotable, check to make sure that all
1100 // instructions in the predecessor blocks can be promoted as well. If
1101 // not, we won't be able to get rid of the control flow, so it's not
1102 // worth promoting to select instructions.
1103 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1104 PN = cast<PHINode>(BB->begin());
1105 BasicBlock *Pred = PN->getIncomingBlock(0);
1106 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1107 IfBlock1 = Pred;
1108 DomBlock = *pred_begin(Pred);
1109 for (BasicBlock::iterator I = Pred->begin();
1110 !isa<TerminatorInst>(I); ++I)
1111 if (!AggressiveInsts.count(I)) {
1112 // This is not an aggressive instruction that we can promote.
1113 // Because of this, we won't be able to get rid of the control
1114 // flow, so the xform is not worth it.
1115 return false;
1116 }
1117 }
1118
1119 Pred = PN->getIncomingBlock(1);
1120 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1121 IfBlock2 = Pred;
1122 DomBlock = *pred_begin(Pred);
1123 for (BasicBlock::iterator I = Pred->begin();
1124 !isa<TerminatorInst>(I); ++I)
1125 if (!AggressiveInsts.count(I)) {
1126 // This is not an aggressive instruction that we can promote.
1127 // Because of this, we won't be able to get rid of the control
1128 // flow, so the xform is not worth it.
1129 return false;
1130 }
1131 }
1132
1133 // If we can still promote the PHI nodes after this gauntlet of tests,
1134 // do all of the PHI's now.
1135
1136 // Move all 'aggressive' instructions, which are defined in the
1137 // conditional parts of the if's up to the dominating block.
1138 if (IfBlock1) {
1139 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1140 IfBlock1->getInstList(),
1141 IfBlock1->begin(),
1142 IfBlock1->getTerminator());
1143 }
1144 if (IfBlock2) {
1145 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1146 IfBlock2->getInstList(),
1147 IfBlock2->begin(),
1148 IfBlock2->getTerminator());
1149 }
1150
1151 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1152 // Change the PHI node into a select instruction.
1153 Value *TrueVal =
1154 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1155 Value *FalseVal =
1156 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1157
1158 Value *NV = new SelectInst(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
1159 PN->replaceAllUsesWith(NV);
1160 NV->takeName(PN);
1161
1162 BB->getInstList().erase(PN);
1163 }
1164 return true;
1165}
1166
1167namespace {
1168 /// ConstantIntOrdering - This class implements a stable ordering of constant
1169 /// integers that does not depend on their address. This is important for
1170 /// applications that sort ConstantInt's to ensure uniqueness.
1171 struct ConstantIntOrdering {
1172 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1173 return LHS->getValue().ult(RHS->getValue());
1174 }
1175 };
1176}
1177
1178// SimplifyCFG - This function is used to do simplification of a CFG. For
1179// example, it adjusts branches to branches to eliminate the extra hop, it
1180// eliminates unreachable basic blocks, and does other "peephole" optimization
1181// of the CFG. It returns true if a modification was made.
1182//
1183// WARNING: The entry node of a function may not be simplified.
1184//
1185bool llvm::SimplifyCFG(BasicBlock *BB) {
1186 bool Changed = false;
1187 Function *M = BB->getParent();
1188
1189 assert(BB && BB->getParent() && "Block not embedded in function!");
1190 assert(BB->getTerminator() && "Degenerate basic block encountered!");
1191 assert(&BB->getParent()->getEntryBlock() != BB &&
1192 "Can't Simplify entry block!");
1193
1194 // Remove basic blocks that have no predecessors... which are unreachable.
1195 if (pred_begin(BB) == pred_end(BB) ||
1196 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
1197 DOUT << "Removing BB: \n" << *BB;
1198
1199 // Loop through all of our successors and make sure they know that one
1200 // of their predecessors is going away.
1201 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1202 SI->removePredecessor(BB);
1203
1204 while (!BB->empty()) {
1205 Instruction &I = BB->back();
1206 // If this instruction is used, replace uses with an arbitrary
1207 // value. Because control flow can't get here, we don't care
1208 // what we replace the value with. Note that since this block is
1209 // unreachable, and all values contained within it must dominate their
1210 // uses, that all uses will eventually be removed.
1211 if (!I.use_empty())
1212 // Make all users of this instruction use undef instead
1213 I.replaceAllUsesWith(UndefValue::get(I.getType()));
1214
1215 // Remove the instruction from the basic block
1216 BB->getInstList().pop_back();
1217 }
1218 M->getBasicBlockList().erase(BB);
1219 return true;
1220 }
1221
1222 // Check to see if we can constant propagate this terminator instruction
1223 // away...
1224 Changed |= ConstantFoldTerminator(BB);
1225
1226 // If this is a returning block with only PHI nodes in it, fold the return
1227 // instruction into any unconditional branch predecessors.
1228 //
1229 // If any predecessor is a conditional branch that just selects among
1230 // different return values, fold the replace the branch/return with a select
1231 // and return.
1232 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1233 BasicBlock::iterator BBI = BB->getTerminator();
1234 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
1235 // Find predecessors that end with branches.
1236 std::vector<BasicBlock*> UncondBranchPreds;
1237 std::vector<BranchInst*> CondBranchPreds;
1238 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1239 TerminatorInst *PTI = (*PI)->getTerminator();
1240 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1241 if (BI->isUnconditional())
1242 UncondBranchPreds.push_back(*PI);
1243 else
1244 CondBranchPreds.push_back(BI);
1245 }
1246
1247 // If we found some, do the transformation!
1248 if (!UncondBranchPreds.empty()) {
1249 while (!UncondBranchPreds.empty()) {
1250 BasicBlock *Pred = UncondBranchPreds.back();
1251 DOUT << "FOLDING: " << *BB
1252 << "INTO UNCOND BRANCH PRED: " << *Pred;
1253 UncondBranchPreds.pop_back();
1254 Instruction *UncondBranch = Pred->getTerminator();
1255 // Clone the return and add it to the end of the predecessor.
1256 Instruction *NewRet = RI->clone();
1257 Pred->getInstList().push_back(NewRet);
1258
1259 // If the return instruction returns a value, and if the value was a
1260 // PHI node in "BB", propagate the right value into the return.
1261 if (NewRet->getNumOperands() == 1)
1262 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1263 if (PN->getParent() == BB)
1264 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1265 // Update any PHI nodes in the returning block to realize that we no
1266 // longer branch to them.
1267 BB->removePredecessor(Pred);
1268 Pred->getInstList().erase(UncondBranch);
1269 }
1270
1271 // If we eliminated all predecessors of the block, delete the block now.
1272 if (pred_begin(BB) == pred_end(BB))
1273 // We know there are no successors, so just nuke the block.
1274 M->getBasicBlockList().erase(BB);
1275
1276 return true;
1277 }
1278
1279 // Check out all of the conditional branches going to this return
1280 // instruction. If any of them just select between returns, change the
1281 // branch itself into a select/return pair.
1282 while (!CondBranchPreds.empty()) {
1283 BranchInst *BI = CondBranchPreds.back();
1284 CondBranchPreds.pop_back();
1285 BasicBlock *TrueSucc = BI->getSuccessor(0);
1286 BasicBlock *FalseSucc = BI->getSuccessor(1);
1287 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1288
1289 // Check to see if the non-BB successor is also a return block.
1290 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1291 // Check to see if there are only PHI instructions in this block.
1292 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1293 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1294 // Okay, we found a branch that is going to two return nodes. If
1295 // there is no return value for this function, just change the
1296 // branch into a return.
1297 if (RI->getNumOperands() == 0) {
1298 TrueSucc->removePredecessor(BI->getParent());
1299 FalseSucc->removePredecessor(BI->getParent());
1300 new ReturnInst(0, BI);
1301 BI->getParent()->getInstList().erase(BI);
1302 return true;
1303 }
1304
1305 // Otherwise, figure out what the true and false return values are
1306 // so we can insert a new select instruction.
1307 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1308 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1309
1310 // Unwrap any PHI nodes in the return blocks.
1311 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1312 if (TVPN->getParent() == TrueSucc)
1313 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1314 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1315 if (FVPN->getParent() == FalseSucc)
1316 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1317
1318 // In order for this transformation to be safe, we must be able to
1319 // unconditionally execute both operands to the return. This is
1320 // normally the case, but we could have a potentially-trapping
1321 // constant expression that prevents this transformation from being
1322 // safe.
1323 if ((!isa<ConstantExpr>(TrueValue) ||
1324 !cast<ConstantExpr>(TrueValue)->canTrap()) &&
1325 (!isa<ConstantExpr>(TrueValue) ||
1326 !cast<ConstantExpr>(TrueValue)->canTrap())) {
1327 TrueSucc->removePredecessor(BI->getParent());
1328 FalseSucc->removePredecessor(BI->getParent());
1329
1330 // Insert a new select instruction.
1331 Value *NewRetVal;
1332 Value *BrCond = BI->getCondition();
1333 if (TrueValue != FalseValue)
1334 NewRetVal = new SelectInst(BrCond, TrueValue,
1335 FalseValue, "retval", BI);
1336 else
1337 NewRetVal = TrueValue;
1338
1339 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1340 << "\n " << *BI << "Select = " << *NewRetVal
1341 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1342
1343 new ReturnInst(NewRetVal, BI);
1344 BI->eraseFromParent();
1345 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1346 if (isInstructionTriviallyDead(BrCondI))
1347 BrCondI->eraseFromParent();
1348 return true;
1349 }
1350 }
1351 }
1352 }
1353 }
1354 } else if (isa<UnwindInst>(BB->begin())) {
1355 // Check to see if the first instruction in this block is just an unwind.
1356 // If so, replace any invoke instructions which use this as an exception
1357 // destination with call instructions, and any unconditional branch
1358 // predecessor with an unwind.
1359 //
1360 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1361 while (!Preds.empty()) {
1362 BasicBlock *Pred = Preds.back();
1363 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1364 if (BI->isUnconditional()) {
1365 Pred->getInstList().pop_back(); // nuke uncond branch
1366 new UnwindInst(Pred); // Use unwind.
1367 Changed = true;
1368 }
1369 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1370 if (II->getUnwindDest() == BB) {
1371 // Insert a new branch instruction before the invoke, because this
1372 // is now a fall through...
1373 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1374 Pred->getInstList().remove(II); // Take out of symbol table
1375
1376 // Insert the call now...
1377 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
1378 CallInst *CI = new CallInst(II->getCalledValue(),
David Greeneb1c4a7b2007-08-01 03:43:44 +00001379 Args.begin(), Args.end(), II->getName(), BI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 CI->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001381 CI->setParamAttrs(II->getParamAttrs());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 // If the invoke produced a value, the Call now does instead
1383 II->replaceAllUsesWith(CI);
1384 delete II;
1385 Changed = true;
1386 }
1387
1388 Preds.pop_back();
1389 }
1390
1391 // If this block is now dead, remove it.
1392 if (pred_begin(BB) == pred_end(BB)) {
1393 // We know there are no successors, so just nuke the block.
1394 M->getBasicBlockList().erase(BB);
1395 return true;
1396 }
1397
1398 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1399 if (isValueEqualityComparison(SI)) {
1400 // If we only have one predecessor, and if it is a branch on this value,
1401 // see if that predecessor totally determines the outcome of this switch.
1402 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1403 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1404 return SimplifyCFG(BB) || 1;
1405
1406 // If the block only contains the switch, see if we can fold the block
1407 // away into any preds.
1408 if (SI == &BB->front())
1409 if (FoldValueComparisonIntoPredecessors(SI))
1410 return SimplifyCFG(BB) || 1;
1411 }
1412 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1413 if (BI->isUnconditional()) {
1414 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1415 while (isa<PHINode>(*BBI)) ++BBI;
1416
1417 BasicBlock *Succ = BI->getSuccessor(0);
1418 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1419 Succ != BB) // Don't hurt infinite loops!
1420 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1421 return 1;
1422
1423 } else { // Conditional branch
1424 if (isValueEqualityComparison(BI)) {
1425 // If we only have one predecessor, and if it is a branch on this value,
1426 // see if that predecessor totally determines the outcome of this
1427 // switch.
1428 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1429 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1430 return SimplifyCFG(BB) || 1;
1431
1432 // This block must be empty, except for the setcond inst, if it exists.
1433 BasicBlock::iterator I = BB->begin();
1434 if (&*I == BI ||
1435 (&*I == cast<Instruction>(BI->getCondition()) &&
1436 &*++I == BI))
1437 if (FoldValueComparisonIntoPredecessors(BI))
1438 return SimplifyCFG(BB) | true;
1439 }
1440
1441 // If this is a branch on a phi node in the current block, thread control
1442 // through this block if any PHI node entries are constants.
1443 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1444 if (PN->getParent() == BI->getParent())
1445 if (FoldCondBranchOnPHI(BI))
1446 return SimplifyCFG(BB) | true;
1447
1448 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1449 // branches to us and one of our successors, fold the setcc into the
1450 // predecessor and use logical operations to pick the right destination.
1451 BasicBlock *TrueDest = BI->getSuccessor(0);
1452 BasicBlock *FalseDest = BI->getSuccessor(1);
1453 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition())) {
1454 BasicBlock::iterator CondIt = Cond;
1455 if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) &&
1456 Cond->getParent() == BB && &BB->front() == Cond &&
1457 &*++CondIt == BI && Cond->hasOneUse() &&
1458 TrueDest != BB && FalseDest != BB)
1459 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1460 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1461 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
1462 BasicBlock *PredBlock = *PI;
1463 if (PBI->getSuccessor(0) == FalseDest ||
1464 PBI->getSuccessor(1) == TrueDest) {
1465 // Invert the predecessors condition test (xor it with true),
1466 // which allows us to write this code once.
1467 Value *NewCond =
1468 BinaryOperator::createNot(PBI->getCondition(),
1469 PBI->getCondition()->getName()+".not", PBI);
1470 PBI->setCondition(NewCond);
1471 BasicBlock *OldTrue = PBI->getSuccessor(0);
1472 BasicBlock *OldFalse = PBI->getSuccessor(1);
1473 PBI->setSuccessor(0, OldFalse);
1474 PBI->setSuccessor(1, OldTrue);
1475 }
1476
1477 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1478 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
1479 // Clone Cond into the predecessor basic block, and or/and the
1480 // two conditions together.
1481 Instruction *New = Cond->clone();
1482 PredBlock->getInstList().insert(PBI, New);
1483 New->takeName(Cond);
1484 Cond->setName(New->getName()+".old");
1485 Instruction::BinaryOps Opcode =
1486 PBI->getSuccessor(0) == TrueDest ?
1487 Instruction::Or : Instruction::And;
1488 Value *NewCond =
1489 BinaryOperator::create(Opcode, PBI->getCondition(),
1490 New, "bothcond", PBI);
1491 PBI->setCondition(NewCond);
1492 if (PBI->getSuccessor(0) == BB) {
1493 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1494 PBI->setSuccessor(0, TrueDest);
1495 }
1496 if (PBI->getSuccessor(1) == BB) {
1497 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1498 PBI->setSuccessor(1, FalseDest);
1499 }
1500 return SimplifyCFG(BB) | 1;
1501 }
1502 }
1503 }
1504
1505 // Scan predessor blocks for conditional branches.
1506 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1507 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1508 if (PBI != BI && PBI->isConditional()) {
1509
1510 // If this block ends with a branch instruction, and if there is a
1511 // predecessor that ends on a branch of the same condition, make
1512 // this conditional branch redundant.
1513 if (PBI->getCondition() == BI->getCondition() &&
1514 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1515 // Okay, the outcome of this conditional branch is statically
1516 // knowable. If this block had a single pred, handle specially.
1517 if (BB->getSinglePredecessor()) {
1518 // Turn this into a branch on constant.
1519 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1520 BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue));
1521 return SimplifyCFG(BB); // Nuke the branch on constant.
1522 }
1523
1524 // Otherwise, if there are multiple predecessors, insert a PHI
1525 // that merges in the constant and simplify the block result.
1526 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1527 PHINode *NewPN = new PHINode(Type::Int1Ty,
1528 BI->getCondition()->getName()+".pr",
1529 BB->begin());
1530 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1531 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1532 PBI != BI && PBI->isConditional() &&
1533 PBI->getCondition() == BI->getCondition() &&
1534 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1535 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1536 NewPN->addIncoming(ConstantInt::get(Type::Int1Ty,
1537 CondIsTrue), *PI);
1538 } else {
1539 NewPN->addIncoming(BI->getCondition(), *PI);
1540 }
1541
1542 BI->setCondition(NewPN);
1543 // This will thread the branch.
1544 return SimplifyCFG(BB) | true;
1545 }
1546 }
1547
1548 // If this is a conditional branch in an empty block, and if any
1549 // predecessors is a conditional branch to one of our destinations,
1550 // fold the conditions into logical ops and one cond br.
1551 if (&BB->front() == BI) {
1552 int PBIOp, BIOp;
1553 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1554 PBIOp = BIOp = 0;
1555 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1556 PBIOp = 0; BIOp = 1;
1557 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1558 PBIOp = 1; BIOp = 0;
1559 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1560 PBIOp = BIOp = 1;
1561 } else {
1562 PBIOp = BIOp = -1;
1563 }
1564
1565 // Check to make sure that the other destination of this branch
1566 // isn't BB itself. If so, this is an infinite loop that will
1567 // keep getting unwound.
1568 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1569 PBIOp = BIOp = -1;
1570
1571 // Do not perform this transformation if it would require
1572 // insertion of a large number of select instructions. For targets
1573 // without predication/cmovs, this is a big pessimization.
1574 if (PBIOp != -1) {
1575 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1576
1577 unsigned NumPhis = 0;
1578 for (BasicBlock::iterator II = CommonDest->begin();
1579 isa<PHINode>(II); ++II, ++NumPhis) {
1580 if (NumPhis > 2) {
1581 // Disable this xform.
1582 PBIOp = -1;
1583 break;
1584 }
1585 }
1586 }
1587
1588 // Finally, if everything is ok, fold the branches to logical ops.
1589 if (PBIOp != -1) {
1590 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1591 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1592
1593 // If OtherDest *is* BB, then this is a basic block with just
1594 // a conditional branch in it, where one edge (OtherDesg) goes
1595 // back to the block. We know that the program doesn't get
1596 // stuck in the infinite loop, so the condition must be such
1597 // that OtherDest isn't branched through. Forward to CommonDest,
1598 // and avoid an infinite loop at optimizer time.
1599 if (OtherDest == BB)
1600 OtherDest = CommonDest;
1601
1602 DOUT << "FOLDING BRs:" << *PBI->getParent()
1603 << "AND: " << *BI->getParent();
1604
1605 // BI may have other predecessors. Because of this, we leave
1606 // it alone, but modify PBI.
1607
1608 // Make sure we get to CommonDest on True&True directions.
1609 Value *PBICond = PBI->getCondition();
1610 if (PBIOp)
1611 PBICond = BinaryOperator::createNot(PBICond,
1612 PBICond->getName()+".not",
1613 PBI);
1614 Value *BICond = BI->getCondition();
1615 if (BIOp)
1616 BICond = BinaryOperator::createNot(BICond,
1617 BICond->getName()+".not",
1618 PBI);
1619 // Merge the conditions.
1620 Value *Cond =
1621 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1622
1623 // Modify PBI to branch on the new condition to the new dests.
1624 PBI->setCondition(Cond);
1625 PBI->setSuccessor(0, CommonDest);
1626 PBI->setSuccessor(1, OtherDest);
1627
1628 // OtherDest may have phi nodes. If so, add an entry from PBI's
1629 // block that are identical to the entries for BI's block.
1630 PHINode *PN;
1631 for (BasicBlock::iterator II = OtherDest->begin();
1632 (PN = dyn_cast<PHINode>(II)); ++II) {
1633 Value *V = PN->getIncomingValueForBlock(BB);
1634 PN->addIncoming(V, PBI->getParent());
1635 }
1636
1637 // We know that the CommonDest already had an edge from PBI to
1638 // it. If it has PHIs though, the PHIs may have different
1639 // entries for BB and PBI's BB. If so, insert a select to make
1640 // them agree.
1641 for (BasicBlock::iterator II = CommonDest->begin();
1642 (PN = dyn_cast<PHINode>(II)); ++II) {
1643 Value * BIV = PN->getIncomingValueForBlock(BB);
1644 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1645 Value *PBIV = PN->getIncomingValue(PBBIdx);
1646 if (BIV != PBIV) {
1647 // Insert a select in PBI to pick the right value.
1648 Value *NV = new SelectInst(PBICond, PBIV, BIV,
1649 PBIV->getName()+".mux", PBI);
1650 PN->setIncomingValue(PBBIdx, NV);
1651 }
1652 }
1653
1654 DOUT << "INTO: " << *PBI->getParent();
1655
1656 // This basic block is probably dead. We know it has at least
1657 // one fewer predecessor.
1658 return SimplifyCFG(BB) | true;
1659 }
1660 }
1661 }
1662 }
1663 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1664 // If there are any instructions immediately before the unreachable that can
1665 // be removed, do so.
1666 Instruction *Unreachable = BB->getTerminator();
1667 while (Unreachable != BB->begin()) {
1668 BasicBlock::iterator BBI = Unreachable;
1669 --BBI;
1670 if (isa<CallInst>(BBI)) break;
1671 // Delete this instruction
1672 BB->getInstList().erase(BBI);
1673 Changed = true;
1674 }
1675
1676 // If the unreachable instruction is the first in the block, take a gander
1677 // at all of the predecessors of this instruction, and simplify them.
1678 if (&BB->front() == Unreachable) {
1679 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1680 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1681 TerminatorInst *TI = Preds[i]->getTerminator();
1682
1683 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1684 if (BI->isUnconditional()) {
1685 if (BI->getSuccessor(0) == BB) {
1686 new UnreachableInst(TI);
1687 TI->eraseFromParent();
1688 Changed = true;
1689 }
1690 } else {
1691 if (BI->getSuccessor(0) == BB) {
1692 new BranchInst(BI->getSuccessor(1), BI);
1693 BI->eraseFromParent();
1694 } else if (BI->getSuccessor(1) == BB) {
1695 new BranchInst(BI->getSuccessor(0), BI);
1696 BI->eraseFromParent();
1697 Changed = true;
1698 }
1699 }
1700 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1701 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1702 if (SI->getSuccessor(i) == BB) {
1703 BB->removePredecessor(SI->getParent());
1704 SI->removeCase(i);
1705 --i; --e;
1706 Changed = true;
1707 }
1708 // If the default value is unreachable, figure out the most popular
1709 // destination and make it the default.
1710 if (SI->getSuccessor(0) == BB) {
1711 std::map<BasicBlock*, unsigned> Popularity;
1712 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1713 Popularity[SI->getSuccessor(i)]++;
1714
1715 // Find the most popular block.
1716 unsigned MaxPop = 0;
1717 BasicBlock *MaxBlock = 0;
1718 for (std::map<BasicBlock*, unsigned>::iterator
1719 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1720 if (I->second > MaxPop) {
1721 MaxPop = I->second;
1722 MaxBlock = I->first;
1723 }
1724 }
1725 if (MaxBlock) {
1726 // Make this the new default, allowing us to delete any explicit
1727 // edges to it.
1728 SI->setSuccessor(0, MaxBlock);
1729 Changed = true;
1730
1731 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1732 // it.
1733 if (isa<PHINode>(MaxBlock->begin()))
1734 for (unsigned i = 0; i != MaxPop-1; ++i)
1735 MaxBlock->removePredecessor(SI->getParent());
1736
1737 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1738 if (SI->getSuccessor(i) == MaxBlock) {
1739 SI->removeCase(i);
1740 --i; --e;
1741 }
1742 }
1743 }
1744 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1745 if (II->getUnwindDest() == BB) {
1746 // Convert the invoke to a call instruction. This would be a good
1747 // place to note that the call does not throw though.
1748 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1749 II->removeFromParent(); // Take out of symbol table
1750
1751 // Insert the call now...
1752 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
1753 CallInst *CI = new CallInst(II->getCalledValue(),
David Greeneb1c4a7b2007-08-01 03:43:44 +00001754 Args.begin(), Args.end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755 II->getName(), BI);
1756 CI->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001757 CI->setParamAttrs(II->getParamAttrs());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758 // If the invoke produced a value, the Call does now instead.
1759 II->replaceAllUsesWith(CI);
1760 delete II;
1761 Changed = true;
1762 }
1763 }
1764 }
1765
1766 // If this block is now dead, remove it.
1767 if (pred_begin(BB) == pred_end(BB)) {
1768 // We know there are no successors, so just nuke the block.
1769 M->getBasicBlockList().erase(BB);
1770 return true;
1771 }
1772 }
1773 }
1774
1775 // Merge basic blocks into their predecessor if there is only one distinct
1776 // pred, and if there is only one distinct successor of the predecessor, and
1777 // if there are no PHI nodes.
1778 //
1779 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1780 BasicBlock *OnlyPred = *PI++;
1781 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1782 if (*PI != OnlyPred) {
1783 OnlyPred = 0; // There are multiple different predecessors...
1784 break;
1785 }
1786
1787 BasicBlock *OnlySucc = 0;
1788 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1789 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1790 // Check to see if there is only one distinct successor...
1791 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1792 OnlySucc = BB;
1793 for (; SI != SE; ++SI)
1794 if (*SI != OnlySucc) {
1795 OnlySucc = 0; // There are multiple distinct successors!
1796 break;
1797 }
1798 }
1799
1800 if (OnlySucc) {
1801 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
1802
1803 // Resolve any PHI nodes at the start of the block. They are all
1804 // guaranteed to have exactly one entry if they exist, unless there are
1805 // multiple duplicate (but guaranteed to be equal) entries for the
1806 // incoming edges. This occurs when there are multiple edges from
1807 // OnlyPred to OnlySucc.
1808 //
1809 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1810 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1811 BB->getInstList().pop_front(); // Delete the phi node.
1812 }
1813
1814 // Delete the unconditional branch from the predecessor.
1815 OnlyPred->getInstList().pop_back();
1816
1817 // Move all definitions in the successor to the predecessor.
1818 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1819
1820 // Make all PHI nodes that referred to BB now refer to Pred as their
1821 // source.
1822 BB->replaceAllUsesWith(OnlyPred);
1823
1824 // Inherit predecessors name if it exists.
1825 if (!OnlyPred->hasName())
1826 OnlyPred->takeName(BB);
1827
1828 // Erase basic block from the function.
1829 M->getBasicBlockList().erase(BB);
1830
1831 return true;
1832 }
1833
1834 // Otherwise, if this block only has a single predecessor, and if that block
1835 // is a conditional branch, see if we can hoist any code from this block up
1836 // into our predecessor.
1837 if (OnlyPred)
1838 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1839 if (BI->isConditional()) {
1840 // Get the other block.
1841 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1842 PI = pred_begin(OtherBB);
1843 ++PI;
1844 if (PI == pred_end(OtherBB)) {
1845 // We have a conditional branch to two blocks that are only reachable
1846 // from the condbr. We know that the condbr dominates the two blocks,
1847 // so see if there is any identical code in the "then" and "else"
1848 // blocks. If so, we can hoist it up to the branching block.
1849 Changed |= HoistThenElseCodeToIf(BI);
1850 }
1851 }
1852
1853 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1854 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1855 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1856 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1857 Instruction *Cond = cast<Instruction>(BI->getCondition());
1858 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1859 // 'setne's and'ed together, collect them.
1860 Value *CompVal = 0;
1861 std::vector<ConstantInt*> Values;
1862 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1863 if (CompVal && CompVal->getType()->isInteger()) {
1864 // There might be duplicate constants in the list, which the switch
1865 // instruction can't handle, remove them now.
1866 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1867 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1868
1869 // Figure out which block is which destination.
1870 BasicBlock *DefaultBB = BI->getSuccessor(1);
1871 BasicBlock *EdgeBB = BI->getSuccessor(0);
1872 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1873
1874 // Create the new switch instruction now.
1875 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
1876
1877 // Add all of the 'cases' to the switch instruction.
1878 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1879 New->addCase(Values[i], EdgeBB);
1880
1881 // We added edges from PI to the EdgeBB. As such, if there were any
1882 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1883 // the number of edges added.
1884 for (BasicBlock::iterator BBI = EdgeBB->begin();
1885 isa<PHINode>(BBI); ++BBI) {
1886 PHINode *PN = cast<PHINode>(BBI);
1887 Value *InVal = PN->getIncomingValueForBlock(*PI);
1888 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1889 PN->addIncoming(InVal, *PI);
1890 }
1891
1892 // Erase the old branch instruction.
1893 (*PI)->getInstList().erase(BI);
1894
1895 // Erase the potentially condition tree that was used to computed the
1896 // branch condition.
1897 ErasePossiblyDeadInstructionTree(Cond);
1898 return true;
1899 }
1900 }
1901
1902 // If there is a trivial two-entry PHI node in this basic block, and we can
1903 // eliminate it, do so now.
1904 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1905 if (PN->getNumIncomingValues() == 2)
1906 Changed |= FoldTwoEntryPHINode(PN);
1907
1908 return Changed;
1909}