1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Peephole optimize the CFG.
12 //===----------------------------------------------------------------------===//
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"
32 /// SafeToMergeTerminators - Return true if it is safe to merge these two
33 /// terminator instructions together.
35 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
36 if (SI1 == SI2) return false; // Can't merge with self!
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));
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))
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.
62 static 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
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);
75 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
76 // almost-empty BB ending in an unconditional branch to Succ, into succ.
78 // Assumption: Succ is the single successor for BB.
80 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
81 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
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!
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);
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
100 if (PN->getIncomingValueForBlock(BB) !=
101 PN->getIncomingValueForBlock(*PI))
102 return false; // Values are not equal...
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;
113 // If the predecessors of Succ are only BB, handle it.
115 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
120 if (IsSafe) return true;
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;
128 if (cast<Instruction>(*UI)->getParent() != Succ)
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))
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.
146 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
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
153 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
155 DOUT << "Killing Trivial BB: \n" << *BB;
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
161 const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
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!");
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));
177 // Add an incoming value for each of the new incoming values.
178 for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
179 PN->addIncoming(OldVal, BBPreds[i]);
184 if (isa<PHINode>(&BB->front())) {
185 SmallVector<BasicBlock*, 16>
186 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
188 // Move all PHI nodes in BB to Succ if they are alive, otherwise
190 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
191 if (PN->use_empty()) {
192 // Just remove the dead phi. This happens if Succ's PHIs were the only
193 // users of the PHI nodes.
194 PN->eraseFromParent();
196 // The instruction is alive, so this means that Succ must have
197 // *ONLY* had BB as a predecessor, and the PHI node is still valid
198 // now. Simply move it into Succ, because we know that BB
199 // strictly dominated Succ.
200 Succ->getInstList().splice(Succ->begin(),
201 BB->getInstList(), BB->begin());
203 // We need to add new entries for the PHI node to account for
204 // predecessors of Succ that the PHI node does not take into
205 // account. At this point, since we know that BB dominated succ,
206 // this means that we should any newly added incoming edges should
207 // use the PHI node as the value for these edges, because they are
209 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
210 if (OldSuccPreds[i] != BB)
211 PN->addIncoming(PN, OldSuccPreds[i]);
215 // Everything that jumped to BB now goes to Succ.
216 BB->replaceAllUsesWith(Succ);
217 if (!Succ->hasName()) Succ->takeName(BB);
218 BB->eraseFromParent(); // Delete the old basic block.
222 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
223 /// presumably PHI nodes in it), check to see if the merge at this block is due
224 /// to an "if condition". If so, return the boolean condition that determines
225 /// which entry into BB will be taken. Also, return by references the block
226 /// that will be entered from if the condition is true, and the block that will
227 /// be entered if the condition is false.
230 static Value *GetIfCondition(BasicBlock *BB,
231 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
232 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
233 "Function can only handle blocks with 2 predecessors!");
234 BasicBlock *Pred1 = *pred_begin(BB);
235 BasicBlock *Pred2 = *++pred_begin(BB);
237 // We can only handle branches. Other control flow will be lowered to
238 // branches if possible anyway.
239 if (!isa<BranchInst>(Pred1->getTerminator()) ||
240 !isa<BranchInst>(Pred2->getTerminator()))
242 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
243 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
245 // Eliminate code duplication by ensuring that Pred1Br is conditional if
247 if (Pred2Br->isConditional()) {
248 // If both branches are conditional, we don't have an "if statement". In
249 // reality, we could transform this case, but since the condition will be
250 // required anyway, we stand no chance of eliminating it, so the xform is
251 // probably not profitable.
252 if (Pred1Br->isConditional())
255 std::swap(Pred1, Pred2);
256 std::swap(Pred1Br, Pred2Br);
259 if (Pred1Br->isConditional()) {
260 // If we found a conditional branch predecessor, make sure that it branches
261 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
262 if (Pred1Br->getSuccessor(0) == BB &&
263 Pred1Br->getSuccessor(1) == Pred2) {
266 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
267 Pred1Br->getSuccessor(1) == BB) {
271 // We know that one arm of the conditional goes to BB, so the other must
272 // go somewhere unrelated, and this must not be an "if statement".
276 // The only thing we have to watch out for here is to make sure that Pred2
277 // doesn't have incoming edges from other blocks. If it does, the condition
278 // doesn't dominate BB.
279 if (++pred_begin(Pred2) != pred_end(Pred2))
282 return Pred1Br->getCondition();
285 // Ok, if we got here, both predecessors end with an unconditional branch to
286 // BB. Don't panic! If both blocks only have a single (identical)
287 // predecessor, and THAT is a conditional branch, then we're all ok!
288 if (pred_begin(Pred1) == pred_end(Pred1) ||
289 ++pred_begin(Pred1) != pred_end(Pred1) ||
290 pred_begin(Pred2) == pred_end(Pred2) ||
291 ++pred_begin(Pred2) != pred_end(Pred2) ||
292 *pred_begin(Pred1) != *pred_begin(Pred2))
295 // Otherwise, if this is a conditional branch, then we can use it!
296 BasicBlock *CommonPred = *pred_begin(Pred1);
297 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
298 assert(BI->isConditional() && "Two successors but not conditional?");
299 if (BI->getSuccessor(0) == Pred1) {
306 return BI->getCondition();
312 // If we have a merge point of an "if condition" as accepted above, return true
313 // if the specified value dominates the block. We don't handle the true
314 // generality of domination here, just a special case which works well enough
317 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
318 // see if V (which must be an instruction) is cheap to compute and is
319 // non-trapping. If both are true, the instruction is inserted into the set and
321 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
322 std::set<Instruction*> *AggressiveInsts) {
323 Instruction *I = dyn_cast<Instruction>(V);
325 // Non-instructions all dominate instructions, but not all constantexprs
326 // can be executed unconditionally.
327 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
332 BasicBlock *PBB = I->getParent();
334 // We don't want to allow weird loops that might have the "if condition" in
335 // the bottom of this block.
336 if (PBB == BB) return false;
338 // If this instruction is defined in a block that contains an unconditional
339 // branch to BB, then it must be in the 'conditional' part of the "if
341 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
342 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
343 if (!AggressiveInsts) return false;
344 // Okay, it looks like the instruction IS in the "condition". Check to
345 // see if its a cheap instruction to unconditionally compute, and if it
346 // only uses stuff defined outside of the condition. If so, hoist it out.
347 switch (I->getOpcode()) {
348 default: return false; // Cannot hoist this out safely.
349 case Instruction::Load:
350 // We can hoist loads that are non-volatile and obviously cannot trap.
351 if (cast<LoadInst>(I)->isVolatile())
353 if (!isa<AllocaInst>(I->getOperand(0)) &&
354 !isa<Constant>(I->getOperand(0)))
357 // Finally, we have to check to make sure there are no instructions
358 // before the load in its basic block, as we are going to hoist the loop
359 // out to its predecessor.
360 if (PBB->begin() != BasicBlock::iterator(I))
363 case Instruction::Add:
364 case Instruction::Sub:
365 case Instruction::And:
366 case Instruction::Or:
367 case Instruction::Xor:
368 case Instruction::Shl:
369 case Instruction::LShr:
370 case Instruction::AShr:
371 case Instruction::ICmp:
372 case Instruction::FCmp:
373 if (I->getOperand(0)->getType()->isFPOrFPVector())
374 return false; // FP arithmetic might trap.
375 break; // These are all cheap and non-trapping instructions.
378 // Okay, we can only really hoist these out if their operands are not
379 // defined in the conditional region.
380 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
381 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
383 // Okay, it's safe to do this! Remember this instruction.
384 AggressiveInsts->insert(I);
390 // GatherConstantSetEQs - Given a potentially 'or'd together collection of
391 // icmp_eq instructions that compare a value against a constant, return the
392 // value being compared, and stick the constant into the Values vector.
393 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
394 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
395 if (Inst->getOpcode() == Instruction::ICmp &&
396 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
397 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
399 return Inst->getOperand(0);
400 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
402 return Inst->getOperand(1);
404 } else if (Inst->getOpcode() == Instruction::Or) {
405 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
406 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
414 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
415 // setne instructions that compare a value against a constant, return the value
416 // being compared, and stick the constant into the Values vector.
417 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
418 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
419 if (Inst->getOpcode() == Instruction::ICmp &&
420 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
421 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
423 return Inst->getOperand(0);
424 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
426 return Inst->getOperand(1);
428 } else if (Inst->getOpcode() == Instruction::And) {
429 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
430 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
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.
443 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
444 std::vector<ConstantInt*> &Values) {
445 if (Cond->getOpcode() == Instruction::Or) {
446 CompVal = GatherConstantSetEQs(Cond, Values);
448 // Return true to indicate that the condition is true if the CompVal is
449 // equal to one of the constants.
451 } else if (Cond->getOpcode() == Instruction::And) {
452 CompVal = GatherConstantSetNEs(Cond, Values);
454 // Return false to indicate that the condition is false if the CompVal is
455 // equal to one of the constants.
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.
464 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
465 if (!isInstructionTriviallyDead(I)) return;
467 SmallVector<Instruction*, 16> InstrsToInspect;
468 InstrsToInspect.push_back(I);
470 while (!InstrsToInspect.empty()) {
471 I = InstrsToInspect.back();
472 InstrsToInspect.pop_back();
474 if (!isInstructionTriviallyDead(I)) continue;
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);
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);
488 // Remove dead instruction.
489 I->eraseFromParent();
493 // isValueEqualityComparison - Return true if the specified terminator checks to
494 // see if a value is equal to constant integer value.
495 static 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)
503 return SI->getCondition();
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);
515 // Given a value comparison instruction, decode all of the 'cases' that it
516 // represents and return the 'default' block.
518 GetValueEqualityComparisonCases(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();
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);
537 // EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
538 // in the list that match the specified block.
539 static 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);
548 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
551 ValuesOverlap(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;
555 // Make V1 be smaller than V2.
556 if (V1->size() > V2->size())
559 if (V1->size() == 0) return false;
560 if (V1->size() == 1) {
562 ConstantInt *TheVal = (*V1)[0].first;
563 for (unsigned i = 0, e = V2->size(); i != e; ++i)
564 if (TheVal == (*V2)[i].first)
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)
575 if ((*V1)[i1].first < (*V2)[i2].first)
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
589 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
591 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
592 if (!PredVal) return false; // Not a value comparison in predecessor.
594 Value *ThisVal = isValueEqualityComparison(TI);
595 assert(ThisVal && "This isn't a value comparison!!");
596 if (ThisVal != PredVal) return false; // Different predicates.
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(),
602 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
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.
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
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
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);
624 // Remove PHI node entries for the dead edge.
625 ThisCases[0].second->removePredecessor(TI->getParent());
627 DOUT << "Threading pred instr: " << *Pred->getTerminator()
628 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
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);
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);
643 DOUT << "Threading pred instr: " << *Pred->getTerminator()
644 << "Through successor TI: " << *TI;
646 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
647 if (DeadCases.count(SI->getCaseValue(i))) {
648 SI->getSuccessor(i)->removePredecessor(TI->getParent());
652 DOUT << "Leaving: " << *TI << "\n";
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) {
665 TIV = PredCases[i].first;
667 return false; // Cannot handle multiple values coming to this block.
669 assert(TIV && "No edge from pred to succ?");
671 // Okay, we found the one constant that our value can be if we get into TI's
672 // BB. Find out which successor will unconditionally be branched to.
673 BasicBlock *TheRealDest = 0;
674 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
675 if (ThisCases[i].first == TIV) {
676 TheRealDest = ThisCases[i].second;
680 // If not handled by any explicit cases, it is handled by the default case.
681 if (TheRealDest == 0) TheRealDest = ThisDef;
683 // Remove PHI node entries for dead edges.
684 BasicBlock *CheckEdge = TheRealDest;
685 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
686 if (*SI != CheckEdge)
687 (*SI)->removePredecessor(TIBB);
691 // Insert the new branch.
692 Instruction *NI = new BranchInst(TheRealDest, TI);
694 DOUT << "Threading pred instr: " << *Pred->getTerminator()
695 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
696 Instruction *Cond = 0;
697 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
698 Cond = dyn_cast<Instruction>(BI->getCondition());
699 TI->eraseFromParent(); // Nuke the old one.
701 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
707 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
708 // equality comparison instruction (either a switch or a branch on "X == c").
709 // See if any of the predecessors of the terminator block are value comparisons
710 // on the same value. If so, and if safe to do so, fold them together.
711 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
712 BasicBlock *BB = TI->getParent();
713 Value *CV = isValueEqualityComparison(TI); // CondVal
714 assert(CV && "Not a comparison?");
715 bool Changed = false;
717 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
718 while (!Preds.empty()) {
719 BasicBlock *Pred = Preds.back();
722 // See if the predecessor is a comparison with the same value.
723 TerminatorInst *PTI = Pred->getTerminator();
724 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
726 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
727 // Figure out which 'cases' to copy from SI to PSI.
728 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
729 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
731 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
732 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
734 // Based on whether the default edge from PTI goes to BB or not, fill in
735 // PredCases and PredDefault with the new switch cases we would like to
737 SmallVector<BasicBlock*, 8> NewSuccessors;
739 if (PredDefault == BB) {
740 // If this is the default destination from PTI, only the edges in TI
741 // that don't occur in PTI, or that branch to BB will be activated.
742 std::set<ConstantInt*> PTIHandled;
743 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
744 if (PredCases[i].second != BB)
745 PTIHandled.insert(PredCases[i].first);
747 // The default destination is BB, we don't need explicit targets.
748 std::swap(PredCases[i], PredCases.back());
749 PredCases.pop_back();
753 // Reconstruct the new switch statement we will be building.
754 if (PredDefault != BBDefault) {
755 PredDefault->removePredecessor(Pred);
756 PredDefault = BBDefault;
757 NewSuccessors.push_back(BBDefault);
759 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
760 if (!PTIHandled.count(BBCases[i].first) &&
761 BBCases[i].second != BBDefault) {
762 PredCases.push_back(BBCases[i]);
763 NewSuccessors.push_back(BBCases[i].second);
767 // If this is not the default destination from PSI, only the edges
768 // in SI that occur in PSI with a destination of BB will be
770 std::set<ConstantInt*> PTIHandled;
771 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
772 if (PredCases[i].second == BB) {
773 PTIHandled.insert(PredCases[i].first);
774 std::swap(PredCases[i], PredCases.back());
775 PredCases.pop_back();
779 // Okay, now we know which constants were sent to BB from the
780 // predecessor. Figure out where they will all go now.
781 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
782 if (PTIHandled.count(BBCases[i].first)) {
783 // If this is one we are capable of getting...
784 PredCases.push_back(BBCases[i]);
785 NewSuccessors.push_back(BBCases[i].second);
786 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
789 // If there are any constants vectored to BB that TI doesn't handle,
790 // they must go to the default destination of TI.
791 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
792 E = PTIHandled.end(); I != E; ++I) {
793 PredCases.push_back(std::make_pair(*I, BBDefault));
794 NewSuccessors.push_back(BBDefault);
798 // Okay, at this point, we know which new successor Pred will get. Make
799 // sure we update the number of entries in the PHI nodes for these
801 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
802 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
804 // Now that the successors are updated, create the new Switch instruction.
805 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
806 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
807 NewSI->addCase(PredCases[i].first, PredCases[i].second);
809 Instruction *DeadCond = 0;
810 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
811 // If PTI is a branch, remember the condition.
812 DeadCond = dyn_cast<Instruction>(BI->getCondition());
813 Pred->getInstList().erase(PTI);
815 // If the condition is dead now, remove the instruction tree.
816 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
818 // Okay, last check. If BB is still a successor of PSI, then we must
819 // have an infinite loop case. If so, add an infinitely looping block
820 // to handle the case to preserve the behavior of the code.
821 BasicBlock *InfLoopBlock = 0;
822 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
823 if (NewSI->getSuccessor(i) == BB) {
824 if (InfLoopBlock == 0) {
825 // Insert it at the end of the loop, because it's either code,
826 // or it won't matter if it's hot. :)
827 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
828 new BranchInst(InfLoopBlock, InfLoopBlock);
830 NewSI->setSuccessor(i, InfLoopBlock);
839 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
840 /// BB2, hoist any common code in the two blocks up into the branch block. The
841 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
842 static bool HoistThenElseCodeToIf(BranchInst *BI) {
843 // This does very trivial matching, with limited scanning, to find identical
844 // instructions in the two blocks. In particular, we don't want to get into
845 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
846 // such, we currently just scan for obviously identical instructions in an
848 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
849 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
851 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
852 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
853 isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
856 // If we get here, we can hoist at least one instruction.
857 BasicBlock *BIParent = BI->getParent();
860 // If we are hoisting the terminator instruction, don't move one (making a
861 // broken BB), instead clone it, and remove BI.
862 if (isa<TerminatorInst>(I1))
863 goto HoistTerminator;
865 // For a normal instruction, we just move one to right before the branch,
866 // then replace all uses of the other with the first. Finally, we remove
867 // the now redundant second instruction.
868 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
869 if (!I2->use_empty())
870 I2->replaceAllUsesWith(I1);
871 BB2->getInstList().erase(I2);
875 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
880 // Okay, it is safe to hoist the terminator.
881 Instruction *NT = I1->clone();
882 BIParent->getInstList().insert(BI, NT);
883 if (NT->getType() != Type::VoidTy) {
884 I1->replaceAllUsesWith(NT);
885 I2->replaceAllUsesWith(NT);
889 // Hoisting one of the terminators from our successor is a great thing.
890 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
891 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
892 // nodes, so we insert select instruction to compute the final result.
893 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
894 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
896 for (BasicBlock::iterator BBI = SI->begin();
897 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
898 Value *BB1V = PN->getIncomingValueForBlock(BB1);
899 Value *BB2V = PN->getIncomingValueForBlock(BB2);
901 // These values do not agree. Insert a select instruction before NT
902 // that determines the right value.
903 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
905 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
906 BB1V->getName()+"."+BB2V->getName(), NT);
907 // Make the PHI node use the select for all incoming values for BB1/BB2
908 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
909 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
910 PN->setIncomingValue(i, SI);
915 // Update any PHI nodes in our new successors.
916 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
917 AddPredecessorToBlock(*SI, BIParent, BB1);
919 BI->eraseFromParent();
923 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
924 /// across this block.
925 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
926 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
929 // If this basic block contains anything other than a PHI (which controls the
930 // branch) and branch itself, bail out. FIXME: improve this in the future.
931 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
932 if (Size > 10) return false; // Don't clone large BB's.
934 // We can only support instructions that are do not define values that are
935 // live outside of the current basic block.
936 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
938 Instruction *U = cast<Instruction>(*UI);
939 if (U->getParent() != BB || isa<PHINode>(U)) return false;
942 // Looks ok, continue checking.
948 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
949 /// that is defined in the same block as the branch and if any PHI entries are
950 /// constants, thread edges corresponding to that entry to be branches to their
951 /// ultimate destination.
952 static bool FoldCondBranchOnPHI(BranchInst *BI) {
953 BasicBlock *BB = BI->getParent();
954 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
955 // NOTE: we currently cannot transform this case if the PHI node is used
956 // outside of the block.
957 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
960 // Degenerate case of a single entry PHI.
961 if (PN->getNumIncomingValues() == 1) {
962 if (PN->getIncomingValue(0) != PN)
963 PN->replaceAllUsesWith(PN->getIncomingValue(0));
965 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
966 PN->eraseFromParent();
970 // Now we know that this block has multiple preds and two succs.
971 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
973 // Okay, this is a simple enough basic block. See if any phi values are
975 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
977 if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
978 CB->getType() == Type::Int1Ty) {
979 // Okay, we now know that all edges from PredBB should be revectored to
980 // branch to RealDest.
981 BasicBlock *PredBB = PN->getIncomingBlock(i);
982 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
984 if (RealDest == BB) continue; // Skip self loops.
986 // The dest block might have PHI nodes, other predecessors and other
987 // difficult cases. Instead of being smart about this, just insert a new
988 // block that jumps to the destination block, effectively splitting
989 // the edge we are about to create.
990 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
991 RealDest->getParent(), RealDest);
992 new BranchInst(RealDest, EdgeBB);
994 for (BasicBlock::iterator BBI = RealDest->begin();
995 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
996 Value *V = PN->getIncomingValueForBlock(BB);
997 PN->addIncoming(V, EdgeBB);
1000 // BB may have instructions that are being threaded over. Clone these
1001 // instructions into EdgeBB. We know that there will be no uses of the
1002 // cloned instructions outside of EdgeBB.
1003 BasicBlock::iterator InsertPt = EdgeBB->begin();
1004 std::map<Value*, Value*> TranslateMap; // Track translated values.
1005 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1006 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1007 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1009 // Clone the instruction.
1010 Instruction *N = BBI->clone();
1011 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1013 // Update operands due to translation.
1014 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1015 std::map<Value*, Value*>::iterator PI =
1016 TranslateMap.find(N->getOperand(i));
1017 if (PI != TranslateMap.end())
1018 N->setOperand(i, PI->second);
1021 // Check for trivial simplification.
1022 if (Constant *C = ConstantFoldInstruction(N)) {
1023 TranslateMap[BBI] = C;
1024 delete N; // Constant folded away, don't need actual inst
1026 // Insert the new instruction into its new home.
1027 EdgeBB->getInstList().insert(InsertPt, N);
1028 if (!BBI->use_empty())
1029 TranslateMap[BBI] = N;
1034 // Loop over all of the edges from PredBB to BB, changing them to branch
1035 // to EdgeBB instead.
1036 TerminatorInst *PredBBTI = PredBB->getTerminator();
1037 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1038 if (PredBBTI->getSuccessor(i) == BB) {
1039 BB->removePredecessor(PredBB);
1040 PredBBTI->setSuccessor(i, EdgeBB);
1043 // Recurse, simplifying any other constants.
1044 return FoldCondBranchOnPHI(BI) | true;
1051 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1052 /// PHI node, see if we can eliminate it.
1053 static bool FoldTwoEntryPHINode(PHINode *PN) {
1054 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1055 // statement", which has a very simple dominance structure. Basically, we
1056 // are trying to find the condition that is being branched on, which
1057 // subsequently causes this merge to happen. We really want control
1058 // dependence information for this check, but simplifycfg can't keep it up
1059 // to date, and this catches most of the cases we care about anyway.
1061 BasicBlock *BB = PN->getParent();
1062 BasicBlock *IfTrue, *IfFalse;
1063 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1064 if (!IfCond) return false;
1066 // Okay, we found that we can merge this two-entry phi node into a select.
1067 // Doing so would require us to fold *all* two entry phi nodes in this block.
1068 // At some point this becomes non-profitable (particularly if the target
1069 // doesn't support cmov's). Only do this transformation if there are two or
1070 // fewer PHI nodes in this block.
1071 unsigned NumPhis = 0;
1072 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1076 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1077 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
1079 // Loop over the PHI's seeing if we can promote them all to select
1080 // instructions. While we are at it, keep track of the instructions
1081 // that need to be moved to the dominating block.
1082 std::set<Instruction*> AggressiveInsts;
1084 BasicBlock::iterator AfterPHIIt = BB->begin();
1085 while (isa<PHINode>(AfterPHIIt)) {
1086 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1087 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1088 if (PN->getIncomingValue(0) != PN)
1089 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1091 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1092 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1093 &AggressiveInsts) ||
1094 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1095 &AggressiveInsts)) {
1100 // If we all PHI nodes are promotable, check to make sure that all
1101 // instructions in the predecessor blocks can be promoted as well. If
1102 // not, we won't be able to get rid of the control flow, so it's not
1103 // worth promoting to select instructions.
1104 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1105 PN = cast<PHINode>(BB->begin());
1106 BasicBlock *Pred = PN->getIncomingBlock(0);
1107 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1109 DomBlock = *pred_begin(Pred);
1110 for (BasicBlock::iterator I = Pred->begin();
1111 !isa<TerminatorInst>(I); ++I)
1112 if (!AggressiveInsts.count(I)) {
1113 // This is not an aggressive instruction that we can promote.
1114 // Because of this, we won't be able to get rid of the control
1115 // flow, so the xform is not worth it.
1120 Pred = PN->getIncomingBlock(1);
1121 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1123 DomBlock = *pred_begin(Pred);
1124 for (BasicBlock::iterator I = Pred->begin();
1125 !isa<TerminatorInst>(I); ++I)
1126 if (!AggressiveInsts.count(I)) {
1127 // This is not an aggressive instruction that we can promote.
1128 // Because of this, we won't be able to get rid of the control
1129 // flow, so the xform is not worth it.
1134 // If we can still promote the PHI nodes after this gauntlet of tests,
1135 // do all of the PHI's now.
1137 // Move all 'aggressive' instructions, which are defined in the
1138 // conditional parts of the if's up to the dominating block.
1140 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1141 IfBlock1->getInstList(),
1143 IfBlock1->getTerminator());
1146 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1147 IfBlock2->getInstList(),
1149 IfBlock2->getTerminator());
1152 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1153 // Change the PHI node into a select instruction.
1155 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1157 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1159 Value *NV = new SelectInst(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
1160 PN->replaceAllUsesWith(NV);
1163 BB->getInstList().erase(PN);
1169 /// ConstantIntOrdering - This class implements a stable ordering of constant
1170 /// integers that does not depend on their address. This is important for
1171 /// applications that sort ConstantInt's to ensure uniqueness.
1172 struct ConstantIntOrdering {
1173 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1174 return LHS->getValue().ult(RHS->getValue());
1179 // SimplifyCFG - This function is used to do simplification of a CFG. For
1180 // example, it adjusts branches to branches to eliminate the extra hop, it
1181 // eliminates unreachable basic blocks, and does other "peephole" optimization
1182 // of the CFG. It returns true if a modification was made.
1184 // WARNING: The entry node of a function may not be simplified.
1186 bool llvm::SimplifyCFG(BasicBlock *BB) {
1187 bool Changed = false;
1188 Function *M = BB->getParent();
1190 assert(BB && BB->getParent() && "Block not embedded in function!");
1191 assert(BB->getTerminator() && "Degenerate basic block encountered!");
1192 assert(&BB->getParent()->getEntryBlock() != BB &&
1193 "Can't Simplify entry block!");
1195 // Remove basic blocks that have no predecessors... which are unreachable.
1196 if ((pred_begin(BB) == pred_end(BB)) ||
1197 (*pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB))) {
1198 DOUT << "Removing BB: \n" << *BB;
1200 // Loop through all of our successors and make sure they know that one
1201 // of their predecessors is going away.
1202 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1203 SI->removePredecessor(BB);
1205 while (!BB->empty()) {
1206 Instruction &I = BB->back();
1207 // If this instruction is used, replace uses with an arbitrary
1208 // value. Because control flow can't get here, we don't care
1209 // what we replace the value with. Note that since this block is
1210 // unreachable, and all values contained within it must dominate their
1211 // uses, that all uses will eventually be removed.
1213 // Make all users of this instruction use undef instead
1214 I.replaceAllUsesWith(UndefValue::get(I.getType()));
1216 // Remove the instruction from the basic block
1217 BB->getInstList().pop_back();
1219 M->getBasicBlockList().erase(BB);
1223 // Check to see if we can constant propagate this terminator instruction
1225 Changed |= ConstantFoldTerminator(BB);
1227 // If there is a trivial two-entry PHI node in this basic block, and we can
1228 // eliminate it, do so now.
1229 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1230 if (PN->getNumIncomingValues() == 2)
1231 Changed |= FoldTwoEntryPHINode(PN);
1233 // If this is a returning block with only PHI nodes in it, fold the return
1234 // instruction into any unconditional branch predecessors.
1236 // If any predecessor is a conditional branch that just selects among
1237 // different return values, fold the replace the branch/return with a select
1239 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1240 BasicBlock::iterator BBI = BB->getTerminator();
1241 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
1242 // Find predecessors that end with branches.
1243 SmallVector<BasicBlock*, 8> UncondBranchPreds;
1244 SmallVector<BranchInst*, 8> CondBranchPreds;
1245 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1246 if ((*PI)->getUnwindDest() == BB) continue;
1248 TerminatorInst *PTI = (*PI)->getTerminator();
1249 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
1250 if (BI->isUnconditional())
1251 UncondBranchPreds.push_back(*PI);
1253 CondBranchPreds.push_back(BI);
1257 // If we found some, do the transformation!
1258 if (!UncondBranchPreds.empty()) {
1259 while (!UncondBranchPreds.empty()) {
1260 BasicBlock *Pred = UncondBranchPreds.back();
1261 DOUT << "FOLDING: " << *BB
1262 << "INTO UNCOND BRANCH PRED: " << *Pred;
1263 UncondBranchPreds.pop_back();
1264 Instruction *UncondBranch = Pred->getTerminator();
1265 // Clone the return and add it to the end of the predecessor.
1266 Instruction *NewRet = RI->clone();
1267 Pred->getInstList().push_back(NewRet);
1269 // If the return instruction returns a value, and if the value was a
1270 // PHI node in "BB", propagate the right value into the return.
1271 if (NewRet->getNumOperands() == 1)
1272 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1273 if (PN->getParent() == BB)
1274 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1275 // Update any PHI nodes in the returning block to realize that we no
1276 // longer branch to them.
1277 BB->removePredecessor(Pred);
1278 Pred->getInstList().erase(UncondBranch);
1281 // If we eliminated all predecessors of the block, delete the block now.
1282 if (pred_begin(BB) == pred_end(BB))
1283 // We know there are no successors, so just nuke the block.
1284 M->getBasicBlockList().erase(BB);
1289 // Check out all of the conditional branches going to this return
1290 // instruction. If any of them just select between returns, change the
1291 // branch itself into a select/return pair.
1292 while (!CondBranchPreds.empty()) {
1293 BranchInst *BI = CondBranchPreds.back();
1294 CondBranchPreds.pop_back();
1295 BasicBlock *TrueSucc = BI->getSuccessor(0);
1296 BasicBlock *FalseSucc = BI->getSuccessor(1);
1297 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1299 // Check to see if the non-BB successor is also a return block.
1300 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1301 // Check to see if there are only PHI instructions in this block.
1302 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1303 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1304 // Okay, we found a branch that is going to two return nodes. If
1305 // there is no return value for this function, just change the
1306 // branch into a return.
1307 if (RI->getNumOperands() == 0) {
1308 TrueSucc->removePredecessor(BI->getParent());
1309 FalseSucc->removePredecessor(BI->getParent());
1310 new ReturnInst(0, BI);
1311 BI->getParent()->getInstList().erase(BI);
1315 // Otherwise, figure out what the true and false return values are
1316 // so we can insert a new select instruction.
1317 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1318 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1320 // Unwrap any PHI nodes in the return blocks.
1321 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1322 if (TVPN->getParent() == TrueSucc)
1323 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1324 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1325 if (FVPN->getParent() == FalseSucc)
1326 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1328 // In order for this transformation to be safe, we must be able to
1329 // unconditionally execute both operands to the return. This is
1330 // normally the case, but we could have a potentially-trapping
1331 // constant expression that prevents this transformation from being
1333 if ((!isa<ConstantExpr>(TrueValue) ||
1334 !cast<ConstantExpr>(TrueValue)->canTrap()) &&
1335 (!isa<ConstantExpr>(TrueValue) ||
1336 !cast<ConstantExpr>(TrueValue)->canTrap())) {
1337 TrueSucc->removePredecessor(BI->getParent());
1338 FalseSucc->removePredecessor(BI->getParent());
1340 // Insert a new select instruction.
1342 Value *BrCond = BI->getCondition();
1343 if (TrueValue != FalseValue)
1344 NewRetVal = new SelectInst(BrCond, TrueValue,
1345 FalseValue, "retval", BI);
1347 NewRetVal = TrueValue;
1349 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1350 << "\n " << *BI << "Select = " << *NewRetVal
1351 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1353 new ReturnInst(NewRetVal, BI);
1354 BI->eraseFromParent();
1355 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1356 if (isInstructionTriviallyDead(BrCondI))
1357 BrCondI->eraseFromParent();
1364 } else if (isa<UnwindInst>(BB->begin())) {
1365 // Check to see if the first instruction in this block is just an unwind.
1366 // If so, replace any invoke instructions which use this as an exception
1367 // destination with call instructions, and any unconditional branch
1368 // predecessor with an unwind.
1370 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
1371 while (!Preds.empty()) {
1372 BasicBlock *Pred = Preds.back();
1374 if (Pred->getUnwindDest() == BB) {
1375 Pred->setUnwindDest(NULL);
1379 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1380 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
1381 Pred->getInstList().pop_back(); // nuke uncond branch
1382 new UnwindInst(Pred); // Use unwind.
1385 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1386 if (II->getUnwindDest() == BB) {
1387 // Insert a new branch instruction before the invoke, because this
1388 // is now a fall through...
1389 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1390 Pred->getInstList().remove(II); // Take out of symbol table
1392 // Insert the call now...
1393 SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
1394 CallInst *CI = new CallInst(II->getCalledValue(),
1395 Args.begin(), Args.end(), II->getName(), BI);
1396 CI->setCallingConv(II->getCallingConv());
1397 CI->setParamAttrs(II->getParamAttrs());
1398 // If the invoke produced a value, the Call now does instead
1399 II->replaceAllUsesWith(CI);
1407 // If this block is now dead, remove it.
1408 if (pred_begin(BB) == pred_end(BB)) {
1409 // We know there are no successors, so just nuke the block.
1410 M->getBasicBlockList().erase(BB);
1414 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1415 if (isValueEqualityComparison(SI)) {
1416 // If we only have one predecessor, and if it is a branch on this value,
1417 // see if that predecessor totally determines the outcome of this switch.
1418 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1419 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1420 return SimplifyCFG(BB) || 1;
1422 // If the block only contains the switch, see if we can fold the block
1423 // away into any preds.
1424 if (SI == &BB->front())
1425 if (FoldValueComparisonIntoPredecessors(SI))
1426 return SimplifyCFG(BB) || 1;
1428 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1429 if (BI->isUnconditional()) {
1430 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1431 while (isa<PHINode>(*BBI)) ++BBI;
1433 BasicBlock *Succ = BI->getSuccessor(0);
1434 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1435 Succ != BB) // Don't hurt infinite loops!
1436 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1439 } else { // Conditional branch
1440 if (isValueEqualityComparison(BI)) {
1441 // If we only have one predecessor, and if it is a branch on this value,
1442 // see if that predecessor totally determines the outcome of this
1444 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1445 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1446 return SimplifyCFG(BB) || 1;
1448 // This block must be empty, except for the setcond inst, if it exists.
1449 BasicBlock::iterator I = BB->begin();
1451 (&*I == cast<Instruction>(BI->getCondition()) &&
1453 if (FoldValueComparisonIntoPredecessors(BI))
1454 return SimplifyCFG(BB) | true;
1457 // If this is a branch on a phi node in the current block, thread control
1458 // through this block if any PHI node entries are constants.
1459 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1460 if (PN->getParent() == BI->getParent())
1461 if (FoldCondBranchOnPHI(BI))
1462 return SimplifyCFG(BB) | true;
1464 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1465 // branches to us and one of our successors, fold the setcc into the
1466 // predecessor and use logical operations to pick the right destination.
1467 BasicBlock *TrueDest = BI->getSuccessor(0);
1468 BasicBlock *FalseDest = BI->getSuccessor(1);
1469 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition())) {
1470 BasicBlock::iterator CondIt = Cond;
1471 if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) &&
1472 Cond->getParent() == BB && &BB->front() == Cond &&
1473 &*++CondIt == BI && Cond->hasOneUse() &&
1474 TrueDest != BB && FalseDest != BB)
1475 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1476 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1477 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
1478 BasicBlock *PredBlock = *PI;
1479 if (PBI->getSuccessor(0) == FalseDest ||
1480 PBI->getSuccessor(1) == TrueDest) {
1481 // Invert the predecessors condition test (xor it with true),
1482 // which allows us to write this code once.
1484 BinaryOperator::createNot(PBI->getCondition(),
1485 PBI->getCondition()->getName()+".not", PBI);
1486 PBI->setCondition(NewCond);
1487 BasicBlock *OldTrue = PBI->getSuccessor(0);
1488 BasicBlock *OldFalse = PBI->getSuccessor(1);
1489 PBI->setSuccessor(0, OldFalse);
1490 PBI->setSuccessor(1, OldTrue);
1493 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1494 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
1495 // Clone Cond into the predecessor basic block, and or/and the
1496 // two conditions together.
1497 Instruction *New = Cond->clone();
1498 PredBlock->getInstList().insert(PBI, New);
1499 New->takeName(Cond);
1500 Cond->setName(New->getName()+".old");
1501 Instruction::BinaryOps Opcode =
1502 PBI->getSuccessor(0) == TrueDest ?
1503 Instruction::Or : Instruction::And;
1505 BinaryOperator::create(Opcode, PBI->getCondition(),
1506 New, "bothcond", PBI);
1507 PBI->setCondition(NewCond);
1508 if (PBI->getSuccessor(0) == BB) {
1509 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1510 PBI->setSuccessor(0, TrueDest);
1512 if (PBI->getSuccessor(1) == BB) {
1513 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1514 PBI->setSuccessor(1, FalseDest);
1516 return SimplifyCFG(BB) | 1;
1521 // Scan predessor blocks for conditional branches.
1522 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1523 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1524 if (PBI != BI && PBI->isConditional()) {
1526 // If this block ends with a branch instruction, and if there is a
1527 // predecessor that ends on a branch of the same condition, make
1528 // this conditional branch redundant.
1529 if (PBI->getCondition() == BI->getCondition() &&
1530 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1531 // Okay, the outcome of this conditional branch is statically
1532 // knowable. If this block had a single pred, handle specially.
1533 if (BB->getSinglePredecessor()) {
1534 // Turn this into a branch on constant.
1535 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1536 BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue));
1537 return SimplifyCFG(BB); // Nuke the branch on constant.
1540 // Otherwise, if there are multiple predecessors, insert a PHI
1541 // that merges in the constant and simplify the block result.
1542 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1543 PHINode *NewPN = new PHINode(Type::Int1Ty,
1544 BI->getCondition()->getName()+".pr",
1546 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1547 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1548 PBI != BI && PBI->isConditional() &&
1549 PBI->getCondition() == BI->getCondition() &&
1550 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1551 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1552 NewPN->addIncoming(ConstantInt::get(Type::Int1Ty,
1555 NewPN->addIncoming(BI->getCondition(), *PI);
1558 BI->setCondition(NewPN);
1559 // This will thread the branch.
1560 return SimplifyCFG(BB) | true;
1564 // If this is a conditional branch in an empty block, and if any
1565 // predecessors is a conditional branch to one of our destinations,
1566 // fold the conditions into logical ops and one cond br.
1567 if (&BB->front() == BI) {
1569 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1571 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1572 PBIOp = 0; BIOp = 1;
1573 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1574 PBIOp = 1; BIOp = 0;
1575 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1581 // Check to make sure that the other destination of this branch
1582 // isn't BB itself. If so, this is an infinite loop that will
1583 // keep getting unwound.
1584 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1587 // Do not perform this transformation if it would require
1588 // insertion of a large number of select instructions. For targets
1589 // without predication/cmovs, this is a big pessimization.
1591 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1593 unsigned NumPhis = 0;
1594 for (BasicBlock::iterator II = CommonDest->begin();
1595 isa<PHINode>(II); ++II, ++NumPhis) {
1597 // Disable this xform.
1604 // Finally, if everything is ok, fold the branches to logical ops.
1606 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1607 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1609 // If OtherDest *is* BB, then this is a basic block with just
1610 // a conditional branch in it, where one edge (OtherDesg) goes
1611 // back to the block. We know that the program doesn't get
1612 // stuck in the infinite loop, so the condition must be such
1613 // that OtherDest isn't branched through. Forward to CommonDest,
1614 // and avoid an infinite loop at optimizer time.
1615 if (OtherDest == BB)
1616 OtherDest = CommonDest;
1618 DOUT << "FOLDING BRs:" << *PBI->getParent()
1619 << "AND: " << *BI->getParent();
1621 // BI may have other predecessors. Because of this, we leave
1622 // it alone, but modify PBI.
1624 // Make sure we get to CommonDest on True&True directions.
1625 Value *PBICond = PBI->getCondition();
1627 PBICond = BinaryOperator::createNot(PBICond,
1628 PBICond->getName()+".not",
1630 Value *BICond = BI->getCondition();
1632 BICond = BinaryOperator::createNot(BICond,
1633 BICond->getName()+".not",
1635 // Merge the conditions.
1637 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1639 // Modify PBI to branch on the new condition to the new dests.
1640 PBI->setCondition(Cond);
1641 PBI->setSuccessor(0, CommonDest);
1642 PBI->setSuccessor(1, OtherDest);
1644 // OtherDest may have phi nodes. If so, add an entry from PBI's
1645 // block that are identical to the entries for BI's block.
1647 for (BasicBlock::iterator II = OtherDest->begin();
1648 (PN = dyn_cast<PHINode>(II)); ++II) {
1649 Value *V = PN->getIncomingValueForBlock(BB);
1650 PN->addIncoming(V, PBI->getParent());
1653 // We know that the CommonDest already had an edge from PBI to
1654 // it. If it has PHIs though, the PHIs may have different
1655 // entries for BB and PBI's BB. If so, insert a select to make
1657 for (BasicBlock::iterator II = CommonDest->begin();
1658 (PN = dyn_cast<PHINode>(II)); ++II) {
1659 Value * BIV = PN->getIncomingValueForBlock(BB);
1660 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1661 Value *PBIV = PN->getIncomingValue(PBBIdx);
1663 // Insert a select in PBI to pick the right value.
1664 Value *NV = new SelectInst(PBICond, PBIV, BIV,
1665 PBIV->getName()+".mux", PBI);
1666 PN->setIncomingValue(PBBIdx, NV);
1670 DOUT << "INTO: " << *PBI->getParent();
1672 // This basic block is probably dead. We know it has at least
1673 // one fewer predecessor.
1674 return SimplifyCFG(BB) | true;
1679 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1680 // If there are any instructions immediately before the unreachable that can
1681 // be removed, do so.
1682 Instruction *Unreachable = BB->getTerminator();
1683 while (Unreachable != BB->begin()) {
1684 BasicBlock::iterator BBI = Unreachable;
1686 if (isa<CallInst>(BBI)) break;
1687 // Delete this instruction
1688 BB->getInstList().erase(BBI);
1692 // If the unreachable instruction is the first in the block, take a gander
1693 // at all of the predecessors of this instruction, and simplify them.
1694 if (&BB->front() == Unreachable) {
1695 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
1696 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1697 TerminatorInst *TI = Preds[i]->getTerminator();
1699 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1700 if (BI->isUnconditional()) {
1701 if (BI->getSuccessor(0) == BB) {
1702 new UnreachableInst(TI);
1703 TI->eraseFromParent();
1707 if (BI->getSuccessor(0) == BB) {
1708 new BranchInst(BI->getSuccessor(1), BI);
1709 BI->eraseFromParent();
1710 } else if (BI->getSuccessor(1) == BB) {
1711 new BranchInst(BI->getSuccessor(0), BI);
1712 BI->eraseFromParent();
1716 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1717 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1718 if (SI->getSuccessor(i) == BB) {
1719 BB->removePredecessor(SI->getParent());
1724 // If the default value is unreachable, figure out the most popular
1725 // destination and make it the default.
1726 if (SI->getSuccessor(0) == BB) {
1727 std::map<BasicBlock*, unsigned> Popularity;
1728 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1729 Popularity[SI->getSuccessor(i)]++;
1731 // Find the most popular block.
1732 unsigned MaxPop = 0;
1733 BasicBlock *MaxBlock = 0;
1734 for (std::map<BasicBlock*, unsigned>::iterator
1735 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1736 if (I->second > MaxPop) {
1738 MaxBlock = I->first;
1742 // Make this the new default, allowing us to delete any explicit
1744 SI->setSuccessor(0, MaxBlock);
1747 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1749 if (isa<PHINode>(MaxBlock->begin()))
1750 for (unsigned i = 0; i != MaxPop-1; ++i)
1751 MaxBlock->removePredecessor(SI->getParent());
1753 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1754 if (SI->getSuccessor(i) == MaxBlock) {
1760 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1761 if (II->getUnwindDest() == BB) {
1762 // Convert the invoke to a call instruction. This would be a good
1763 // place to note that the call does not throw though.
1764 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1765 II->removeFromParent(); // Take out of symbol table
1767 // Insert the call now...
1768 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
1769 CallInst *CI = new CallInst(II->getCalledValue(),
1770 Args.begin(), Args.end(),
1772 CI->setCallingConv(II->getCallingConv());
1773 CI->setParamAttrs(II->getParamAttrs());
1774 // If the invoke produced a value, the Call does now instead.
1775 II->replaceAllUsesWith(CI);
1782 // If this block is now dead, remove it.
1783 if (pred_begin(BB) == pred_end(BB)) {
1784 // We know there are no successors, so just nuke the block.
1785 M->getBasicBlockList().erase(BB);
1791 // Merge basic blocks into their predecessor if there is only one distinct
1792 // pred, and if there is only one distinct successor of the predecessor, and
1793 // if there are no PHI nodes.
1795 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1796 BasicBlock *OnlyPred = *PI++;
1797 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1798 if (*PI != OnlyPred) {
1799 OnlyPred = 0; // There are multiple different predecessors...
1803 BasicBlock *OnlySucc = 0;
1804 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1805 OnlyPred->getUnwindDest() != BB &&
1806 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1807 // Check to see if there is only one distinct successor...
1808 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1810 for (; SI != SE; ++SI)
1811 if (*SI != OnlySucc) {
1812 OnlySucc = 0; // There are multiple distinct successors!
1817 if (OnlySucc && (BB->getUnwindDest() == OnlyPred->getUnwindDest() ||
1818 !BB->getUnwindDest() || !OnlyPred->getUnwindDest())) {
1819 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
1821 // Resolve any PHI nodes at the start of the block. They are all
1822 // guaranteed to have exactly one entry if they exist, unless there are
1823 // multiple duplicate (but guaranteed to be equal) entries for the
1824 // incoming edges. This occurs when there are multiple edges from
1825 // OnlyPred to OnlySucc.
1827 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1828 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1829 BB->getInstList().pop_front(); // Delete the phi node.
1832 // Delete the unconditional branch from the predecessor.
1833 OnlyPred->getInstList().pop_back();
1835 // Move all definitions in the successor to the predecessor.
1836 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1838 // Move the unwind destination block
1839 if (!OnlyPred->getUnwindDest() && BB->getUnwindDest())
1840 OnlyPred->setUnwindDest(BB->getUnwindDest());
1842 // Make all PHI nodes that referred to BB now refer to Pred as their
1844 BB->replaceAllUsesWith(OnlyPred);
1846 // Inherit predecessors name if it exists.
1847 if (!OnlyPred->hasName())
1848 OnlyPred->takeName(BB);
1850 // Erase basic block from the function.
1851 M->getBasicBlockList().erase(BB);
1856 // Otherwise, if this block only has a single predecessor, and if that block
1857 // is a conditional branch, see if we can hoist any code from this block up
1858 // into our predecessor.
1860 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1861 if (BI->isConditional()) {
1862 // Get the other block.
1863 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1864 PI = pred_begin(OtherBB);
1866 if (PI == pred_end(OtherBB)) {
1867 // We have a conditional branch to two blocks that are only reachable
1868 // from the condbr. We know that the condbr dominates the two blocks,
1869 // so see if there is any identical code in the "then" and "else"
1870 // blocks. If so, we can hoist it up to the branching block.
1871 Changed |= HoistThenElseCodeToIf(BI);
1875 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1876 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1877 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1878 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1879 Instruction *Cond = cast<Instruction>(BI->getCondition());
1880 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1881 // 'setne's and'ed together, collect them.
1883 std::vector<ConstantInt*> Values;
1884 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1885 if (CompVal && CompVal->getType()->isInteger()) {
1886 // There might be duplicate constants in the list, which the switch
1887 // instruction can't handle, remove them now.
1888 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1889 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1891 // Figure out which block is which destination.
1892 BasicBlock *DefaultBB = BI->getSuccessor(1);
1893 BasicBlock *EdgeBB = BI->getSuccessor(0);
1894 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1896 // Create the new switch instruction now.
1897 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
1899 // Add all of the 'cases' to the switch instruction.
1900 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1901 New->addCase(Values[i], EdgeBB);
1903 // We added edges from PI to the EdgeBB. As such, if there were any
1904 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1905 // the number of edges added.
1906 for (BasicBlock::iterator BBI = EdgeBB->begin();
1907 isa<PHINode>(BBI); ++BBI) {
1908 PHINode *PN = cast<PHINode>(BBI);
1909 Value *InVal = PN->getIncomingValueForBlock(*PI);
1910 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1911 PN->addIncoming(InVal, *PI);
1914 // Erase the old branch instruction.
1915 (*PI)->getInstList().erase(BI);
1917 // Erase the potentially condition tree that was used to computed the
1918 // branch condition.
1919 ErasePossiblyDeadInstructionTree(Cond);