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"
29 /// SafeToMergeTerminators - Return true if it is safe to merge these two
30 /// terminator instructions together.
32 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
33 if (SI1 == SI2) return false; // Can't merge with self!
35 // It is not safe to merge these two switch instructions if they have a common
36 // successor, and if that successor has a PHI node, and if *that* PHI node has
37 // conflicting incoming values from the two switch blocks.
38 BasicBlock *SI1BB = SI1->getParent();
39 BasicBlock *SI2BB = SI2->getParent();
40 std::set<BasicBlock*> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
42 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
43 if (SI1Succs.count(*I))
44 for (BasicBlock::iterator BBI = (*I)->begin();
45 isa<PHINode>(BBI); ++BBI) {
46 PHINode *PN = cast<PHINode>(BBI);
47 if (PN->getIncomingValueForBlock(SI1BB) !=
48 PN->getIncomingValueForBlock(SI2BB))
55 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
56 /// now be entries in it from the 'NewPred' block. The values that will be
57 /// flowing into the PHI nodes will be the same as those coming in from
58 /// ExistPred, an existing predecessor of Succ.
59 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
60 BasicBlock *ExistPred) {
61 assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
62 succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
63 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
65 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
66 PHINode *PN = cast<PHINode>(I);
67 Value *V = PN->getIncomingValueForBlock(ExistPred);
68 PN->addIncoming(V, NewPred);
72 // CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
73 // almost-empty BB ending in an unconditional branch to Succ, into succ.
75 // Assumption: Succ is the single successor for BB.
77 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
78 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
80 // Check to see if one of the predecessors of BB is already a predecessor of
81 // Succ. If so, we cannot do the transformation if there are any PHI nodes
82 // with incompatible values coming in from the two edges!
84 if (isa<PHINode>(Succ->front())) {
85 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
86 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
88 if (std::find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
89 // Loop over all of the PHI nodes checking to see if there are
90 // incompatible values coming in.
91 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
92 PHINode *PN = cast<PHINode>(I);
93 // Loop up the entries in the PHI node for BB and for *PI if the
94 // values coming in are non-equal, we cannot merge these two blocks
95 // (instead we should insert a conditional move or something, then
97 if (PN->getIncomingValueForBlock(BB) !=
98 PN->getIncomingValueForBlock(*PI))
99 return false; // Values are not equal...
104 // Finally, if BB has PHI nodes that are used by things other than the PHIs in
105 // Succ and Succ has predecessors that are not Succ and not Pred, we cannot
106 // fold these blocks, as we don't know whether BB dominates Succ or not to
107 // update the PHI nodes correctly.
108 if (!isa<PHINode>(BB->begin()) || Succ->getSinglePredecessor()) return true;
110 // If the predecessors of Succ are only BB and Succ itself, we can handle this.
112 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
113 if (*PI != Succ && *PI != BB) {
117 if (IsSafe) return true;
119 // If the PHI nodes in BB are only used by instructions in Succ, we are ok if
120 // BB and Succ have no common predecessors.
121 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
122 PHINode *PN = cast<PHINode>(I);
123 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E;
125 if (cast<Instruction>(*UI)->getParent() != Succ)
129 // Scan the predecessor sets of BB and Succ, making sure there are no common
130 // predecessors. Common predecessors would cause us to build a phi node with
131 // differing incoming values, which is not legal.
132 std::set<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
133 for (pred_iterator PI = pred_begin(Succ), E = pred_end(Succ); PI != E; ++PI)
134 if (BBPreds.count(*PI))
140 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
141 /// branch to Succ, and contains no instructions other than PHI nodes and the
142 /// branch. If possible, eliminate BB.
143 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
145 // If our successor has PHI nodes, then we need to update them to include
146 // entries for BB's predecessors, not for BB itself. Be careful though,
147 // if this transformation fails (returns true) then we cannot do this
150 if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
152 DEBUG(std::cerr << "Killing Trivial BB: \n" << *BB);
154 if (isa<PHINode>(Succ->begin())) {
155 // If there is more than one pred of succ, and there are PHI nodes in
156 // the successor, then we need to add incoming edges for the PHI nodes
158 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
160 // Loop over all of the PHI nodes in the successor of BB.
161 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
162 PHINode *PN = cast<PHINode>(I);
163 Value *OldVal = PN->removeIncomingValue(BB, false);
164 assert(OldVal && "No entry in PHI for Pred BB!");
166 // If this incoming value is one of the PHI nodes in BB, the new entries
167 // in the PHI node are the entries from the old PHI.
168 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
169 PHINode *OldValPN = cast<PHINode>(OldVal);
170 for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
171 PN->addIncoming(OldValPN->getIncomingValue(i),
172 OldValPN->getIncomingBlock(i));
174 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
175 End = BBPreds.end(); PredI != End; ++PredI) {
176 // Add an incoming value for each of the new incoming values...
177 PN->addIncoming(OldVal, *PredI);
183 if (isa<PHINode>(&BB->front())) {
184 std::vector<BasicBlock*>
185 OldSuccPreds(pred_begin(Succ), pred_end(Succ));
187 // Move all PHI nodes in BB to Succ if they are alive, otherwise
189 while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
190 if (PN->use_empty()) {
191 // Just remove the dead phi. This happens if Succ's PHIs were the only
192 // users of the PHI nodes.
193 PN->eraseFromParent();
195 // The instruction is alive, so this means that Succ must have
196 // *ONLY* had BB as a predecessor, and the PHI node is still valid
197 // now. Simply move it into Succ, because we know that BB
198 // strictly dominated Succ.
199 Succ->getInstList().splice(Succ->begin(),
200 BB->getInstList(), BB->begin());
202 // We need to add new entries for the PHI node to account for
203 // predecessors of Succ that the PHI node does not take into
204 // account. At this point, since we know that BB dominated succ,
205 // this means that we should any newly added incoming edges should
206 // use the PHI node as the value for these edges, because they are
208 for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
209 if (OldSuccPreds[i] != BB)
210 PN->addIncoming(PN, OldSuccPreds[i]);
214 // Everything that jumped to BB now goes to Succ.
215 std::string OldName = BB->getName();
216 BB->replaceAllUsesWith(Succ);
217 BB->eraseFromParent(); // Delete the old basic block.
219 if (!OldName.empty() && !Succ->hasName()) // Transfer name if we can
220 Succ->setName(OldName);
224 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
225 /// presumably PHI nodes in it), check to see if the merge at this block is due
226 /// to an "if condition". If so, return the boolean condition that determines
227 /// which entry into BB will be taken. Also, return by references the block
228 /// that will be entered from if the condition is true, and the block that will
229 /// be entered if the condition is false.
232 static Value *GetIfCondition(BasicBlock *BB,
233 BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
234 assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
235 "Function can only handle blocks with 2 predecessors!");
236 BasicBlock *Pred1 = *pred_begin(BB);
237 BasicBlock *Pred2 = *++pred_begin(BB);
239 // We can only handle branches. Other control flow will be lowered to
240 // branches if possible anyway.
241 if (!isa<BranchInst>(Pred1->getTerminator()) ||
242 !isa<BranchInst>(Pred2->getTerminator()))
244 BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
245 BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
247 // Eliminate code duplication by ensuring that Pred1Br is conditional if
249 if (Pred2Br->isConditional()) {
250 // If both branches are conditional, we don't have an "if statement". In
251 // reality, we could transform this case, but since the condition will be
252 // required anyway, we stand no chance of eliminating it, so the xform is
253 // probably not profitable.
254 if (Pred1Br->isConditional())
257 std::swap(Pred1, Pred2);
258 std::swap(Pred1Br, Pred2Br);
261 if (Pred1Br->isConditional()) {
262 // If we found a conditional branch predecessor, make sure that it branches
263 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
264 if (Pred1Br->getSuccessor(0) == BB &&
265 Pred1Br->getSuccessor(1) == Pred2) {
268 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
269 Pred1Br->getSuccessor(1) == BB) {
273 // We know that one arm of the conditional goes to BB, so the other must
274 // go somewhere unrelated, and this must not be an "if statement".
278 // The only thing we have to watch out for here is to make sure that Pred2
279 // doesn't have incoming edges from other blocks. If it does, the condition
280 // doesn't dominate BB.
281 if (++pred_begin(Pred2) != pred_end(Pred2))
284 return Pred1Br->getCondition();
287 // Ok, if we got here, both predecessors end with an unconditional branch to
288 // BB. Don't panic! If both blocks only have a single (identical)
289 // predecessor, and THAT is a conditional branch, then we're all ok!
290 if (pred_begin(Pred1) == pred_end(Pred1) ||
291 ++pred_begin(Pred1) != pred_end(Pred1) ||
292 pred_begin(Pred2) == pred_end(Pred2) ||
293 ++pred_begin(Pred2) != pred_end(Pred2) ||
294 *pred_begin(Pred1) != *pred_begin(Pred2))
297 // Otherwise, if this is a conditional branch, then we can use it!
298 BasicBlock *CommonPred = *pred_begin(Pred1);
299 if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
300 assert(BI->isConditional() && "Two successors but not conditional?");
301 if (BI->getSuccessor(0) == Pred1) {
308 return BI->getCondition();
314 // If we have a merge point of an "if condition" as accepted above, return true
315 // if the specified value dominates the block. We don't handle the true
316 // generality of domination here, just a special case which works well enough
319 // If AggressiveInsts is non-null, and if V does not dominate BB, we check to
320 // see if V (which must be an instruction) is cheap to compute and is
321 // non-trapping. If both are true, the instruction is inserted into the set and
323 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
324 std::set<Instruction*> *AggressiveInsts) {
325 Instruction *I = dyn_cast<Instruction>(V);
327 // Non-instructions all dominate instructions, but not all constantexprs
328 // can be executed unconditionally.
329 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
334 BasicBlock *PBB = I->getParent();
336 // We don't want to allow weird loops that might have the "if condition" in
337 // the bottom of this block.
338 if (PBB == BB) return false;
340 // If this instruction is defined in a block that contains an unconditional
341 // branch to BB, then it must be in the 'conditional' part of the "if
343 if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
344 if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
345 if (!AggressiveInsts) return false;
346 // Okay, it looks like the instruction IS in the "condition". Check to
347 // see if its a cheap instruction to unconditionally compute, and if it
348 // only uses stuff defined outside of the condition. If so, hoist it out.
349 switch (I->getOpcode()) {
350 default: return false; // Cannot hoist this out safely.
351 case Instruction::Load:
352 // We can hoist loads that are non-volatile and obviously cannot trap.
353 if (cast<LoadInst>(I)->isVolatile())
355 if (!isa<AllocaInst>(I->getOperand(0)) &&
356 !isa<Constant>(I->getOperand(0)))
359 // Finally, we have to check to make sure there are no instructions
360 // before the load in its basic block, as we are going to hoist the loop
361 // out to its predecessor.
362 if (PBB->begin() != BasicBlock::iterator(I))
365 case Instruction::Add:
366 case Instruction::Sub:
367 case Instruction::And:
368 case Instruction::Or:
369 case Instruction::Xor:
370 case Instruction::Shl:
371 case Instruction::Shr:
372 case Instruction::SetEQ:
373 case Instruction::SetNE:
374 case Instruction::SetLT:
375 case Instruction::SetGT:
376 case Instruction::SetLE:
377 case Instruction::SetGE:
378 break; // These are all cheap and non-trapping instructions.
381 // Okay, we can only really hoist these out if their operands are not
382 // defined in the conditional region.
383 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
384 if (!DominatesMergePoint(I->getOperand(i), BB, 0))
386 // Okay, it's safe to do this! Remember this instruction.
387 AggressiveInsts->insert(I);
393 // GatherConstantSetEQs - Given a potentially 'or'd together collection of seteq
394 // instructions that compare a value against a constant, return the value being
395 // compared, and stick the constant into the Values vector.
396 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
397 if (Instruction *Inst = dyn_cast<Instruction>(V))
398 if (Inst->getOpcode() == Instruction::SetEQ) {
399 if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
401 return Inst->getOperand(0);
402 } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
404 return Inst->getOperand(1);
406 } else if (Inst->getOpcode() == Instruction::Or) {
407 if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
408 if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
415 // GatherConstantSetNEs - Given a potentially 'and'd together collection of
416 // setne instructions that compare a value against a constant, return the value
417 // being compared, and stick the constant into the Values vector.
418 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
419 if (Instruction *Inst = dyn_cast<Instruction>(V))
420 if (Inst->getOpcode() == Instruction::SetNE) {
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::Cast) {
429 // Cast of X to bool is really a comparison against zero.
430 assert(Inst->getType() == Type::BoolTy && "Can only handle bool values!");
431 Values.push_back(ConstantInt::get(Inst->getOperand(0)->getType(), 0));
432 return Inst->getOperand(0);
433 } else if (Inst->getOpcode() == Instruction::And) {
434 if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
435 if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
444 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
445 /// bunch of comparisons of one value against constants, return the value and
446 /// the constants being compared.
447 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
448 std::vector<ConstantInt*> &Values) {
449 if (Cond->getOpcode() == Instruction::Or) {
450 CompVal = GatherConstantSetEQs(Cond, Values);
452 // Return true to indicate that the condition is true if the CompVal is
453 // equal to one of the constants.
455 } else if (Cond->getOpcode() == Instruction::And) {
456 CompVal = GatherConstantSetNEs(Cond, Values);
458 // Return false to indicate that the condition is false if the CompVal is
459 // equal to one of the constants.
465 /// ErasePossiblyDeadInstructionTree - If the specified instruction is dead and
466 /// has no side effects, nuke it. If it uses any instructions that become dead
467 /// because the instruction is now gone, nuke them too.
468 static void ErasePossiblyDeadInstructionTree(Instruction *I) {
469 if (!isInstructionTriviallyDead(I)) return;
471 std::vector<Instruction*> InstrsToInspect;
472 InstrsToInspect.push_back(I);
474 while (!InstrsToInspect.empty()) {
475 I = InstrsToInspect.back();
476 InstrsToInspect.pop_back();
478 if (!isInstructionTriviallyDead(I)) continue;
480 // If I is in the work list multiple times, remove previous instances.
481 for (unsigned i = 0, e = InstrsToInspect.size(); i != e; ++i)
482 if (InstrsToInspect[i] == I) {
483 InstrsToInspect.erase(InstrsToInspect.begin()+i);
487 // Add operands of dead instruction to worklist.
488 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
489 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
490 InstrsToInspect.push_back(OpI);
492 // Remove dead instruction.
493 I->eraseFromParent();
497 // isValueEqualityComparison - Return true if the specified terminator checks to
498 // see if a value is equal to constant integer value.
499 static Value *isValueEqualityComparison(TerminatorInst *TI) {
500 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
501 // Do not permit merging of large switch instructions into their
502 // predecessors unless there is only one predecessor.
503 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
504 pred_end(SI->getParent())) > 128)
507 return SI->getCondition();
509 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
510 if (BI->isConditional() && BI->getCondition()->hasOneUse())
511 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
512 if ((SCI->getOpcode() == Instruction::SetEQ ||
513 SCI->getOpcode() == Instruction::SetNE) &&
514 isa<ConstantInt>(SCI->getOperand(1)))
515 return SCI->getOperand(0);
519 // Given a value comparison instruction, decode all of the 'cases' that it
520 // represents and return the 'default' block.
522 GetValueEqualityComparisonCases(TerminatorInst *TI,
523 std::vector<std::pair<ConstantInt*,
524 BasicBlock*> > &Cases) {
525 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
526 Cases.reserve(SI->getNumCases());
527 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
528 Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
529 return SI->getDefaultDest();
532 BranchInst *BI = cast<BranchInst>(TI);
533 SetCondInst *SCI = cast<SetCondInst>(BI->getCondition());
534 Cases.push_back(std::make_pair(cast<ConstantInt>(SCI->getOperand(1)),
535 BI->getSuccessor(SCI->getOpcode() ==
536 Instruction::SetNE)));
537 return BI->getSuccessor(SCI->getOpcode() == Instruction::SetEQ);
541 // EliminateBlockCases - Given an vector of bb/value pairs, remove any entries
542 // in the list that match the specified block.
543 static void EliminateBlockCases(BasicBlock *BB,
544 std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
545 for (unsigned i = 0, e = Cases.size(); i != e; ++i)
546 if (Cases[i].second == BB) {
547 Cases.erase(Cases.begin()+i);
552 // ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
555 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
556 std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
557 std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
559 // Make V1 be smaller than V2.
560 if (V1->size() > V2->size())
563 if (V1->size() == 0) return false;
564 if (V1->size() == 1) {
566 ConstantInt *TheVal = (*V1)[0].first;
567 for (unsigned i = 0, e = V2->size(); i != e; ++i)
568 if (TheVal == (*V2)[i].first)
572 // Otherwise, just sort both lists and compare element by element.
573 std::sort(V1->begin(), V1->end());
574 std::sort(V2->begin(), V2->end());
575 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
576 while (i1 != e1 && i2 != e2) {
577 if ((*V1)[i1].first == (*V2)[i2].first)
579 if ((*V1)[i1].first < (*V2)[i2].first)
587 // SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
588 // terminator instruction and its block is known to only have a single
589 // predecessor block, check to see if that predecessor is also a value
590 // comparison with the same value, and if that comparison determines the outcome
591 // of this comparison. If so, simplify TI. This does a very limited form of
593 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
595 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
596 if (!PredVal) return false; // Not a value comparison in predecessor.
598 Value *ThisVal = isValueEqualityComparison(TI);
599 assert(ThisVal && "This isn't a value comparison!!");
600 if (ThisVal != PredVal) return false; // Different predicates.
602 // Find out information about when control will move from Pred to TI's block.
603 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
604 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
606 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
608 // Find information about how control leaves this block.
609 std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
610 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
611 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
613 // If TI's block is the default block from Pred's comparison, potentially
614 // simplify TI based on this knowledge.
615 if (PredDef == TI->getParent()) {
616 // If we are here, we know that the value is none of those cases listed in
617 // PredCases. If there are any cases in ThisCases that are in PredCases, we
619 if (ValuesOverlap(PredCases, ThisCases)) {
620 if (BranchInst *BTI = dyn_cast<BranchInst>(TI)) {
621 // Okay, one of the successors of this condbr is dead. Convert it to a
623 assert(ThisCases.size() == 1 && "Branch can only have one case!");
624 Value *Cond = BTI->getCondition();
625 // Insert the new branch.
626 Instruction *NI = new BranchInst(ThisDef, TI);
628 // Remove PHI node entries for the dead edge.
629 ThisCases[0].second->removePredecessor(TI->getParent());
631 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
632 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
634 TI->eraseFromParent(); // Nuke the old one.
635 // If condition is now dead, nuke it.
636 if (Instruction *CondI = dyn_cast<Instruction>(Cond))
637 ErasePossiblyDeadInstructionTree(CondI);
641 SwitchInst *SI = cast<SwitchInst>(TI);
642 // Okay, TI has cases that are statically dead, prune them away.
643 std::set<Constant*> DeadCases;
644 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
645 DeadCases.insert(PredCases[i].first);
647 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
648 << "Through successor TI: " << *TI);
650 for (unsigned i = SI->getNumCases()-1; i != 0; --i)
651 if (DeadCases.count(SI->getCaseValue(i))) {
652 SI->getSuccessor(i)->removePredecessor(TI->getParent());
656 DEBUG(std::cerr << "Leaving: " << *TI << "\n");
662 // Otherwise, TI's block must correspond to some matched value. Find out
663 // which value (or set of values) this is.
664 ConstantInt *TIV = 0;
665 BasicBlock *TIBB = TI->getParent();
666 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
667 if (PredCases[i].second == TIBB)
669 TIV = PredCases[i].first;
671 return false; // Cannot handle multiple values coming to this block.
672 assert(TIV && "No edge from pred to succ?");
674 // Okay, we found the one constant that our value can be if we get into TI's
675 // BB. Find out which successor will unconditionally be branched to.
676 BasicBlock *TheRealDest = 0;
677 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
678 if (ThisCases[i].first == TIV) {
679 TheRealDest = ThisCases[i].second;
683 // If not handled by any explicit cases, it is handled by the default case.
684 if (TheRealDest == 0) TheRealDest = ThisDef;
686 // Remove PHI node entries for dead edges.
687 BasicBlock *CheckEdge = TheRealDest;
688 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
689 if (*SI != CheckEdge)
690 (*SI)->removePredecessor(TIBB);
694 // Insert the new branch.
695 Instruction *NI = new BranchInst(TheRealDest, TI);
697 DEBUG(std::cerr << "Threading pred instr: " << *Pred->getTerminator()
698 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
699 Instruction *Cond = 0;
700 if (BranchInst *BI = dyn_cast<BranchInst>(TI))
701 Cond = dyn_cast<Instruction>(BI->getCondition());
702 TI->eraseFromParent(); // Nuke the old one.
704 if (Cond) ErasePossiblyDeadInstructionTree(Cond);
710 // FoldValueComparisonIntoPredecessors - The specified terminator is a value
711 // equality comparison instruction (either a switch or a branch on "X == c").
712 // See if any of the predecessors of the terminator block are value comparisons
713 // on the same value. If so, and if safe to do so, fold them together.
714 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
715 BasicBlock *BB = TI->getParent();
716 Value *CV = isValueEqualityComparison(TI); // CondVal
717 assert(CV && "Not a comparison?");
718 bool Changed = false;
720 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
721 while (!Preds.empty()) {
722 BasicBlock *Pred = Preds.back();
725 // See if the predecessor is a comparison with the same value.
726 TerminatorInst *PTI = Pred->getTerminator();
727 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
729 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
730 // Figure out which 'cases' to copy from SI to PSI.
731 std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
732 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
734 std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
735 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
737 // Based on whether the default edge from PTI goes to BB or not, fill in
738 // PredCases and PredDefault with the new switch cases we would like to
740 std::vector<BasicBlock*> NewSuccessors;
742 if (PredDefault == BB) {
743 // If this is the default destination from PTI, only the edges in TI
744 // that don't occur in PTI, or that branch to BB will be activated.
745 std::set<ConstantInt*> PTIHandled;
746 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
747 if (PredCases[i].second != BB)
748 PTIHandled.insert(PredCases[i].first);
750 // The default destination is BB, we don't need explicit targets.
751 std::swap(PredCases[i], PredCases.back());
752 PredCases.pop_back();
756 // Reconstruct the new switch statement we will be building.
757 if (PredDefault != BBDefault) {
758 PredDefault->removePredecessor(Pred);
759 PredDefault = BBDefault;
760 NewSuccessors.push_back(BBDefault);
762 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
763 if (!PTIHandled.count(BBCases[i].first) &&
764 BBCases[i].second != BBDefault) {
765 PredCases.push_back(BBCases[i]);
766 NewSuccessors.push_back(BBCases[i].second);
770 // If this is not the default destination from PSI, only the edges
771 // in SI that occur in PSI with a destination of BB will be
773 std::set<ConstantInt*> PTIHandled;
774 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
775 if (PredCases[i].second == BB) {
776 PTIHandled.insert(PredCases[i].first);
777 std::swap(PredCases[i], PredCases.back());
778 PredCases.pop_back();
782 // Okay, now we know which constants were sent to BB from the
783 // predecessor. Figure out where they will all go now.
784 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
785 if (PTIHandled.count(BBCases[i].first)) {
786 // If this is one we are capable of getting...
787 PredCases.push_back(BBCases[i]);
788 NewSuccessors.push_back(BBCases[i].second);
789 PTIHandled.erase(BBCases[i].first);// This constant is taken care of
792 // If there are any constants vectored to BB that TI doesn't handle,
793 // they must go to the default destination of TI.
794 for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
795 E = PTIHandled.end(); I != E; ++I) {
796 PredCases.push_back(std::make_pair(*I, BBDefault));
797 NewSuccessors.push_back(BBDefault);
801 // Okay, at this point, we know which new successor Pred will get. Make
802 // sure we update the number of entries in the PHI nodes for these
804 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
805 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
807 // Now that the successors are updated, create the new Switch instruction.
808 SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
809 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
810 NewSI->addCase(PredCases[i].first, PredCases[i].second);
812 Instruction *DeadCond = 0;
813 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
814 // If PTI is a branch, remember the condition.
815 DeadCond = dyn_cast<Instruction>(BI->getCondition());
816 Pred->getInstList().erase(PTI);
818 // If the condition is dead now, remove the instruction tree.
819 if (DeadCond) ErasePossiblyDeadInstructionTree(DeadCond);
821 // Okay, last check. If BB is still a successor of PSI, then we must
822 // have an infinite loop case. If so, add an infinitely looping block
823 // to handle the case to preserve the behavior of the code.
824 BasicBlock *InfLoopBlock = 0;
825 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
826 if (NewSI->getSuccessor(i) == BB) {
827 if (InfLoopBlock == 0) {
828 // Insert it at the end of the loop, because it's either code,
829 // or it won't matter if it's hot. :)
830 InfLoopBlock = new BasicBlock("infloop", BB->getParent());
831 new BranchInst(InfLoopBlock, InfLoopBlock);
833 NewSI->setSuccessor(i, InfLoopBlock);
842 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
843 /// BB2, hoist any common code in the two blocks up into the branch block. The
844 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
845 static bool HoistThenElseCodeToIf(BranchInst *BI) {
846 // This does very trivial matching, with limited scanning, to find identical
847 // instructions in the two blocks. In particular, we don't want to get into
848 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
849 // such, we currently just scan for obviously identical instructions in an
851 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
852 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
854 Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
855 if (I1->getOpcode() != I2->getOpcode() || !I1->isIdenticalTo(I2) ||
859 // If we get here, we can hoist at least one instruction.
860 BasicBlock *BIParent = BI->getParent();
863 // If we are hoisting the terminator instruction, don't move one (making a
864 // broken BB), instead clone it, and remove BI.
865 if (isa<TerminatorInst>(I1))
866 goto HoistTerminator;
868 // For a normal instruction, we just move one to right before the branch,
869 // then replace all uses of the other with the first. Finally, we remove
870 // the now redundant second instruction.
871 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
872 if (!I2->use_empty())
873 I2->replaceAllUsesWith(I1);
874 BB2->getInstList().erase(I2);
878 } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
883 // Okay, it is safe to hoist the terminator.
884 Instruction *NT = I1->clone();
885 BIParent->getInstList().insert(BI, NT);
886 if (NT->getType() != Type::VoidTy) {
887 I1->replaceAllUsesWith(NT);
888 I2->replaceAllUsesWith(NT);
889 NT->setName(I1->getName());
892 // Hoisting one of the terminators from our successor is a great thing.
893 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
894 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
895 // nodes, so we insert select instruction to compute the final result.
896 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
897 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
899 for (BasicBlock::iterator BBI = SI->begin();
900 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
901 Value *BB1V = PN->getIncomingValueForBlock(BB1);
902 Value *BB2V = PN->getIncomingValueForBlock(BB2);
904 // These values do not agree. Insert a select instruction before NT
905 // that determines the right value.
906 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
908 SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
909 BB1V->getName()+"."+BB2V->getName(), NT);
910 // Make the PHI node use the select for all incoming values for BB1/BB2
911 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
912 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
913 PN->setIncomingValue(i, SI);
918 // Update any PHI nodes in our new successors.
919 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
920 AddPredecessorToBlock(*SI, BIParent, BB1);
922 BI->eraseFromParent();
926 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
927 /// across this block.
928 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
929 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
932 // If this basic block contains anything other than a PHI (which controls the
933 // branch) and branch itself, bail out. FIXME: improve this in the future.
934 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
935 if (Size > 10) return false; // Don't clone large BB's.
937 // We can only support instructions that are do not define values that are
938 // live outside of the current basic block.
939 for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
941 Instruction *U = cast<Instruction>(*UI);
942 if (U->getParent() != BB || isa<PHINode>(U)) return false;
945 // Looks ok, continue checking.
951 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
952 /// that is defined in the same block as the branch and if any PHI entries are
953 /// constants, thread edges corresponding to that entry to be branches to their
954 /// ultimate destination.
955 static bool FoldCondBranchOnPHI(BranchInst *BI) {
956 BasicBlock *BB = BI->getParent();
957 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
958 // NOTE: we currently cannot transform this case if the PHI node is used
959 // outside of the block.
960 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
963 // Degenerate case of a single entry PHI.
964 if (PN->getNumIncomingValues() == 1) {
965 if (PN->getIncomingValue(0) != PN)
966 PN->replaceAllUsesWith(PN->getIncomingValue(0));
968 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
969 PN->eraseFromParent();
973 // Now we know that this block has multiple preds and two succs.
974 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
976 // Okay, this is a simple enough basic block. See if any phi values are
978 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
979 if (ConstantBool *CB = dyn_cast<ConstantBool>(PN->getIncomingValue(i))) {
980 // Okay, we now know that all edges from PredBB should be revectored to
981 // branch to RealDest.
982 BasicBlock *PredBB = PN->getIncomingBlock(i);
983 BasicBlock *RealDest = BI->getSuccessor(!CB->getValue());
985 if (RealDest == BB) continue; // Skip self loops.
987 // The dest block might have PHI nodes, other predecessors and other
988 // difficult cases. Instead of being smart about this, just insert a new
989 // block that jumps to the destination block, effectively splitting
990 // the edge we are about to create.
991 BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
992 RealDest->getParent(), RealDest);
993 new BranchInst(RealDest, EdgeBB);
995 for (BasicBlock::iterator BBI = RealDest->begin();
996 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
997 Value *V = PN->getIncomingValueForBlock(BB);
998 PN->addIncoming(V, EdgeBB);
1001 // BB may have instructions that are being threaded over. Clone these
1002 // instructions into EdgeBB. We know that there will be no uses of the
1003 // cloned instructions outside of EdgeBB.
1004 BasicBlock::iterator InsertPt = EdgeBB->begin();
1005 std::map<Value*, Value*> TranslateMap; // Track translated values.
1006 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1007 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1008 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1010 // Clone the instruction.
1011 Instruction *N = BBI->clone();
1012 if (BBI->hasName()) N->setName(BBI->getName()+".c");
1014 // Update operands due to translation.
1015 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1016 std::map<Value*, Value*>::iterator PI =
1017 TranslateMap.find(N->getOperand(i));
1018 if (PI != TranslateMap.end())
1019 N->setOperand(i, PI->second);
1022 // Check for trivial simplification.
1023 if (Constant *C = ConstantFoldInstruction(N)) {
1024 TranslateMap[BBI] = C;
1025 delete N; // Constant folded away, don't need actual inst
1027 // Insert the new instruction into its new home.
1028 EdgeBB->getInstList().insert(InsertPt, N);
1029 if (!BBI->use_empty())
1030 TranslateMap[BBI] = N;
1035 // Loop over all of the edges from PredBB to BB, changing them to branch
1036 // to EdgeBB instead.
1037 TerminatorInst *PredBBTI = PredBB->getTerminator();
1038 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1039 if (PredBBTI->getSuccessor(i) == BB) {
1040 BB->removePredecessor(PredBB);
1041 PredBBTI->setSuccessor(i, EdgeBB);
1044 // Recurse, simplifying any other constants.
1045 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 DEBUG(std::cerr << "FOUND IF CONDITION! " << *IfCond << " T: "
1067 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
1069 // Loop over the PHI's seeing if we can promote them all to select
1070 // instructions. While we are at it, keep track of the instructions
1071 // that need to be moved to the dominating block.
1072 std::set<Instruction*> AggressiveInsts;
1074 BasicBlock::iterator AfterPHIIt = BB->begin();
1075 while (isa<PHINode>(AfterPHIIt)) {
1076 PHINode *PN = cast<PHINode>(AfterPHIIt++);
1077 if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
1078 if (PN->getIncomingValue(0) != PN)
1079 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1081 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
1082 } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
1083 &AggressiveInsts) ||
1084 !DominatesMergePoint(PN->getIncomingValue(1), BB,
1085 &AggressiveInsts)) {
1090 // If we all PHI nodes are promotable, check to make sure that all
1091 // instructions in the predecessor blocks can be promoted as well. If
1092 // not, we won't be able to get rid of the control flow, so it's not
1093 // worth promoting to select instructions.
1094 BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
1095 PN = cast<PHINode>(BB->begin());
1096 BasicBlock *Pred = PN->getIncomingBlock(0);
1097 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1099 DomBlock = *pred_begin(Pred);
1100 for (BasicBlock::iterator I = Pred->begin();
1101 !isa<TerminatorInst>(I); ++I)
1102 if (!AggressiveInsts.count(I)) {
1103 // This is not an aggressive instruction that we can promote.
1104 // Because of this, we won't be able to get rid of the control
1105 // flow, so the xform is not worth it.
1110 Pred = PN->getIncomingBlock(1);
1111 if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
1113 DomBlock = *pred_begin(Pred);
1114 for (BasicBlock::iterator I = Pred->begin();
1115 !isa<TerminatorInst>(I); ++I)
1116 if (!AggressiveInsts.count(I)) {
1117 // This is not an aggressive instruction that we can promote.
1118 // Because of this, we won't be able to get rid of the control
1119 // flow, so the xform is not worth it.
1124 // If we can still promote the PHI nodes after this gauntlet of tests,
1125 // do all of the PHI's now.
1127 // Move all 'aggressive' instructions, which are defined in the
1128 // conditional parts of the if's up to the dominating block.
1130 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1131 IfBlock1->getInstList(),
1133 IfBlock1->getTerminator());
1136 DomBlock->getInstList().splice(DomBlock->getTerminator(),
1137 IfBlock2->getInstList(),
1139 IfBlock2->getTerminator());
1142 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1143 // Change the PHI node into a select instruction.
1145 PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1147 PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
1149 std::string Name = PN->getName(); PN->setName("");
1150 PN->replaceAllUsesWith(new SelectInst(IfCond, TrueVal, FalseVal,
1152 BB->getInstList().erase(PN);
1158 /// ConstantIntOrdering - This class implements a stable ordering of constant
1159 /// integers that does not depend on their address. This is important for
1160 /// applications that sort ConstantInt's to ensure uniqueness.
1161 struct ConstantIntOrdering {
1162 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
1163 return LHS->getZExtValue() < RHS->getZExtValue();
1168 // SimplifyCFG - This function is used to do simplification of a CFG. For
1169 // example, it adjusts branches to branches to eliminate the extra hop, it
1170 // eliminates unreachable basic blocks, and does other "peephole" optimization
1171 // of the CFG. It returns true if a modification was made.
1173 // WARNING: The entry node of a function may not be simplified.
1175 bool llvm::SimplifyCFG(BasicBlock *BB) {
1176 bool Changed = false;
1177 Function *M = BB->getParent();
1179 assert(BB && BB->getParent() && "Block not embedded in function!");
1180 assert(BB->getTerminator() && "Degenerate basic block encountered!");
1181 assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
1183 // Remove basic blocks that have no predecessors... which are unreachable.
1184 if (pred_begin(BB) == pred_end(BB) ||
1185 *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
1186 DEBUG(std::cerr << "Removing BB: \n" << *BB);
1188 // Loop through all of our successors and make sure they know that one
1189 // of their predecessors is going away.
1190 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1191 SI->removePredecessor(BB);
1193 while (!BB->empty()) {
1194 Instruction &I = BB->back();
1195 // If this instruction is used, replace uses with an arbitrary
1196 // value. Because control flow can't get here, we don't care
1197 // what we replace the value with. Note that since this block is
1198 // unreachable, and all values contained within it must dominate their
1199 // uses, that all uses will eventually be removed.
1201 // Make all users of this instruction use undef instead
1202 I.replaceAllUsesWith(UndefValue::get(I.getType()));
1204 // Remove the instruction from the basic block
1205 BB->getInstList().pop_back();
1207 M->getBasicBlockList().erase(BB);
1211 // Check to see if we can constant propagate this terminator instruction
1213 Changed |= ConstantFoldTerminator(BB);
1215 // If this is a returning block with only PHI nodes in it, fold the return
1216 // instruction into any unconditional branch predecessors.
1218 // If any predecessor is a conditional branch that just selects among
1219 // different return values, fold the replace the branch/return with a select
1221 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
1222 BasicBlock::iterator BBI = BB->getTerminator();
1223 if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
1224 // Find predecessors that end with branches.
1225 std::vector<BasicBlock*> UncondBranchPreds;
1226 std::vector<BranchInst*> CondBranchPreds;
1227 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1228 TerminatorInst *PTI = (*PI)->getTerminator();
1229 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
1230 if (BI->isUnconditional())
1231 UncondBranchPreds.push_back(*PI);
1233 CondBranchPreds.push_back(BI);
1236 // If we found some, do the transformation!
1237 if (!UncondBranchPreds.empty()) {
1238 while (!UncondBranchPreds.empty()) {
1239 BasicBlock *Pred = UncondBranchPreds.back();
1240 DEBUG(std::cerr << "FOLDING: " << *BB
1241 << "INTO UNCOND BRANCH PRED: " << *Pred);
1242 UncondBranchPreds.pop_back();
1243 Instruction *UncondBranch = Pred->getTerminator();
1244 // Clone the return and add it to the end of the predecessor.
1245 Instruction *NewRet = RI->clone();
1246 Pred->getInstList().push_back(NewRet);
1248 // If the return instruction returns a value, and if the value was a
1249 // PHI node in "BB", propagate the right value into the return.
1250 if (NewRet->getNumOperands() == 1)
1251 if (PHINode *PN = dyn_cast<PHINode>(NewRet->getOperand(0)))
1252 if (PN->getParent() == BB)
1253 NewRet->setOperand(0, PN->getIncomingValueForBlock(Pred));
1254 // Update any PHI nodes in the returning block to realize that we no
1255 // longer branch to them.
1256 BB->removePredecessor(Pred);
1257 Pred->getInstList().erase(UncondBranch);
1260 // If we eliminated all predecessors of the block, delete the block now.
1261 if (pred_begin(BB) == pred_end(BB))
1262 // We know there are no successors, so just nuke the block.
1263 M->getBasicBlockList().erase(BB);
1268 // Check out all of the conditional branches going to this return
1269 // instruction. If any of them just select between returns, change the
1270 // branch itself into a select/return pair.
1271 while (!CondBranchPreds.empty()) {
1272 BranchInst *BI = CondBranchPreds.back();
1273 CondBranchPreds.pop_back();
1274 BasicBlock *TrueSucc = BI->getSuccessor(0);
1275 BasicBlock *FalseSucc = BI->getSuccessor(1);
1276 BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
1278 // Check to see if the non-BB successor is also a return block.
1279 if (isa<ReturnInst>(OtherSucc->getTerminator())) {
1280 // Check to see if there are only PHI instructions in this block.
1281 BasicBlock::iterator OSI = OtherSucc->getTerminator();
1282 if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
1283 // Okay, we found a branch that is going to two return nodes. If
1284 // there is no return value for this function, just change the
1285 // branch into a return.
1286 if (RI->getNumOperands() == 0) {
1287 TrueSucc->removePredecessor(BI->getParent());
1288 FalseSucc->removePredecessor(BI->getParent());
1289 new ReturnInst(0, BI);
1290 BI->getParent()->getInstList().erase(BI);
1294 // Otherwise, figure out what the true and false return values are
1295 // so we can insert a new select instruction.
1296 Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
1297 Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
1299 // Unwrap any PHI nodes in the return blocks.
1300 if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
1301 if (TVPN->getParent() == TrueSucc)
1302 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1303 if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
1304 if (FVPN->getParent() == FalseSucc)
1305 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
1307 // In order for this transformation to be safe, we must be able to
1308 // unconditionally execute both operands to the return. This is
1309 // normally the case, but we could have a potentially-trapping
1310 // constant expression that prevents this transformation from being
1312 if ((!isa<ConstantExpr>(TrueValue) ||
1313 !cast<ConstantExpr>(TrueValue)->canTrap()) &&
1314 (!isa<ConstantExpr>(TrueValue) ||
1315 !cast<ConstantExpr>(TrueValue)->canTrap())) {
1316 TrueSucc->removePredecessor(BI->getParent());
1317 FalseSucc->removePredecessor(BI->getParent());
1319 // Insert a new select instruction.
1321 Value *BrCond = BI->getCondition();
1322 if (TrueValue != FalseValue)
1323 NewRetVal = new SelectInst(BrCond, TrueValue,
1324 FalseValue, "retval", BI);
1326 NewRetVal = TrueValue;
1328 DEBUG(std::cerr << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
1329 << "\n " << *BI << "Select = " << *NewRetVal
1330 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
1332 new ReturnInst(NewRetVal, BI);
1333 BI->eraseFromParent();
1334 if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
1335 if (isInstructionTriviallyDead(BrCondI))
1336 BrCondI->eraseFromParent();
1343 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->begin())) {
1344 // Check to see if the first instruction in this block is just an unwind.
1345 // If so, replace any invoke instructions which use this as an exception
1346 // destination with call instructions, and any unconditional branch
1347 // predecessor with an unwind.
1349 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1350 while (!Preds.empty()) {
1351 BasicBlock *Pred = Preds.back();
1352 if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
1353 if (BI->isUnconditional()) {
1354 Pred->getInstList().pop_back(); // nuke uncond branch
1355 new UnwindInst(Pred); // Use unwind.
1358 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
1359 if (II->getUnwindDest() == BB) {
1360 // Insert a new branch instruction before the invoke, because this
1361 // is now a fall through...
1362 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1363 Pred->getInstList().remove(II); // Take out of symbol table
1365 // Insert the call now...
1366 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1367 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1369 CI->setCallingConv(II->getCallingConv());
1370 // If the invoke produced a value, the Call now does instead
1371 II->replaceAllUsesWith(CI);
1379 // If this block is now dead, remove it.
1380 if (pred_begin(BB) == pred_end(BB)) {
1381 // We know there are no successors, so just nuke the block.
1382 M->getBasicBlockList().erase(BB);
1386 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1387 if (isValueEqualityComparison(SI)) {
1388 // If we only have one predecessor, and if it is a branch on this value,
1389 // see if that predecessor totally determines the outcome of this switch.
1390 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1391 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
1392 return SimplifyCFG(BB) || 1;
1394 // If the block only contains the switch, see if we can fold the block
1395 // away into any preds.
1396 if (SI == &BB->front())
1397 if (FoldValueComparisonIntoPredecessors(SI))
1398 return SimplifyCFG(BB) || 1;
1400 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1401 if (BI->isUnconditional()) {
1402 BasicBlock::iterator BBI = BB->begin(); // Skip over phi nodes...
1403 while (isa<PHINode>(*BBI)) ++BBI;
1405 BasicBlock *Succ = BI->getSuccessor(0);
1406 if (BBI->isTerminator() && // Terminator is the only non-phi instruction!
1407 Succ != BB) // Don't hurt infinite loops!
1408 if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
1411 } else { // Conditional branch
1412 if (Value *CompVal = isValueEqualityComparison(BI)) {
1413 // If we only have one predecessor, and if it is a branch on this value,
1414 // see if that predecessor totally determines the outcome of this
1416 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
1417 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
1418 return SimplifyCFG(BB) || 1;
1420 // This block must be empty, except for the setcond inst, if it exists.
1421 BasicBlock::iterator I = BB->begin();
1423 (&*I == cast<Instruction>(BI->getCondition()) &&
1425 if (FoldValueComparisonIntoPredecessors(BI))
1426 return SimplifyCFG(BB) | true;
1429 // If this is a branch on a phi node in the current block, thread control
1430 // through this block if any PHI node entries are constants.
1431 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
1432 if (PN->getParent() == BI->getParent())
1433 if (FoldCondBranchOnPHI(BI))
1434 return SimplifyCFG(BB) | true;
1436 // If this basic block is ONLY a setcc and a branch, and if a predecessor
1437 // branches to us and one of our successors, fold the setcc into the
1438 // predecessor and use logical operations to pick the right destination.
1439 BasicBlock *TrueDest = BI->getSuccessor(0);
1440 BasicBlock *FalseDest = BI->getSuccessor(1);
1441 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(BI->getCondition()))
1442 if (Cond->getParent() == BB && &BB->front() == Cond &&
1443 Cond->getNext() == BI && Cond->hasOneUse() &&
1444 TrueDest != BB && FalseDest != BB)
1445 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI!=E; ++PI)
1446 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1447 if (PBI->isConditional() && SafeToMergeTerminators(BI, PBI)) {
1448 BasicBlock *PredBlock = *PI;
1449 if (PBI->getSuccessor(0) == FalseDest ||
1450 PBI->getSuccessor(1) == TrueDest) {
1451 // Invert the predecessors condition test (xor it with true),
1452 // which allows us to write this code once.
1454 BinaryOperator::createNot(PBI->getCondition(),
1455 PBI->getCondition()->getName()+".not", PBI);
1456 PBI->setCondition(NewCond);
1457 BasicBlock *OldTrue = PBI->getSuccessor(0);
1458 BasicBlock *OldFalse = PBI->getSuccessor(1);
1459 PBI->setSuccessor(0, OldFalse);
1460 PBI->setSuccessor(1, OldTrue);
1463 if ((PBI->getSuccessor(0) == TrueDest && FalseDest != BB) ||
1464 (PBI->getSuccessor(1) == FalseDest && TrueDest != BB)) {
1465 // Clone Cond into the predecessor basic block, and or/and the
1466 // two conditions together.
1467 Instruction *New = Cond->clone();
1468 New->setName(Cond->getName());
1469 Cond->setName(Cond->getName()+".old");
1470 PredBlock->getInstList().insert(PBI, New);
1471 Instruction::BinaryOps Opcode =
1472 PBI->getSuccessor(0) == TrueDest ?
1473 Instruction::Or : Instruction::And;
1475 BinaryOperator::create(Opcode, PBI->getCondition(),
1476 New, "bothcond", PBI);
1477 PBI->setCondition(NewCond);
1478 if (PBI->getSuccessor(0) == BB) {
1479 AddPredecessorToBlock(TrueDest, PredBlock, BB);
1480 PBI->setSuccessor(0, TrueDest);
1482 if (PBI->getSuccessor(1) == BB) {
1483 AddPredecessorToBlock(FalseDest, PredBlock, BB);
1484 PBI->setSuccessor(1, FalseDest);
1486 return SimplifyCFG(BB) | 1;
1490 // Scan predessor blocks for conditional branchs.
1491 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1492 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1493 if (PBI != BI && PBI->isConditional()) {
1495 // If this block ends with a branch instruction, and if there is a
1496 // predecessor that ends on a branch of the same condition, make this
1497 // conditional branch redundant.
1498 if (PBI->getCondition() == BI->getCondition() &&
1499 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1500 // Okay, the outcome of this conditional branch is statically
1501 // knowable. If this block had a single pred, handle specially.
1502 if (BB->getSinglePredecessor()) {
1503 // Turn this into a branch on constant.
1504 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1505 BI->setCondition(ConstantBool::get(CondIsTrue));
1506 return SimplifyCFG(BB); // Nuke the branch on constant.
1509 // Otherwise, if there are multiple predecessors, insert a PHI that
1510 // merges in the constant and simplify the block result.
1511 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
1512 PHINode *NewPN = new PHINode(Type::BoolTy,
1513 BI->getCondition()->getName()+".pr",
1515 for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1516 if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
1517 PBI != BI && PBI->isConditional() &&
1518 PBI->getCondition() == BI->getCondition() &&
1519 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
1520 bool CondIsTrue = PBI->getSuccessor(0) == BB;
1521 NewPN->addIncoming(ConstantBool::get(CondIsTrue), *PI);
1523 NewPN->addIncoming(BI->getCondition(), *PI);
1526 BI->setCondition(NewPN);
1527 // This will thread the branch.
1528 return SimplifyCFG(BB) | true;
1532 // If this is a conditional branch in an empty block, and if any
1533 // predecessors is a conditional branch to one of our destinations,
1534 // fold the conditions into logical ops and one cond br.
1535 if (&BB->front() == BI) {
1537 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
1539 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
1540 PBIOp = 0; BIOp = 1;
1541 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
1542 PBIOp = 1; BIOp = 0;
1543 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
1549 // Check to make sure that the other destination of this branch
1550 // isn't BB itself. If so, this is an infinite loop that will
1551 // keep getting unwound.
1552 if (PBIOp != -1 && PBI->getSuccessor(PBIOp) == BB)
1555 // Finally, if everything is ok, fold the branches to logical ops.
1557 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
1558 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
1560 // If OtherDest *is* BB, then this is a basic block with just
1561 // a conditional branch in it, where one edge (OtherDesg) goes
1562 // back to the block. We know that the program doesn't get
1563 // stuck in the infinite loop, so the condition must be such
1564 // that OtherDest isn't branched through. Forward to CommonDest,
1565 // and avoid an infinite loop at optimizer time.
1566 if (OtherDest == BB)
1567 OtherDest = CommonDest;
1569 DEBUG(std::cerr << "FOLDING BRs:" << *PBI->getParent()
1570 << "AND: " << *BI->getParent());
1572 // BI may have other predecessors. Because of this, we leave
1573 // it alone, but modify PBI.
1575 // Make sure we get to CommonDest on True&True directions.
1576 Value *PBICond = PBI->getCondition();
1578 PBICond = BinaryOperator::createNot(PBICond,
1579 PBICond->getName()+".not",
1581 Value *BICond = BI->getCondition();
1583 BICond = BinaryOperator::createNot(BICond,
1584 BICond->getName()+".not",
1586 // Merge the conditions.
1588 BinaryOperator::createOr(PBICond, BICond, "brmerge", PBI);
1590 // Modify PBI to branch on the new condition to the new dests.
1591 PBI->setCondition(Cond);
1592 PBI->setSuccessor(0, CommonDest);
1593 PBI->setSuccessor(1, OtherDest);
1595 // OtherDest may have phi nodes. If so, add an entry from PBI's
1596 // block that are identical to the entries for BI's block.
1598 for (BasicBlock::iterator II = OtherDest->begin();
1599 (PN = dyn_cast<PHINode>(II)); ++II) {
1600 Value *V = PN->getIncomingValueForBlock(BB);
1601 PN->addIncoming(V, PBI->getParent());
1604 // We know that the CommonDest already had an edge from PBI to
1605 // it. If it has PHIs though, the PHIs may have different
1606 // entries for BB and PBI's BB. If so, insert a select to make
1608 for (BasicBlock::iterator II = CommonDest->begin();
1609 (PN = dyn_cast<PHINode>(II)); ++II) {
1610 Value * BIV = PN->getIncomingValueForBlock(BB);
1611 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
1612 Value *PBIV = PN->getIncomingValue(PBBIdx);
1614 // Insert a select in PBI to pick the right value.
1615 Value *NV = new SelectInst(PBICond, PBIV, BIV,
1616 PBIV->getName()+".mux", PBI);
1617 PN->setIncomingValue(PBBIdx, NV);
1621 DEBUG(std::cerr << "INTO: " << *PBI->getParent());
1623 // This basic block is probably dead. We know it has at least
1624 // one fewer predecessor.
1625 return SimplifyCFG(BB) | true;
1630 } else if (isa<UnreachableInst>(BB->getTerminator())) {
1631 // If there are any instructions immediately before the unreachable that can
1632 // be removed, do so.
1633 Instruction *Unreachable = BB->getTerminator();
1634 while (Unreachable != BB->begin()) {
1635 BasicBlock::iterator BBI = Unreachable;
1637 if (isa<CallInst>(BBI)) break;
1638 // Delete this instruction
1639 BB->getInstList().erase(BBI);
1643 // If the unreachable instruction is the first in the block, take a gander
1644 // at all of the predecessors of this instruction, and simplify them.
1645 if (&BB->front() == Unreachable) {
1646 std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
1647 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
1648 TerminatorInst *TI = Preds[i]->getTerminator();
1650 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1651 if (BI->isUnconditional()) {
1652 if (BI->getSuccessor(0) == BB) {
1653 new UnreachableInst(TI);
1654 TI->eraseFromParent();
1658 if (BI->getSuccessor(0) == BB) {
1659 new BranchInst(BI->getSuccessor(1), BI);
1660 BI->eraseFromParent();
1661 } else if (BI->getSuccessor(1) == BB) {
1662 new BranchInst(BI->getSuccessor(0), BI);
1663 BI->eraseFromParent();
1667 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1668 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1669 if (SI->getSuccessor(i) == BB) {
1670 BB->removePredecessor(SI->getParent());
1675 // If the default value is unreachable, figure out the most popular
1676 // destination and make it the default.
1677 if (SI->getSuccessor(0) == BB) {
1678 std::map<BasicBlock*, unsigned> Popularity;
1679 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1680 Popularity[SI->getSuccessor(i)]++;
1682 // Find the most popular block.
1683 unsigned MaxPop = 0;
1684 BasicBlock *MaxBlock = 0;
1685 for (std::map<BasicBlock*, unsigned>::iterator
1686 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
1687 if (I->second > MaxPop) {
1689 MaxBlock = I->first;
1693 // Make this the new default, allowing us to delete any explicit
1695 SI->setSuccessor(0, MaxBlock);
1698 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
1700 if (isa<PHINode>(MaxBlock->begin()))
1701 for (unsigned i = 0; i != MaxPop-1; ++i)
1702 MaxBlock->removePredecessor(SI->getParent());
1704 for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
1705 if (SI->getSuccessor(i) == MaxBlock) {
1711 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
1712 if (II->getUnwindDest() == BB) {
1713 // Convert the invoke to a call instruction. This would be a good
1714 // place to note that the call does not throw though.
1715 BranchInst *BI = new BranchInst(II->getNormalDest(), II);
1716 II->removeFromParent(); // Take out of symbol table
1718 // Insert the call now...
1719 std::vector<Value*> Args(II->op_begin()+3, II->op_end());
1720 CallInst *CI = new CallInst(II->getCalledValue(), Args,
1722 CI->setCallingConv(II->getCallingConv());
1723 // If the invoke produced a value, the Call does now instead.
1724 II->replaceAllUsesWith(CI);
1731 // If this block is now dead, remove it.
1732 if (pred_begin(BB) == pred_end(BB)) {
1733 // We know there are no successors, so just nuke the block.
1734 M->getBasicBlockList().erase(BB);
1740 // Merge basic blocks into their predecessor if there is only one distinct
1741 // pred, and if there is only one distinct successor of the predecessor, and
1742 // if there are no PHI nodes.
1744 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
1745 BasicBlock *OnlyPred = *PI++;
1746 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
1747 if (*PI != OnlyPred) {
1748 OnlyPred = 0; // There are multiple different predecessors...
1752 BasicBlock *OnlySucc = 0;
1753 if (OnlyPred && OnlyPred != BB && // Don't break self loops
1754 OnlyPred->getTerminator()->getOpcode() != Instruction::Invoke) {
1755 // Check to see if there is only one distinct successor...
1756 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
1758 for (; SI != SE; ++SI)
1759 if (*SI != OnlySucc) {
1760 OnlySucc = 0; // There are multiple distinct successors!
1766 DEBUG(std::cerr << "Merging: " << *BB << "into: " << *OnlyPred);
1767 TerminatorInst *Term = OnlyPred->getTerminator();
1769 // Resolve any PHI nodes at the start of the block. They are all
1770 // guaranteed to have exactly one entry if they exist, unless there are
1771 // multiple duplicate (but guaranteed to be equal) entries for the
1772 // incoming edges. This occurs when there are multiple edges from
1773 // OnlyPred to OnlySucc.
1775 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
1776 PN->replaceAllUsesWith(PN->getIncomingValue(0));
1777 BB->getInstList().pop_front(); // Delete the phi node...
1780 // Delete the unconditional branch from the predecessor...
1781 OnlyPred->getInstList().pop_back();
1783 // Move all definitions in the successor to the predecessor...
1784 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
1786 // Make all PHI nodes that referred to BB now refer to Pred as their
1788 BB->replaceAllUsesWith(OnlyPred);
1790 std::string OldName = BB->getName();
1792 // Erase basic block from the function...
1793 M->getBasicBlockList().erase(BB);
1795 // Inherit predecessors name if it exists...
1796 if (!OldName.empty() && !OnlyPred->hasName())
1797 OnlyPred->setName(OldName);
1802 // Otherwise, if this block only has a single predecessor, and if that block
1803 // is a conditional branch, see if we can hoist any code from this block up
1804 // into our predecessor.
1806 if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
1807 if (BI->isConditional()) {
1808 // Get the other block.
1809 BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
1810 PI = pred_begin(OtherBB);
1812 if (PI == pred_end(OtherBB)) {
1813 // We have a conditional branch to two blocks that are only reachable
1814 // from the condbr. We know that the condbr dominates the two blocks,
1815 // so see if there is any identical code in the "then" and "else"
1816 // blocks. If so, we can hoist it up to the branching block.
1817 Changed |= HoistThenElseCodeToIf(BI);
1821 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1822 if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
1823 // Change br (X == 0 | X == 1), T, F into a switch instruction.
1824 if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
1825 Instruction *Cond = cast<Instruction>(BI->getCondition());
1826 // If this is a bunch of seteq's or'd together, or if it's a bunch of
1827 // 'setne's and'ed together, collect them.
1829 std::vector<ConstantInt*> Values;
1830 bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
1831 if (CompVal && CompVal->getType()->isInteger()) {
1832 // There might be duplicate constants in the list, which the switch
1833 // instruction can't handle, remove them now.
1834 std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
1835 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
1837 // Figure out which block is which destination.
1838 BasicBlock *DefaultBB = BI->getSuccessor(1);
1839 BasicBlock *EdgeBB = BI->getSuccessor(0);
1840 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
1842 // Create the new switch instruction now.
1843 SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
1845 // Add all of the 'cases' to the switch instruction.
1846 for (unsigned i = 0, e = Values.size(); i != e; ++i)
1847 New->addCase(Values[i], EdgeBB);
1849 // We added edges from PI to the EdgeBB. As such, if there were any
1850 // PHI nodes in EdgeBB, they need entries to be added corresponding to
1851 // the number of edges added.
1852 for (BasicBlock::iterator BBI = EdgeBB->begin();
1853 isa<PHINode>(BBI); ++BBI) {
1854 PHINode *PN = cast<PHINode>(BBI);
1855 Value *InVal = PN->getIncomingValueForBlock(*PI);
1856 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
1857 PN->addIncoming(InVal, *PI);
1860 // Erase the old branch instruction.
1861 (*PI)->getInstList().erase(BI);
1863 // Erase the potentially condition tree that was used to computed the
1864 // branch condition.
1865 ErasePossiblyDeadInstructionTree(Cond);
1870 // If there is a trivial two-entry PHI node in this basic block, and we can
1871 // eliminate it, do so now.
1872 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
1873 if (PN->getNumIncomingValues() == 2)
1874 Changed |= FoldTwoEntryPHINode(PN);