1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
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/Support/CFG.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 /// SafeToMergeTerminators - Return true if it is safe to merge these two
29 /// terminator instructions together.
31 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
32 if (SI1 == SI2) return false; // Can't merge with self!
34 // It is not safe to merge these two switch instructions if they have a common
35 // successor, and if that successor has a PHI node, and if *that* PHI node has
36 // conflicting incoming values from the two switch blocks.
37 BasicBlock *SI1BB = SI1->getParent();
38 BasicBlock *SI2BB = SI2->getParent();
39 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
41 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
42 if (SI1Succs.count(*I))
43 for (BasicBlock::iterator BBI = (*I)->begin();
44 isa<PHINode>(BBI); ++BBI) {
45 PHINode *PN = cast<PHINode>(BBI);
46 if (PN->getIncomingValueForBlock(SI1BB) !=
47 PN->getIncomingValueForBlock(SI2BB))
54 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
55 /// now be entries in it from the 'NewPred' block. The values that will be
56 /// flowing into the PHI nodes will be the same as those coming in from
57 /// ExistPred, an existing predecessor of Succ.
58 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
59 BasicBlock *ExistPred) {
60 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
61 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
62 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
64 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
65 PHINode *PN = cast<PHINode>(I);
66 Value *V = PN->getIncomingValueForBlock(ExistPred);
67 PN->addIncoming(V, NewPred);
71 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
72 // almost-empty BB ending in an unconditional branch to Succ, into succ.
74 // Assumption: Succ is the single successor for BB.
76 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
77 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
79 // Check to see if one of the predecessors of BB is already a predecessor of
80 // Succ. If so, we cannot do the transformation if there are any PHI nodes
81 // with incompatible values coming in from the two edges!
83 if (isa<PHINode>(Succ->front())) {
84 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
85 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
87 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
88 // Loop over all of the PHI nodes checking to see if there are
89 // incompatible values coming in.
90 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
91 PHINode *PN = cast<PHINode>(I);
92 // Loop up the entries in the PHI node for BB and for *PI if the
93 // values coming in are non-equal, we cannot merge these two blocks
94 // (instead we should insert a conditional move or something, then
96 if (PN->getIncomingValueForBlock(BB) !=
97 PN->getIncomingValueForBlock(*PI))
98 return false; // Values are not equal...
103 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
104 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
105 // fold these blocks, as we don't know whether BB dominates Succ or not to
106 // update the PHI nodes correctly.
107 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
109 // If the predecessors of Succ are only BB and Succ itself, we can handle this.
111 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
112 if (*PI != Succ && *PI != BB) {
116 if (IsSafe) return true;
118 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
119 // BB and Succ have no common predecessors.
120 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
121 PHINode *PN = cast<PHINode>(I);
122 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
124 if (cast<Instruction>(*UI)->getParent() != Succ)
128 // Scan the predecessor sets of BB and Succ, making sure there are no common
129 // predecessors. Common predecessors would cause us to build a phi node with
130 // differing incoming values, which is not legal.
131 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
132 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
133 if (BBPreds.count(*PI))
139 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
140 /// branch to Succ, and contains no instructions other than PHI nodes and the
141 /// branch. If possible, eliminate BB.
142 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
144 // If our successor has PHI nodes, then we need to update them to include
145 // entries for BB's predecessors, not for BB itself. Be careful though,
146 // if this transformation fails (returns true) then we cannot do this
149 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
151 DOUT << "Killing Trivial BB: \n" << *BB;
153 if (isa<PHINode>(Succ->begin())) {
154 // If there is more than one pred of succ, and there are PHI nodes in
155 // the successor, then we need to add incoming edges for the PHI nodes
157 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
159 // Loop over all of the PHI nodes in the successor of BB.
160 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
161 PHINode *PN = cast<PHINode>(I);
162 Value *OldVal = PN->removeIncomingValue(BB, false);
163 assert(OldVal && "No entry in PHI for Pred BB!");
165 // If this incoming value is one of the PHI nodes in BB, the new entries
166 // in the PHI node are the entries from the old PHI.
167 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
168 PHINode *OldValPN = cast<PHINode>(OldVal);
169 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
170 PN->addIncoming(OldValPN->getIncomingValue(i),
171 OldValPN->getIncomingBlock(i));
173 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
174 End = BBPreds.end(); PredI != End; ++PredI) {
175 // Add an incoming value for each of the new incoming values...
176 PN->addIncoming(OldVal, *PredI);
182 if (isa<PHINode>(&BB->front())) {
183 std::vector<BasicBlock*>
184 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
186 // Move all PHI nodes in BB to Succ if they are alive, otherwise
188 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
189 if (PN->use_empty()) {
190 // Just remove the dead phi. This happens if Succ's PHIs were the only
191 // users of the PHI nodes.
192 PN->eraseFromParent();
194 // The instruction is alive, so this means that Succ must have
195 // *ONLY* had BB as a predecessor, and the PHI node is still valid
196 // now. Simply move it into Succ, because we know that BB
197 // strictly dominated Succ.
198 Succ->getInstList().splice(Succ->begin(),
199 BB->getInstList(), BB->begin());
201 // We need to add new entries for the PHI node to account for
202 // predecessors of Succ that the PHI node does not take into
203 // account. At this point, since we know that BB dominated succ,
204 // this means that we should any newly added incoming edges should
205 // use the PHI node as the value for these edges, because they are
207 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
208 if (OldSuccPreds[i] != BB)
209 PN->addIncoming(PN, OldSuccPreds[i]);
213 // Everything that jumped to BB now goes to Succ.
214 std::string OldName = BB->getName();
215 BB->replaceAllUsesWith(Succ);
216 BB->eraseFromParent(); // Delete the old basic block.
218 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
219 Succ->setName(OldName);
223 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
224 /// presumably PHI nodes in it), check to see if the merge at this block is due
225 /// to an "if condition". If so, return the boolean condition that determines
226 /// which entry into BB will be taken. Also, return by references the block
227 /// that will be entered from if the condition is true, and the block that will
228 /// be entered if the condition is false.
231 static Value *GetIfCondition(BasicBlock *BB,
232 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
233 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
234 "Function can only handle blocks with 2 predecessors!");
235 BasicBlock *Pred1 = *pred_begin(BB);
236 BasicBlock *Pred2 = *++pred_begin(BB);
238 // We can only handle branches. Other control flow will be lowered to
239 // branches if possible anyway.
240 if (!isa<BranchInst>(Pred1->getTerminator()) ||
241 !isa<BranchInst>(Pred2->getTerminator()))
243 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
244 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
246 // Eliminate code duplication by ensuring that Pred1Br is conditional if
248 if (Pred2Br->isConditional()) {
249 // If both branches are conditional, we don't have an "if statement". In
250 // reality, we could transform this case, but since the condition will be
251 // required anyway, we stand no chance of eliminating it, so the xform is
252 // probably not profitable.
253 if (Pred1Br->isConditional())
256 std::swap(Pred1, Pred2);
257 std::swap(Pred1Br, Pred2Br);
260 if (Pred1Br->isConditional()) {
261 // If we found a conditional branch predecessor, make sure that it branches
262 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
263 if (Pred1Br->getSuccessor(0) == BB &&
264 Pred1Br->getSuccessor(1) == Pred2) {
267 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
268 Pred1Br->getSuccessor(1) == BB) {
272 // We know that one arm of the conditional goes to BB, so the other must
273 // go somewhere unrelated, and this must not be an "if statement".
277 // The only thing we have to watch out for here is to make sure that Pred2
278 // doesn't have incoming edges from other blocks. If it does, the condition
279 // doesn't dominate BB.
280 if (++pred_begin(Pred2) != pred_end(Pred2))
283 return Pred1Br->getCondition();
286 // Ok, if we got here, both predecessors end with an unconditional branch to
287 // BB. Don't panic! If both blocks only have a single (identical)
288 // predecessor, and THAT is a conditional branch, then we're all ok!
289 if (pred_begin(Pred1) == pred_end(Pred1) ||
290 ++pred_begin(Pred1) != pred_end(Pred1) ||
291 pred_begin(Pred2) == pred_end(Pred2) ||
292 ++pred_begin(Pred2) != pred_end(Pred2) ||
293 *pred_begin(Pred1) != *pred_begin(Pred2))
296 // Otherwise, if this is a conditional branch, then we can use it!
297 BasicBlock *CommonPred = *pred_begin(Pred1);
298 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
299 assert(BI->isConditional() && "Two successors but not conditional?");
300 if (BI->getSuccessor(0) == Pred1) {
307 return BI->getCondition();
313 // If we have a merge point of an "if condition" as accepted above, return true
314 // if the specified value dominates the block. We don't handle the true
315 // generality of domination here, just a special case which works well enough
318 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
319 // see if V (which must be an instruction) is cheap to compute and is
320 // non-trapping. If both are true, the instruction is inserted into the set and
322 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
323 std::set<Instruction*> *AggressiveInsts) {
324 Instruction *I = dyn_cast<Instruction>(V);
326 // Non-instructions all dominate instructions, but not all constantexprs
327 // can be executed unconditionally.
328 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
333 BasicBlock *PBB = I->getParent();
335 // We don't want to allow weird loops that might have the "if condition" in
336 // the bottom of this block.
337 if (PBB == BB) return false;
339 // If this instruction is defined in a block that contains an unconditional
340 // branch to BB, then it must be in the 'conditional' part of the "if
342 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
343 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
344 if (!AggressiveInsts) return false;
345 // Okay, it looks like the instruction IS in the "condition". Check to
346 // see if its a cheap instruction to unconditionally compute, and if it
347 // only uses stuff defined outside of the condition. If so, hoist it out.
348 switch (I->getOpcode()) {
349 default: return false; // Cannot hoist this out safely.
350 case Instruction::Load:
351 // We can hoist loads that are non-volatile and obviously cannot trap.
352 if (cast<LoadInst>(I)->isVolatile())
354 if (!isa<AllocaInst>(I->getOperand(0)) &&
355 !isa<Constant>(I->getOperand(0)))
358 // Finally, we have to check to make sure there are no instructions
359 // before the load in its basic block, as we are going to hoist the loop
360 // out to its predecessor.
361 if (PBB->begin() != BasicBlock::iterator(I))
364 case Instruction::Add:
365 case Instruction::Sub:
366 case Instruction::And:
367 case Instruction::Or:
368 case Instruction::Xor:
369 case Instruction::Shl:
370 case Instruction::LShr:
371 case Instruction::AShr:
372 case Instruction::ICmp:
373 case Instruction::FCmp:
374 break; // These are all cheap and non-trapping instructions.
377 // Okay, we can only really hoist these out if their operands are not
378 // defined in the conditional region.
379 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
380 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
382 // Okay, it's safe to do this! Remember this instruction.
383 AggressiveInsts->insert(I);
389 // GatherConstantSetEQs - Given a potentially 'or'd together collection of
390 // icmp_eq instructions that compare a value against a constant, return the
391 // value being compared, and stick the constant into the Values vector.
392 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
393 if (Instruction *Inst = dyn_cast<Instruction>(V))
394 if (Inst->getOpcode() == Instruction::ICmp &&
395 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
396 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
398 return Inst->getOperand(0);
399 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
401 return Inst->getOperand(1);
403 } else if (Inst->getOpcode() == Instruction::Or) {
404 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
405 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
412 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
413 // setne instructions that compare a value against a constant, return the value
414 // being compared, and stick the constant into the Values vector.
415 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
416 if (Instruction *Inst = dyn_cast<Instruction>(V))
417 if (Inst->getOpcode() == Instruction::ICmp &&
418 cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
419 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
421 return Inst->getOperand(0);
422 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
424 return Inst->getOperand(1);
426 } else if (Inst->getOpcode() == Instruction::And) {
427 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
428 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
437 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
438 /// bunch of comparisons of one value against constants, return the value and
439 /// the constants being compared.
440 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
441 std::vector<ConstantInt*> &Values) {
442 if (Cond->getOpcode() == Instruction::Or) {
443 CompVal = GatherConstantSetEQs(Cond, Values);
445 // Return true to indicate that the condition is true if the CompVal is
446 // equal to one of the constants.
448 } else if (Cond->getOpcode() == Instruction::And) {
449 CompVal = GatherConstantSetNEs(Cond, Values);
451 // Return false to indicate that the condition is false if the CompVal is
452 // equal to one of the constants.
458 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
459 /// has no side effects, nuke it. If it uses any instructions that become dead
460 /// because the instruction is now gone, nuke them too.
461 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
462 if (!isInstructionTriviallyDead(I)) return;
464 std::vector<Instruction*> InstrsToInspect;
465 InstrsToInspect.push_back(I);
467 while (!InstrsToInspect.empty()) {
468 I = InstrsToInspect.back();
469 InstrsToInspect.pop_back();
471 if (!isInstructionTriviallyDead(I)) continue;
473 // If I is in the work list multiple times, remove previous instances.
474 for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
475 if (InstrsToInspect[i] == I) {
476 InstrsToInspect.erase(InstrsToInspect.begin()+i);
480 // Add operands of dead instruction to worklist.
481 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
482 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
483 InstrsToInspect.push_back(OpI);
485 // Remove dead instruction.
486 I->eraseFromParent();
490 // isValueEqualityComparison - Return true if the specified terminator checks to
491 // see if a value is equal to constant integer value.
492 static Value *isValueEqualityComparison(TerminatorInst *TI) {
493 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
494 // Do not permit merging of large switch instructions into their
495 // predecessors unless there is only one predecessor.
496 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
497 pred_end(SI->getParent())) > 128)
500 return SI->getCondition();
502 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
503 if (BI->isConditional() && BI->getCondition()->hasOneUse())
504 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
505 if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
506 ICI->getPredicate() == ICmpInst::ICMP_NE) &&
507 isa<ConstantInt>(ICI->getOperand(1)))
508 return ICI->getOperand(0);
512 // Given a value comparison instruction, decode all of the 'cases' that it
513 // represents and return the 'default' block.
515 GetValueEqualityComparisonCases(TerminatorInst *TI,
516 std::vector<std::pair<ConstantInt*,
517 BasicBlock*> > &Cases) {
518 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
519 Cases.reserve(SI->getNumCases());
520 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
521 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
522 return SI->getDefaultDest();
525 BranchInst *BI = cast<BranchInst>(TI);
526 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
527 Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
528 BI->getSuccessor(ICI->getPredicate() ==
529 ICmpInst::ICMP_NE)));
530 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
534 // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
535 // in the list that match the specified block.
536 static void EliminateBlockCases(BasicBlock *BB,
537 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
538 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
539 if (Cases[i].second == BB) {
540 Cases.erase(Cases.begin()+i);
545 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
548 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
549 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
550 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
552 // Make V1 be smaller than V2.
553 if (V1->size() > V2->size())
556 if (V1->size() == 0) return false;
557 if (V1->size() == 1) {
559 ConstantInt *TheVal = (*V1)[0].first;
560 for (unsigned i = 0, e = V2->size(); i != e; ++i)
561 if (TheVal == (*V2)[i].first)
565 // Otherwise, just sort both lists and compare element by element.
566 std::sort(V1->begin(), V1->end());
567 std::sort(V2->begin(), V2->end());
568 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
569 while (i1 != e1 && i2 != e2) {
570 if ((*V1)[i1].first == (*V2)[i2].first)
572 if ((*V1)[i1].first < (*V2)[i2].first)
580 // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
581 // terminator instruction and its block is known to only have a single
582 // predecessor block, check to see if that predecessor is also a value
583 // comparison with the same value, and if that comparison determines the outcome
584 // of this comparison. If so, simplify TI. This does a very limited form of
586 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
588 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
589 if (!PredVal) return false; // Not a value comparison in predecessor.
591 Value *ThisVal = isValueEqualityComparison(TI);
592 assert(ThisVal && "This isn't a value comparison!!");
593 if (ThisVal != PredVal) return false; // Different predicates.
595 // Find out information about when control will move from Pred to TI's block.
596 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
597 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
599 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
601 // Find information about how control leaves this block.
602 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
603 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
604 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
606 // If TI's block is the default block from Pred's comparison, potentially
607 // simplify TI based on this knowledge.
608 if (PredDef == TI->getParent()) {
609 // If we are here, we know that the value is none of those cases listed in
610 // PredCases. If there are any cases in ThisCases that are in PredCases, we
612 if (ValuesOverlap(PredCases, ThisCases)) {
613 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
614 // Okay, one of the successors of this condbr is dead. Convert it to a
616 assert(ThisCases.size() == 1 && "Branch can only have one case!");
617 Value *Cond = BTI->getCondition();
618 // Insert the new branch.
619 Instruction *NI = new BranchInst(ThisDef, TI);
621 // Remove PHI node entries for the dead edge.
622 ThisCases[0].second->removePredecessor(TI->getParent());
624 DOUT << "Threading pred instr: " << *Pred->getTerminator()
625 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
627 TI->eraseFromParent(); // Nuke the old one.
628 // If condition is now dead, nuke it.
629 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
630 ErasePossiblyDeadInstructionTree(CondI);
634 SwitchInst *SI = cast<SwitchInst>(TI);
635 // Okay, TI has cases that are statically dead, prune them away.
636 std::set<Constant*> DeadCases;
637 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
638 DeadCases.insert(PredCases[i].first);
640 DOUT << "Threading pred instr: " << *Pred->getTerminator()
641 << "Through successor TI: " << *TI;
643 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
644 if (DeadCases.count(SI->getCaseValue(i))) {
645 SI->getSuccessor(i)->removePredecessor(TI->getParent());
649 DOUT << "Leaving: " << *TI << "\n";
655 // Otherwise, TI's block must correspond to some matched value. Find out
656 // which value (or set of values) this is.
657 ConstantInt *TIV = 0;
658 BasicBlock *TIBB = TI->getParent();
659 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
660 if (PredCases[i].second == TIBB)
662 TIV = PredCases[i].first;
664 return false; // Cannot handle multiple values coming to this block.
665 assert(TIV && "No edge from pred to succ?");
667 // Okay, we found the one constant that our value can be if we get into TI's
668 // BB. Find out which successor will unconditionally be branched to.
669 BasicBlock *TheRealDest = 0;
670 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
671 if (ThisCases[i].first == TIV) {
672 TheRealDest = ThisCases[i].second;
676 // If not handled by any explicit cases, it is handled by the default case.
677 if (TheRealDest == 0) TheRealDest = ThisDef;
679 // Remove PHI node entries for dead edges.
680 BasicBlock *CheckEdge = TheRealDest;
681 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
682 if (*SI != CheckEdge)
683 (*SI)->removePredecessor(TIBB);
687 // Insert the new branch.
688 Instruction *NI = new BranchInst(TheRealDest, TI);
690 DOUT << "Threading pred instr: " << *Pred->getTerminator()
691 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
692 Instruction *Cond = 0;
693 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
694 Cond = dyn_cast<Instruction>(BI->getCondition());
695 TI->eraseFromParent(); // Nuke the old one.
697 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
703 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
704 // equality comparison instruction (either a switch or a branch on "X == c").
705 // See if any of the predecessors of the terminator block are value comparisons
706 // on the same value. If so, and if safe to do so, fold them together.
707 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
708 BasicBlock *BB = TI->getParent();
709 Value *CV = isValueEqualityComparison(TI); // CondVal
710 assert(CV && "Not a comparison?");
711 bool Changed = false;
713 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
714 while (!Preds.empty()) {
715 BasicBlock *Pred = Preds.back();
718 // See if the predecessor is a comparison with the same value.
719 TerminatorInst *PTI = Pred->getTerminator();
720 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
722 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
723 // Figure out which 'cases' to copy from SI to PSI.
724 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
725 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
727 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
728 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
730 // Based on whether the default edge from PTI goes to BB or not, fill in
731 // PredCases and PredDefault with the new switch cases we would like to
733 std::vector<BasicBlock*> NewSuccessors;
735 if (PredDefault == BB) {
736 // If this is the default destination from PTI, only the edges in TI
737 // that don't occur in PTI, or that branch to BB will be activated.
738 std::set<ConstantInt*> PTIHandled;
739 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
740 if (PredCases[i].second != BB)
741 PTIHandled.insert(PredCases[i].first);
743 // The default destination is BB, we don't need explicit targets.
744 std::swap(PredCases[i], PredCases.back());
745 PredCases.pop_back();
749 // Reconstruct the new switch statement we will be building.
750 if (PredDefault != BBDefault) {
751 PredDefault->removePredecessor(Pred);
752 PredDefault = BBDefault;
753 NewSuccessors.push_back(BBDefault);
755 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
756 if (!PTIHandled.count(BBCases[i].first) &&
757 BBCases[i].second != BBDefault) {
758 PredCases.push_back(BBCases[i]);
759 NewSuccessors.push_back(BBCases[i].second);
763 // If this is not the default destination from PSI, only the edges
764 // in SI that occur in PSI with a destination of BB will be
766 std::set<ConstantInt*> PTIHandled;
767 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
768 if (PredCases[i].second == BB) {
769 PTIHandled.insert(PredCases[i].first);
770 std::swap(PredCases[i], PredCases.back());
771 PredCases.pop_back();
775 // Okay, now we know which constants were sent to BB from the
776 // predecessor. Figure out where they will all go now.
777 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
778 if (PTIHandled.count(BBCases[i].first)) {
779 // If this is one we are capable of getting...
780 PredCases.push_back(BBCases[i]);
781 NewSuccessors.push_back(BBCases[i].second);
782 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
785 // If there are any constants vectored to BB that TI doesn't handle,
786 // they must go to the default destination of TI.
787 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
788 E = PTIHandled.end(); I != E; ++I) {
789 PredCases.push_back(std::make_pair(*I, BBDefault));
790 NewSuccessors.push_back(BBDefault);
794 // Okay, at this point, we know which new successor Pred will get. Make
795 // sure we update the number of entries in the PHI nodes for these
797 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
798 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
800 // Now that the successors are updated, create the new Switch instruction.
801 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
802 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
803 NewSI->addCase(PredCases[i].first, PredCases[i].second);
805 Instruction *DeadCond = 0;
806 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
807 // If PTI is a branch, remember the condition.
808 DeadCond = dyn_cast<Instruction>(BI->getCondition());
809 Pred->getInstList().erase(PTI);
811 // If the condition is dead now, remove the instruction tree.
812 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
814 // Okay, last check. If BB is still a successor of PSI, then we must
815 // have an infinite loop case. If so, add an infinitely looping block
816 // to handle the case to preserve the behavior of the code.
817 BasicBlock *InfLoopBlock = 0;
818 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
819 if (NewSI->getSuccessor(i) == BB) {
820 if (InfLoopBlock == 0) {
821 // Insert it at the end of the loop, because it's either code,
822 // or it won't matter if it's hot. :)
823 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
824 new BranchInst(InfLoopBlock, InfLoopBlock);
826 NewSI->setSuccessor(i, InfLoopBlock);
835 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
836 /// BB2, hoist any common code in the two blocks up into the branch block. The
837 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
838 static bool HoistThenElseCodeToIf(BranchInst *BI) {
839 // This does very trivial matching, with limited scanning, to find identical
840 // instructions in the two blocks. In particular, we don't want to get into
841 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
842 // such, we currently just scan for obviously identical instructions in an
844 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
845 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
847 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
848 if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) ||
849 isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
852 // If we get here, we can hoist at least one instruction.
853 BasicBlock *BIParent = BI->getParent();
856 // If we are hoisting the terminator instruction, don't move one (making a
857 // broken BB), instead clone it, and remove BI.
858 if (isa<TerminatorInst>(I1))
859 goto HoistTerminator;
861 // For a normal instruction, we just move one to right before the branch,
862 // then replace all uses of the other with the first. Finally, we remove
863 // the now redundant second instruction.
864 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
865 if (!I2->use_empty())
866 I2->replaceAllUsesWith(I1);
867 BB2->getInstList().erase(I2);
871 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
876 // Okay, it is safe to hoist the terminator.
877 Instruction *NT = I1->clone();
878 BIParent->getInstList().insert(BI, NT);
879 if (NT->getType() != Type::VoidTy) {
880 I1->replaceAllUsesWith(NT);
881 I2->replaceAllUsesWith(NT);
882 NT->setName(I1->getName());
885 // Hoisting one of the terminators from our successor is a great thing.
886 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
887 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
888 // nodes, so we insert select instruction to compute the final result.
889 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
890 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
892 for (BasicBlock::iterator BBI = SI->begin();
893 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
894 Value *BB1V = PN->getIncomingValueForBlock(BB1);
895 Value *BB2V = PN->getIncomingValueForBlock(BB2);
897 // These values do not agree. Insert a select instruction before NT
898 // that determines the right value.
899 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
901 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
902 BB1V->getName()+"."+BB2V->getName(), NT);
903 // Make the PHI node use the select for all incoming values for BB1/BB2
904 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
905 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
906 PN->setIncomingValue(i, SI);
911 // Update any PHI nodes in our new successors.
912 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
913 AddPredecessorToBlock(*SI, BIParent, BB1);
915 BI->eraseFromParent();
919 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
920 /// across this block.
921 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
922 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
925 // If this basic block contains anything other than a PHI (which controls the
926 // branch) and branch itself, bail out. FIXME: improve this in the future.
927 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
928 if (Size > 10) return false; // Don't clone large BB's.
930 // We can only support instructions that are do not define values that are
931 // live outside of the current basic block.
932 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
934 Instruction *U = cast<Instruction>(*UI);
935 if (U->getParent() != BB || isa<PHINode>(U)) return false;
938 // Looks ok, continue checking.
944 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
945 /// that is defined in the same block as the branch and if any PHI entries are
946 /// constants, thread edges corresponding to that entry to be branches to their
947 /// ultimate destination.
948 static bool FoldCondBranchOnPHI(BranchInst *BI) {
949 BasicBlock *BB = BI->getParent();
950 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
951 // NOTE: we currently cannot transform this case if the PHI node is used
952 // outside of the block.
953 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
956 // Degenerate case of a single entry PHI.
957 if (PN->getNumIncomingValues() == 1) {
958 if (PN->getIncomingValue(0) != PN)
959 PN->replaceAllUsesWith(PN->getIncomingValue(0));
961 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
962 PN->eraseFromParent();
966 // Now we know that this block has multiple preds and two succs.
967 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
969 // Okay, this is a simple enough basic block. See if any phi values are
971 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
972 if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) {
973 // Okay, we now know that all edges from PredBB should be revectored to
974 // branch to RealDest.
975 BasicBlock *PredBB = PN->getIncomingBlock(i);
976 BasicBlock *RealDest = BI->getSuccessor(!CB->getValue());
978 if (RealDest == BB) continue; // Skip self loops.
980 // The dest block might have PHI nodes, other predecessors and other
981 // difficult cases. Instead of being smart about this, just insert a new
982 // block that jumps to the destination block, effectively splitting
983 // the edge we are about to create.
984 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
985 RealDest->getParent(), RealDest);
986 new BranchInst(RealDest, EdgeBB);
988 for (BasicBlock::iterator BBI = RealDest->begin();
989 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
990 Value *V = PN->getIncomingValueForBlock(BB);
991 PN->addIncoming(V, EdgeBB);
994 // BB may have instructions that are being threaded over. Clone these
995 // instructions into EdgeBB. We know that there will be no uses of the
996 // cloned instructions outside of EdgeBB.
997 BasicBlock::iterator InsertPt = EdgeBB->begin();
998 std::map<Value*, Value*> TranslateMap; // Track translated values.
999 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1000 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1001 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1003 // Clone the instruction.
1004 Instruction *N = BBI->clone();
1005 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1007 // Update operands due to translation.
1008 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1009 std::map<Value*, Value*>::iterator PI =
1010 TranslateMap.find(N->getOperand(i));
1011 if (PI != TranslateMap.end())
1012 N->setOperand(i, PI->second);
1015 // Check for trivial simplification.
1016 if (Constant *C = ConstantFoldInstruction(N)) {
1017 TranslateMap[BBI] = C;
1018 delete N; // Constant folded away, don't need actual inst
1020 // Insert the new instruction into its new home.
1021 EdgeBB->getInstList().insert(InsertPt, N);
1022 if (!BBI->use_empty())
1023 TranslateMap[BBI] = N;
1028 // Loop over all of the edges from PredBB to BB, changing them to branch
1029 // to EdgeBB instead.
1030 TerminatorInst *PredBBTI = PredBB->getTerminator();
1031 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1032 if (PredBBTI->getSuccessor(i) == BB) {
1033 BB->removePredecessor(PredBB);
1034 PredBBTI->setSuccessor(i, EdgeBB);
1037 // Recurse, simplifying any other constants.
1038 return FoldCondBranchOnPHI(BI) | true;
1044 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1045 /// PHI node, see if we can eliminate it.
1046 static bool FoldTwoEntryPHINode(PHINode *PN) {
1047 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1048 // statement", which has a very simple dominance structure. Basically, we
1049 // are trying to find the condition that is being branched on, which
1050 // subsequently causes this merge to happen. We really want control
1051 // dependence information for this check, but simplifycfg can't keep it up
1052 // to date, and this catches most of the cases we care about anyway.
1054 BasicBlock *BB = PN->getParent();
1055 BasicBlock *IfTrue, *IfFalse;
1056 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
1057 if (!IfCond) return false;
1059 // Okay, we found that we can merge this two-entry phi node into a select.
1060 // Doing so would require us to fold *all* two entry phi nodes in this block.
1061 // At some point this becomes non-profitable (particularly if the target
1062 // doesn't support cmov's). Only do this transformation if there are two or
1063 // fewer PHI nodes in this block.
1064 unsigned NumPhis = 0;
1065 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1069 DOUT << "FOUND IF CONDITION! " << *IfCond << " T: "
1070 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n";
1072 // Loop over the PHI's seeing if we can promote them all to select
1073 // instructions. While we are at it, keep track of the instructions
1074 // that need to be moved to the dominating block.
1075 std::set<Instruction*> AggressiveInsts;
1077 BasicBlock::iterator AfterPHIIt = BB->begin();
1078 while (isa<PHINode>(AfterPHIIt)) {
1079 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1080 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1081 if (PN->getIncomingValue(0) != PN)
1082 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1084 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1085 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1086 &AggressiveInsts) ||
1087 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1088 &AggressiveInsts)) {
1093 // If we all PHI nodes are promotable, check to make sure that all
1094 // instructions in the predecessor blocks can be promoted as well. If
1095 // not, we won't be able to get rid of the control flow, so it's not
1096 // worth promoting to select instructions.
1097 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1098 PN = cast<PHINode>(BB->begin());
1099 BasicBlock *Pred = PN->getIncomingBlock(0);
1100 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1102 DomBlock = *pred_begin(Pred);
1103 for (BasicBlock::iterator I = Pred->begin();
1104 !isa<TerminatorInst>(I); ++I)
1105 if (!AggressiveInsts.count(I)) {
1106 // This is not an aggressive instruction that we can promote.
1107 // Because of this, we won't be able to get rid of the control
1108 // flow, so the xform is not worth it.
1113 Pred = PN->getIncomingBlock(1);
1114 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1116 DomBlock = *pred_begin(Pred);
1117 for (BasicBlock::iterator I = Pred->begin();
1118 !isa<TerminatorInst>(I); ++I)
1119 if (!AggressiveInsts.count(I)) {
1120 // This is not an aggressive instruction that we can promote.
1121 // Because of this, we won't be able to get rid of the control
1122 // flow, so the xform is not worth it.
1127 // If we can still promote the PHI nodes after this gauntlet of tests,
1128 // do all of the PHI's now.
1130 // Move all 'aggressive' instructions, which are defined in the
1131 // conditional parts of the if's up to the dominating block.
1133 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1134 IfBlock1->getInstList(),
1136 IfBlock1->getTerminator());
1139 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1140 IfBlock2->getInstList(),
1142 IfBlock2->getTerminator());
1145 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1146 // Change the PHI node into a select instruction.
1148 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1150 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1152 std::string Name = PN->getName(); PN->setName("");
1153 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1155 BB->getInstList().erase(PN);
1161 /// ConstantIntOrdering - This class implements a stable ordering of constant
1162 /// integers that does not depend on their address. This is important for
1163 /// applications that sort ConstantInt's to ensure uniqueness.
1164 struct ConstantIntOrdering {
1165 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1166 return LHS->getZExtValue() < RHS->getZExtValue();
1171 // SimplifyCFG - This function is used to do simplification of a CFG. For
1172 // example, it adjusts branches to branches to eliminate the extra hop, it
1173 // eliminates unreachable basic blocks, and does other "peephole" optimization
1174 // of the CFG. It returns true if a modification was made.
1176 // WARNING: The entry node of a function may not be simplified.
1178 bool llvm::SimplifyCFG(BasicBlock *BB) {
1179 bool Changed = false;
1180 Function *M = BB->getParent();
1182 assert(BB && BB->getParent() && "Block not embedded in function!");
1183 assert(BB->getTerminator() && "Degenerate basic block encountered!");
1184 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
1186 // Remove basic blocks that have no predecessors... which are unreachable.
1187 if (pred_begin(BB) == pred_end(BB) ||
1188 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
1189 DOUT << "Removing BB: \n" << *BB;
1191 // Loop through all of our successors and make sure they know that one
1192 // of their predecessors is going away.
1193 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1194 SI->removePredecessor(BB);
1196 while (!BB->empty()) {
1197 Instruction &I = BB->back();
1198 // If this instruction is used, replace uses with an arbitrary
1199 // value. Because control flow can't get here, we don't care
1200 // what we replace the value with. Note that since this block is
1201 // unreachable, and all values contained within it must dominate their
1202 // uses, that all uses will eventually be removed.
1204 // Make all users of this instruction use undef instead
1205 I.replaceAllUsesWith(UndefValue::get(I.getType()));
1207 // Remove the instruction from the basic block
1208 BB->getInstList().pop_back();
1210 M->getBasicBlockList().erase(BB);
1214 // Check to see if we can constant propagate this terminator instruction
1216 Changed |= ConstantFoldTerminator(BB);
1218 // If this is a returning block with only PHI nodes in it, fold the return
1219 // instruction into any unconditional branch predecessors.
1221 // If any predecessor is a conditional branch that just selects among
1222 // different return values, fold the replace the branch/return with a select
1224 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1225 BasicBlock::iterator BBI = BB->getTerminator();
1226 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
1227 // Find predecessors that end with branches.
1228 std::vector<BasicBlock*> UncondBranchPreds;
1229 std::vector<BranchInst*> CondBranchPreds;
1230 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1231 TerminatorInst *PTI = (*PI)->getTerminator();
1232 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1233 if (BI->isUnconditional())
1234 UncondBranchPreds.push_back(*PI);
1236 CondBranchPreds.push_back(BI);
1239 // If we found some, do the transformation!
1240 if (!UncondBranchPreds.empty()) {
1241 while (!UncondBranchPreds.empty()) {
1242 BasicBlock *Pred = UncondBranchPreds.back();
1243 DOUT << "FOLDING: " << *BB
1244 << "INTO UNCOND BRANCH PRED: " << *Pred;
1245 UncondBranchPreds.pop_back();
1246 Instruction *UncondBranch = Pred->getTerminator();
1247 // Clone the return and add it to the end of the predecessor.
1248 Instruction *NewRet = RI->clone();
1249 Pred->getInstList().push_back(NewRet);
1251 // If the return instruction returns a value, and if the value was a
1252 // PHI node in "BB", propagate the right value into the return.
1253 if (NewRet->getNumOperands() == 1)
1254 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1255 if (PN->getParent() == BB)
1256 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1257 // Update any PHI nodes in the returning block to realize that we no
1258 // longer branch to them.
1259 BB->removePredecessor(Pred);
1260 Pred->getInstList().erase(UncondBranch);
1263 // If we eliminated all predecessors of the block, delete the block now.
1264 if (pred_begin(BB) == pred_end(BB))
1265 // We know there are no successors, so just nuke the block.
1266 M->getBasicBlockList().erase(BB);
1271 // Check out all of the conditional branches going to this return
1272 // instruction. If any of them just select between returns, change the
1273 // branch itself into a select/return pair.
1274 while (!CondBranchPreds.empty()) {
1275 BranchInst *BI = CondBranchPreds.back();
1276 CondBranchPreds.pop_back();
1277 BasicBlock *TrueSucc = BI->getSuccessor(0);
1278 BasicBlock *FalseSucc = BI->getSuccessor(1);
1279 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1281 // Check to see if the non-BB successor is also a return block.
1282 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1283 // Check to see if there are only PHI instructions in this block.
1284 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1285 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1286 // Okay, we found a branch that is going to two return nodes. If
1287 // there is no return value for this function, just change the
1288 // branch into a return.
1289 if (RI->getNumOperands() == 0) {
1290 TrueSucc->removePredecessor(BI->getParent());
1291 FalseSucc->removePredecessor(BI->getParent());
1292 new ReturnInst(0, BI);
1293 BI->getParent()->getInstList().erase(BI);
1297 // Otherwise, figure out what the true and false return values are
1298 // so we can insert a new select instruction.
1299 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1300 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1302 // Unwrap any PHI nodes in the return blocks.
1303 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1304 if (TVPN->getParent() == TrueSucc)
1305 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1306 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1307 if (FVPN->getParent() == FalseSucc)
1308 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1310 // In order for this transformation to be safe, we must be able to
1311 // unconditionally execute both operands to the return. This is
1312 // normally the case, but we could have a potentially-trapping
1313 // constant expression that prevents this transformation from being
1315 if ((!isa<ConstantExpr>(TrueValue) ||
1316 !cast<ConstantExpr>(TrueValue)->canTrap()) &&
1317 (!isa<ConstantExpr>(TrueValue) ||
1318 !cast<ConstantExpr>(TrueValue)->canTrap())) {
1319 TrueSucc->removePredecessor(BI->getParent());
1320 FalseSucc->removePredecessor(BI->getParent());
1322 // Insert a new select instruction.
1324 Value *BrCond = BI->getCondition();
1325 if (TrueValue != FalseValue)
1326 NewRetVal = new SelectInst(BrCond, TrueValue,
1327 FalseValue, "retval", BI);
1329 NewRetVal = TrueValue;
1331 DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1332 << "\n " << *BI << "Select = " << *NewRetVal
1333 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
1335 new ReturnInst(NewRetVal, BI);
1336 BI->eraseFromParent();
1337 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1338 if (isInstructionTriviallyDead(BrCondI))
1339 BrCondI->eraseFromParent();
1346 } else if (isa<UnwindInst>(BB->begin())) {
1347 // Check to see if the first instruction in this block is just an unwind.
1348 // If so, replace any invoke instructions which use this as an exception
1349 // destination with call instructions, and any unconditional branch
1350 // predecessor with an unwind.
1352 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1353 while (!Preds.empty()) {
1354 BasicBlock *Pred = Preds.back();
1355 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1356 if (BI->isUnconditional()) {
1357 Pred->getInstList().pop_back(); // nuke uncond branch
1358 new UnwindInst(Pred); // Use unwind.
1361 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1362 if (II->getUnwindDest() == BB) {
1363 // Insert a new branch instruction before the invoke, because this
1364 // is now a fall through...
1365 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1366 Pred->getInstList().remove(II); // Take out of symbol table
1368 // Insert the call now...
1369 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1370 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1372 CI->setCallingConv(II->getCallingConv());
1373 // If the invoke produced a value, the Call now does instead
1374 II->replaceAllUsesWith(CI);
1382 // If this block is now dead, remove it.
1383 if (pred_begin(BB) == pred_end(BB)) {
1384 // We know there are no successors, so just nuke the block.
1385 M->getBasicBlockList().erase(BB);
1389 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1390 if (isValueEqualityComparison(SI)) {
1391 // If we only have one predecessor, and if it is a branch on this value,
1392 // see if that predecessor totally determines the outcome of this switch.
1393 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1394 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1395 return SimplifyCFG(BB) || 1;
1397 // If the block only contains the switch, see if we can fold the block
1398 // away into any preds.
1399 if (SI == &BB->front())
1400 if (FoldValueComparisonIntoPredecessors(SI))
1401 return SimplifyCFG(BB) || 1;
1403 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1404 if (BI->isUnconditional()) {
1405 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1406 while (isa<PHINode>(*BBI)) ++BBI;
1408 BasicBlock *Succ = BI->getSuccessor(0);
1409 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1410 Succ != BB) // Don't hurt infinite loops!
1411 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1414 } else { // Conditional branch
1415 if (isValueEqualityComparison(BI)) {
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
1419 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1420 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1421 return SimplifyCFG(BB) || 1;
1423 // This block must be empty, except for the setcond inst, if it exists.
1424 BasicBlock::iterator I = BB->begin();
1426 (&*I == cast<Instruction>(BI->getCondition()) &&
1428 if (FoldValueComparisonIntoPredecessors(BI))
1429 return SimplifyCFG(BB) | true;
1432 // If this is a branch on a phi node in the current block, thread control
1433 // through this block if any PHI node entries are constants.
1434 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1435 if (PN->getParent() == BI->getParent())
1436 if (FoldCondBranchOnPHI(BI))
1437 return SimplifyCFG(BB) | true;
1439 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1440 // branches to us and one of our successors, fold the setcc into the
1441 // predecessor and use logical operations to pick the right destination.
1442 BasicBlock *TrueDest = BI->getSuccessor(0);
1443 BasicBlock *FalseDest = BI->getSuccessor(1);
1444 if (Instruction *Cond = dyn_cast<Instruction>(BI->getCondition()))
1445 if ((isa<CmpInst>(Cond) || isa<BinaryOperator>(Cond)) &&
1446 Cond->getParent() == BB && &BB->front() == Cond &&
1447 Cond->getNext() == BI && Cond->hasOneUse() &&
1448 TrueDest != BB && FalseDest != BB)
1449 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1450 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1451 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
1452 BasicBlock *PredBlock = *PI;
1453 if (PBI->getSuccessor(0) == FalseDest ||
1454 PBI->getSuccessor(1) == TrueDest) {
1455 // Invert the predecessors condition test (xor it with true),
1456 // which allows us to write this code once.
1458 BinaryOperator::createNot(PBI->getCondition(),
1459 PBI->getCondition()->getName()+".not", PBI);
1460 PBI->setCondition(NewCond);
1461 BasicBlock *OldTrue = PBI->getSuccessor(0);
1462 BasicBlock *OldFalse = PBI->getSuccessor(1);
1463 PBI->setSuccessor(0, OldFalse);
1464 PBI->setSuccessor(1, OldTrue);
1467 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1468 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
1469 // Clone Cond into the predecessor basic block, and or/and the
1470 // two conditions together.
1471 Instruction *New = Cond->clone();
1472 New->setName(Cond->getName());
1473 Cond->setName(Cond->getName()+".old");
1474 PredBlock->getInstList().insert(PBI, New);
1475 Instruction::BinaryOps Opcode =
1476 PBI->getSuccessor(0) == TrueDest ?
1477 Instruction::Or : Instruction::And;
1479 BinaryOperator::create(Opcode, PBI->getCondition(),
1480 New, "bothcond", PBI);
1481 PBI->setCondition(NewCond);
1482 if (PBI->getSuccessor(0) == BB) {
1483 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1484 PBI->setSuccessor(0, TrueDest);
1486 if (PBI->getSuccessor(1) == BB) {
1487 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1488 PBI->setSuccessor(1, FalseDest);
1490 return SimplifyCFG(BB) | 1;
1494 // Scan predessor blocks for conditional branchs.
1495 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1496 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1497 if (PBI != BI && PBI->isConditional()) {
1499 // If this block ends with a branch instruction, and if there is a
1500 // predecessor that ends on a branch of the same condition, make this
1501 // conditional branch redundant.
1502 if (PBI->getCondition() == BI->getCondition() &&
1503 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1504 // Okay, the outcome of this conditional branch is statically
1505 // knowable. If this block had a single pred, handle specially.
1506 if (BB->getSinglePredecessor()) {
1507 // Turn this into a branch on constant.
1508 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1509 BI->setCondition(ConstantBool::get(CondIsTrue));
1510 return SimplifyCFG(BB); // Nuke the branch on constant.
1513 // Otherwise, if there are multiple predecessors, insert a PHI that
1514 // merges in the constant and simplify the block result.
1515 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1516 PHINode *NewPN = new PHINode(Type::BoolTy,
1517 BI->getCondition()->getName()+".pr",
1519 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1520 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1521 PBI != BI && PBI->isConditional() &&
1522 PBI->getCondition() == BI->getCondition() &&
1523 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1524 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1525 NewPN->addIncoming(ConstantBool::get(CondIsTrue), *PI);
1527 NewPN->addIncoming(BI->getCondition(), *PI);
1530 BI->setCondition(NewPN);
1531 // This will thread the branch.
1532 return SimplifyCFG(BB) | true;
1536 // If this is a conditional branch in an empty block, and if any
1537 // predecessors is a conditional branch to one of our destinations,
1538 // fold the conditions into logical ops and one cond br.
1539 if (&BB->front() == BI) {
1541 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1543 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1544 PBIOp = 0; BIOp = 1;
1545 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1546 PBIOp = 1; BIOp = 0;
1547 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1553 // Check to make sure that the other destination of this branch
1554 // isn't BB itself. If so, this is an infinite loop that will
1555 // keep getting unwound.
1556 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1559 // Do not perform this transformation if it would require
1560 // insertion of a large number of select instructions. For targets
1561 // without predication/cmovs, this is a big pessimization.
1563 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1565 unsigned NumPhis = 0;
1566 for (BasicBlock::iterator II = CommonDest->begin();
1567 isa<PHINode>(II); ++II, ++NumPhis) {
1569 // Disable this xform.
1576 // Finally, if everything is ok, fold the branches to logical ops.
1578 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1579 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1581 // If OtherDest *is* BB, then this is a basic block with just
1582 // a conditional branch in it, where one edge (OtherDesg) goes
1583 // back to the block. We know that the program doesn't get
1584 // stuck in the infinite loop, so the condition must be such
1585 // that OtherDest isn't branched through. Forward to CommonDest,
1586 // and avoid an infinite loop at optimizer time.
1587 if (OtherDest == BB)
1588 OtherDest = CommonDest;
1590 DOUT << "FOLDING BRs:" << *PBI->getParent()
1591 << "AND: " << *BI->getParent();
1593 // BI may have other predecessors. Because of this, we leave
1594 // it alone, but modify PBI.
1596 // Make sure we get to CommonDest on True&True directions.
1597 Value *PBICond = PBI->getCondition();
1599 PBICond = BinaryOperator::createNot(PBICond,
1600 PBICond->getName()+".not",
1602 Value *BICond = BI->getCondition();
1604 BICond = BinaryOperator::createNot(BICond,
1605 BICond->getName()+".not",
1607 // Merge the conditions.
1609 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1611 // Modify PBI to branch on the new condition to the new dests.
1612 PBI->setCondition(Cond);
1613 PBI->setSuccessor(0, CommonDest);
1614 PBI->setSuccessor(1, OtherDest);
1616 // OtherDest may have phi nodes. If so, add an entry from PBI's
1617 // block that are identical to the entries for BI's block.
1619 for (BasicBlock::iterator II = OtherDest->begin();
1620 (PN = dyn_cast<PHINode>(II)); ++II) {
1621 Value *V = PN->getIncomingValueForBlock(BB);
1622 PN->addIncoming(V, PBI->getParent());
1625 // We know that the CommonDest already had an edge from PBI to
1626 // it. If it has PHIs though, the PHIs may have different
1627 // entries for BB and PBI's BB. If so, insert a select to make
1629 for (BasicBlock::iterator II = CommonDest->begin();
1630 (PN = dyn_cast<PHINode>(II)); ++II) {
1631 Value * BIV = PN->getIncomingValueForBlock(BB);
1632 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1633 Value *PBIV = PN->getIncomingValue(PBBIdx);
1635 // Insert a select in PBI to pick the right value.
1636 Value *NV = new SelectInst(PBICond, PBIV, BIV,
1637 PBIV->getName()+".mux", PBI);
1638 PN->setIncomingValue(PBBIdx, NV);
1642 DOUT << "INTO: " << *PBI->getParent();
1644 // This basic block is probably dead. We know it has at least
1645 // one fewer predecessor.
1646 return SimplifyCFG(BB) | true;
1651 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1652 // If there are any instructions immediately before the unreachable that can
1653 // be removed, do so.
1654 Instruction *Unreachable = BB->getTerminator();
1655 while (Unreachable != BB->begin()) {
1656 BasicBlock::iterator BBI = Unreachable;
1658 if (isa<CallInst>(BBI)) break;
1659 // Delete this instruction
1660 BB->getInstList().erase(BBI);
1664 // If the unreachable instruction is the first in the block, take a gander
1665 // at all of the predecessors of this instruction, and simplify them.
1666 if (&BB->front() == Unreachable) {
1667 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1668 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1669 TerminatorInst *TI = Preds[i]->getTerminator();
1671 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1672 if (BI->isUnconditional()) {
1673 if (BI->getSuccessor(0) == BB) {
1674 new UnreachableInst(TI);
1675 TI->eraseFromParent();
1679 if (BI->getSuccessor(0) == BB) {
1680 new BranchInst(BI->getSuccessor(1), BI);
1681 BI->eraseFromParent();
1682 } else if (BI->getSuccessor(1) == BB) {
1683 new BranchInst(BI->getSuccessor(0), BI);
1684 BI->eraseFromParent();
1688 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1689 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1690 if (SI->getSuccessor(i) == BB) {
1691 BB->removePredecessor(SI->getParent());
1696 // If the default value is unreachable, figure out the most popular
1697 // destination and make it the default.
1698 if (SI->getSuccessor(0) == BB) {
1699 std::map<BasicBlock*, unsigned> Popularity;
1700 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1701 Popularity[SI->getSuccessor(i)]++;
1703 // Find the most popular block.
1704 unsigned MaxPop = 0;
1705 BasicBlock *MaxBlock = 0;
1706 for (std::map<BasicBlock*, unsigned>::iterator
1707 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1708 if (I->second > MaxPop) {
1710 MaxBlock = I->first;
1714 // Make this the new default, allowing us to delete any explicit
1716 SI->setSuccessor(0, MaxBlock);
1719 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1721 if (isa<PHINode>(MaxBlock->begin()))
1722 for (unsigned i = 0; i != MaxPop-1; ++i)
1723 MaxBlock->removePredecessor(SI->getParent());
1725 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1726 if (SI->getSuccessor(i) == MaxBlock) {
1732 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1733 if (II->getUnwindDest() == BB) {
1734 // Convert the invoke to a call instruction. This would be a good
1735 // place to note that the call does not throw though.
1736 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1737 II->removeFromParent(); // Take out of symbol table
1739 // Insert the call now...
1740 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1741 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1743 CI->setCallingConv(II->getCallingConv());
1744 // If the invoke produced a value, the Call does now instead.
1745 II->replaceAllUsesWith(CI);
1752 // If this block is now dead, remove it.
1753 if (pred_begin(BB) == pred_end(BB)) {
1754 // We know there are no successors, so just nuke the block.
1755 M->getBasicBlockList().erase(BB);
1761 // Merge basic blocks into their predecessor if there is only one distinct
1762 // pred, and if there is only one distinct successor of the predecessor, and
1763 // if there are no PHI nodes.
1765 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1766 BasicBlock *OnlyPred = *PI++;
1767 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1768 if (*PI != OnlyPred) {
1769 OnlyPred = 0; // There are multiple different predecessors...
1773 BasicBlock *OnlySucc = 0;
1774 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1775 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1776 // Check to see if there is only one distinct successor...
1777 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1779 for (; SI != SE; ++SI)
1780 if (*SI != OnlySucc) {
1781 OnlySucc = 0; // There are multiple distinct successors!
1787 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
1789 // Resolve any PHI nodes at the start of the block. They are all
1790 // guaranteed to have exactly one entry if they exist, unless there are
1791 // multiple duplicate (but guaranteed to be equal) entries for the
1792 // incoming edges. This occurs when there are multiple edges from
1793 // OnlyPred to OnlySucc.
1795 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1796 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1797 BB->getInstList().pop_front(); // Delete the phi node...
1800 // Delete the unconditional branch from the predecessor...
1801 OnlyPred->getInstList().pop_back();
1803 // Move all definitions in the successor to the predecessor...
1804 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1806 // Make all PHI nodes that referred to BB now refer to Pred as their
1808 BB->replaceAllUsesWith(OnlyPred);
1810 std::string OldName = BB->getName();
1812 // Erase basic block from the function...
1813 M->getBasicBlockList().erase(BB);
1815 // Inherit predecessors name if it exists...
1816 if (!OldName.empty() && !OnlyPred->hasName())
1817 OnlyPred->setName(OldName);
1822 // Otherwise, if this block only has a single predecessor, and if that block
1823 // is a conditional branch, see if we can hoist any code from this block up
1824 // into our predecessor.
1826 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1827 if (BI->isConditional()) {
1828 // Get the other block.
1829 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1830 PI = pred_begin(OtherBB);
1832 if (PI == pred_end(OtherBB)) {
1833 // We have a conditional branch to two blocks that are only reachable
1834 // from the condbr. We know that the condbr dominates the two blocks,
1835 // so see if there is any identical code in the "then" and "else"
1836 // blocks. If so, we can hoist it up to the branching block.
1837 Changed |= HoistThenElseCodeToIf(BI);
1841 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1842 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1843 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1844 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1845 Instruction *Cond = cast<Instruction>(BI->getCondition());
1846 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1847 // 'setne's and'ed together, collect them.
1849 std::vector<ConstantInt*> Values;
1850 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1851 if (CompVal && CompVal->getType()->isInteger()) {
1852 // There might be duplicate constants in the list, which the switch
1853 // instruction can't handle, remove them now.
1854 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1855 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1857 // Figure out which block is which destination.
1858 BasicBlock *DefaultBB = BI->getSuccessor(1);
1859 BasicBlock *EdgeBB = BI->getSuccessor(0);
1860 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1862 // Create the new switch instruction now.
1863 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
1865 // Add all of the 'cases' to the switch instruction.
1866 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1867 New->addCase(Values[i], EdgeBB);
1869 // We added edges from PI to the EdgeBB. As such, if there were any
1870 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1871 // the number of edges added.
1872 for (BasicBlock::iterator BBI = EdgeBB->begin();
1873 isa<PHINode>(BBI); ++BBI) {
1874 PHINode *PN = cast<PHINode>(BBI);
1875 Value *InVal = PN->getIncomingValueForBlock(*PI);
1876 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1877 PN->addIncoming(InVal, *PI);
1880 // Erase the old branch instruction.
1881 (*PI)->getInstList().erase(BI);
1883 // Erase the potentially condition tree that was used to computed the
1884 // branch condition.
1885 ErasePossiblyDeadInstructionTree(Cond);
1890 // If there is a trivial two-entry PHI node in this basic block, and we can
1891 // eliminate it, do so now.
1892 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1893 if (PN->getNumIncomingValues() == 2)
1894 Changed |= FoldTwoEntryPHINode(PN);