LLVM API Documentation

SimplifyCFG.cpp

Go to the documentation of this file.
00001 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Peephole optimize the CFG.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "simplifycfg"
00015 #include "llvm/Transforms/Utils/Local.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/Instructions.h"
00018 #include "llvm/Type.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/Support/CFG.h"
00021 #include "llvm/Support/Debug.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/ADT/SmallPtrSet.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include <algorithm>
00028 #include <functional>
00029 #include <set>
00030 #include <map>
00031 using namespace llvm;
00032 
00033 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
00034 
00035 /// SafeToMergeTerminators - Return true if it is safe to merge these two
00036 /// terminator instructions together.
00037 ///
00038 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
00039   if (SI1 == SI2) return false;  // Can't merge with self!
00040   
00041   // It is not safe to merge these two switch instructions if they have a common
00042   // successor, and if that successor has a PHI node, and if *that* PHI node has
00043   // conflicting incoming values from the two switch blocks.
00044   BasicBlock *SI1BB = SI1->getParent();
00045   BasicBlock *SI2BB = SI2->getParent();
00046   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
00047   
00048   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
00049     if (SI1Succs.count(*I))
00050       for (BasicBlock::iterator BBI = (*I)->begin();
00051            isa<PHINode>(BBI); ++BBI) {
00052         PHINode *PN = cast<PHINode>(BBI);
00053         if (PN->getIncomingValueForBlock(SI1BB) !=
00054             PN->getIncomingValueForBlock(SI2BB))
00055           return false;
00056       }
00057         
00058   return true;
00059 }
00060 
00061 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
00062 /// now be entries in it from the 'NewPred' block.  The values that will be
00063 /// flowing into the PHI nodes will be the same as those coming in from
00064 /// ExistPred, an existing predecessor of Succ.
00065 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
00066                                   BasicBlock *ExistPred) {
00067   assert(std::find(succ_begin(ExistPred), succ_end(ExistPred), Succ) !=
00068          succ_end(ExistPred) && "ExistPred is not a predecessor of Succ!");
00069   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
00070   
00071   PHINode *PN;
00072   for (BasicBlock::iterator I = Succ->begin();
00073        (PN = dyn_cast<PHINode>(I)); ++I)
00074     PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
00075 }
00076 
00077 /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
00078 /// almost-empty BB ending in an unconditional branch to Succ, into succ.
00079 ///
00080 /// Assumption: Succ is the single successor for BB.
00081 ///
00082 static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
00083   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
00084 
00085   DOUT << "Looking to fold " << BB->getNameStart() << " into " 
00086        << Succ->getNameStart() << "\n";
00087   // Shortcut, if there is only a single predecessor is must be BB and merging
00088   // is always safe
00089   if (Succ->getSinglePredecessor()) return true;
00090 
00091   typedef SmallPtrSet<Instruction*, 16> InstrSet;
00092   InstrSet BBPHIs;
00093 
00094   // Make a list of all phi nodes in BB
00095   BasicBlock::iterator BBI = BB->begin();
00096   while (isa<PHINode>(*BBI)) BBPHIs.insert(BBI++);
00097 
00098   // Make a list of the predecessors of BB
00099   typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
00100   BlockSet BBPreds(pred_begin(BB), pred_end(BB));
00101 
00102   // Use that list to make another list of common predecessors of BB and Succ
00103   BlockSet CommonPreds;
00104   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
00105         PI != PE; ++PI)
00106     if (BBPreds.count(*PI))
00107       CommonPreds.insert(*PI);
00108 
00109   // Shortcut, if there are no common predecessors, merging is always safe
00110   if (CommonPreds.empty())
00111     return true;
00112   
00113   // Look at all the phi nodes in Succ, to see if they present a conflict when
00114   // merging these blocks
00115   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00116     PHINode *PN = cast<PHINode>(I);
00117 
00118     // If the incoming value from BB is again a PHINode in
00119     // BB which has the same incoming value for *PI as PN does, we can
00120     // merge the phi nodes and then the blocks can still be merged
00121     PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
00122     if (BBPN && BBPN->getParent() == BB) {
00123       for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
00124             PI != PE; PI++) {
00125         if (BBPN->getIncomingValueForBlock(*PI) 
00126               != PN->getIncomingValueForBlock(*PI)) {
00127           DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in " 
00128                << Succ->getNameStart() << " is conflicting with " 
00129                << BBPN->getNameStart() << " with regard to common predecessor "
00130                << (*PI)->getNameStart() << "\n";
00131           return false;
00132         }
00133       }
00134       // Remove this phinode from the list of phis in BB, since it has been
00135       // handled.
00136       BBPHIs.erase(BBPN);
00137     } else {
00138       Value* Val = PN->getIncomingValueForBlock(BB);
00139       for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
00140             PI != PE; PI++) {
00141         // See if the incoming value for the common predecessor is equal to the
00142         // one for BB, in which case this phi node will not prevent the merging
00143         // of the block.
00144         if (Val != PN->getIncomingValueForBlock(*PI)) {
00145           DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in " 
00146           << Succ->getNameStart() << " is conflicting with regard to common "
00147           << "predecessor " << (*PI)->getNameStart() << "\n";
00148           return false;
00149         }
00150       }
00151     }
00152   }
00153 
00154   // If there are any other phi nodes in BB that don't have a phi node in Succ
00155   // to merge with, they must be moved to Succ completely. However, for any
00156   // predecessors of Succ, branches will be added to the phi node that just
00157   // point to itself. So, for any common predecessors, this must not cause
00158   // conflicts.
00159   for (InstrSet::iterator I = BBPHIs.begin(), E = BBPHIs.end();
00160         I != E; I++) {
00161     PHINode *PN = cast<PHINode>(*I);
00162     for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
00163           PI != PE; PI++)
00164       if (PN->getIncomingValueForBlock(*PI) != PN) {
00165         DOUT << "Can't fold, phi node " << *PN->getNameStart() << " in " 
00166              << BB->getNameStart() << " is conflicting with regard to common "
00167              << "predecessor " << (*PI)->getNameStart() << "\n";
00168         return false;
00169       }
00170   }
00171 
00172   return true;
00173 }
00174 
00175 /// TryToSimplifyUncondBranchFromEmptyBlock - BB contains an unconditional
00176 /// branch to Succ, and contains no instructions other than PHI nodes and the
00177 /// branch.  If possible, eliminate BB.
00178 static bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
00179                                                     BasicBlock *Succ) {
00180   // Check to see if merging these blocks would cause conflicts for any of the
00181   // phi nodes in BB or Succ. If not, we can safely merge.
00182   if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
00183   
00184   DOUT << "Killing Trivial BB: \n" << *BB;
00185   
00186   if (isa<PHINode>(Succ->begin())) {
00187     // If there is more than one pred of succ, and there are PHI nodes in
00188     // the successor, then we need to add incoming edges for the PHI nodes
00189     //
00190     const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
00191     
00192     // Loop over all of the PHI nodes in the successor of BB.
00193     for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
00194       PHINode *PN = cast<PHINode>(I);
00195       Value *OldVal = PN->removeIncomingValue(BB, false);
00196       assert(OldVal && "No entry in PHI for Pred BB!");
00197       
00198       // If this incoming value is one of the PHI nodes in BB, the new entries
00199       // in the PHI node are the entries from the old PHI.
00200       if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
00201         PHINode *OldValPN = cast<PHINode>(OldVal);
00202         for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
00203           // Note that, since we are merging phi nodes and BB and Succ might
00204           // have common predecessors, we could end up with a phi node with
00205           // identical incoming branches. This will be cleaned up later (and
00206           // will trigger asserts if we try to clean it up now, without also
00207           // simplifying the corresponding conditional branch).
00208           PN->addIncoming(OldValPN->getIncomingValue(i),
00209                           OldValPN->getIncomingBlock(i));
00210       } else {
00211         // Add an incoming value for each of the new incoming values.
00212         for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
00213           PN->addIncoming(OldVal, BBPreds[i]);
00214       }
00215     }
00216   }
00217   
00218   if (isa<PHINode>(&BB->front())) {
00219     SmallVector<BasicBlock*, 16>
00220     OldSuccPreds(pred_begin(Succ), pred_end(Succ));
00221     
00222     // Move all PHI nodes in BB to Succ if they are alive, otherwise
00223     // delete them.
00224     while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
00225       if (PN->use_empty()) {
00226         // Just remove the dead phi.  This happens if Succ's PHIs were the only
00227         // users of the PHI nodes.
00228         PN->eraseFromParent();
00229         continue;
00230       }
00231     
00232       // The instruction is alive, so this means that BB must dominate all
00233       // predecessors of Succ (Since all uses of the PN are after its
00234       // definition, so in Succ or a block dominated by Succ. If a predecessor
00235       // of Succ would not be dominated by BB, PN would violate the def before
00236       // use SSA demand). Therefore, we can simply move the phi node to the
00237       // next block.
00238       Succ->getInstList().splice(Succ->begin(),
00239                                  BB->getInstList(), BB->begin());
00240       
00241       // We need to add new entries for the PHI node to account for
00242       // predecessors of Succ that the PHI node does not take into
00243       // account.  At this point, since we know that BB dominated succ and all
00244       // of its predecessors, this means that we should any newly added
00245       // incoming edges should use the PHI node itself as the value for these
00246       // edges, because they are loop back edges.
00247       for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
00248         if (OldSuccPreds[i] != BB)
00249           PN->addIncoming(PN, OldSuccPreds[i]);
00250     }
00251   }
00252     
00253   // Everything that jumped to BB now goes to Succ.
00254   BB->replaceAllUsesWith(Succ);
00255   if (!Succ->hasName()) Succ->takeName(BB);
00256   BB->eraseFromParent();              // Delete the old basic block.
00257   return true;
00258 }
00259 
00260 /// GetIfCondition - Given a basic block (BB) with two predecessors (and
00261 /// presumably PHI nodes in it), check to see if the merge at this block is due
00262 /// to an "if condition".  If so, return the boolean condition that determines
00263 /// which entry into BB will be taken.  Also, return by references the block
00264 /// that will be entered from if the condition is true, and the block that will
00265 /// be entered if the condition is false.
00266 ///
00267 ///
00268 static Value *GetIfCondition(BasicBlock *BB,
00269                              BasicBlock *&IfTrue, BasicBlock *&IfFalse) {
00270   assert(std::distance(pred_begin(BB), pred_end(BB)) == 2 &&
00271          "Function can only handle blocks with 2 predecessors!");
00272   BasicBlock *Pred1 = *pred_begin(BB);
00273   BasicBlock *Pred2 = *++pred_begin(BB);
00274 
00275   // We can only handle branches.  Other control flow will be lowered to
00276   // branches if possible anyway.
00277   if (!isa<BranchInst>(Pred1->getTerminator()) ||
00278       !isa<BranchInst>(Pred2->getTerminator()))
00279     return 0;
00280   BranchInst *Pred1Br = cast<BranchInst>(Pred1->getTerminator());
00281   BranchInst *Pred2Br = cast<BranchInst>(Pred2->getTerminator());
00282 
00283   // Eliminate code duplication by ensuring that Pred1Br is conditional if
00284   // either are.
00285   if (Pred2Br->isConditional()) {
00286     // If both branches are conditional, we don't have an "if statement".  In
00287     // reality, we could transform this case, but since the condition will be
00288     // required anyway, we stand no chance of eliminating it, so the xform is
00289     // probably not profitable.
00290     if (Pred1Br->isConditional())
00291       return 0;
00292 
00293     std::swap(Pred1, Pred2);
00294     std::swap(Pred1Br, Pred2Br);
00295   }
00296 
00297   if (Pred1Br->isConditional()) {
00298     // If we found a conditional branch predecessor, make sure that it branches
00299     // to BB and Pred2Br.  If it doesn't, this isn't an "if statement".
00300     if (Pred1Br->getSuccessor(0) == BB &&
00301         Pred1Br->getSuccessor(1) == Pred2) {
00302       IfTrue = Pred1;
00303       IfFalse = Pred2;
00304     } else if (Pred1Br->getSuccessor(0) == Pred2 &&
00305                Pred1Br->getSuccessor(1) == BB) {
00306       IfTrue = Pred2;
00307       IfFalse = Pred1;
00308     } else {
00309       // We know that one arm of the conditional goes to BB, so the other must
00310       // go somewhere unrelated, and this must not be an "if statement".
00311       return 0;
00312     }
00313 
00314     // The only thing we have to watch out for here is to make sure that Pred2
00315     // doesn't have incoming edges from other blocks.  If it does, the condition
00316     // doesn't dominate BB.
00317     if (++pred_begin(Pred2) != pred_end(Pred2))
00318       return 0;
00319 
00320     return Pred1Br->getCondition();
00321   }
00322 
00323   // Ok, if we got here, both predecessors end with an unconditional branch to
00324   // BB.  Don't panic!  If both blocks only have a single (identical)
00325   // predecessor, and THAT is a conditional branch, then we're all ok!
00326   if (pred_begin(Pred1) == pred_end(Pred1) ||
00327       ++pred_begin(Pred1) != pred_end(Pred1) ||
00328       pred_begin(Pred2) == pred_end(Pred2) ||
00329       ++pred_begin(Pred2) != pred_end(Pred2) ||
00330       *pred_begin(Pred1) != *pred_begin(Pred2))
00331     return 0;
00332 
00333   // Otherwise, if this is a conditional branch, then we can use it!
00334   BasicBlock *CommonPred = *pred_begin(Pred1);
00335   if (BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator())) {
00336     assert(BI->isConditional() && "Two successors but not conditional?");
00337     if (BI->getSuccessor(0) == Pred1) {
00338       IfTrue = Pred1;
00339       IfFalse = Pred2;
00340     } else {
00341       IfTrue = Pred2;
00342       IfFalse = Pred1;
00343     }
00344     return BI->getCondition();
00345   }
00346   return 0;
00347 }
00348 
00349 
00350 /// DominatesMergePoint - If we have a merge point of an "if condition" as
00351 /// accepted above, return true if the specified value dominates the block.  We
00352 /// don't handle the true generality of domination here, just a special case
00353 /// which works well enough for us.
00354 ///
00355 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
00356 /// see if V (which must be an instruction) is cheap to compute and is
00357 /// non-trapping.  If both are true, the instruction is inserted into the set
00358 /// and true is returned.
00359 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
00360                                 std::set<Instruction*> *AggressiveInsts) {
00361   Instruction *I = dyn_cast<Instruction>(V);
00362   if (!I) {
00363     // Non-instructions all dominate instructions, but not all constantexprs
00364     // can be executed unconditionally.
00365     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
00366       if (C->canTrap())
00367         return false;
00368     return true;
00369   }
00370   BasicBlock *PBB = I->getParent();
00371 
00372   // We don't want to allow weird loops that might have the "if condition" in
00373   // the bottom of this block.
00374   if (PBB == BB) return false;
00375 
00376   // If this instruction is defined in a block that contains an unconditional
00377   // branch to BB, then it must be in the 'conditional' part of the "if
00378   // statement".
00379   if (BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator()))
00380     if (BI->isUnconditional() && BI->getSuccessor(0) == BB) {
00381       if (!AggressiveInsts) return false;
00382       // Okay, it looks like the instruction IS in the "condition".  Check to
00383       // see if its a cheap instruction to unconditionally compute, and if it
00384       // only uses stuff defined outside of the condition.  If so, hoist it out.
00385       switch (I->getOpcode()) {
00386       default: return false;  // Cannot hoist this out safely.
00387       case Instruction::Load:
00388         // We can hoist loads that are non-volatile and obviously cannot trap.
00389         if (cast<LoadInst>(I)->isVolatile())
00390           return false;
00391         // FIXME: A computation of a constant can trap!
00392         if (!isa<AllocaInst>(I->getOperand(0)) &&
00393             !isa<Constant>(I->getOperand(0)))
00394           return false;
00395 
00396         // Finally, we have to check to make sure there are no instructions
00397         // before the load in its basic block, as we are going to hoist the loop
00398         // out to its predecessor.
00399         if (PBB->begin() != BasicBlock::iterator(I))
00400           return false;
00401         break;
00402       case Instruction::Add:
00403       case Instruction::Sub:
00404       case Instruction::And:
00405       case Instruction::Or:
00406       case Instruction::Xor:
00407       case Instruction::Shl:
00408       case Instruction::LShr:
00409       case Instruction::AShr:
00410       case Instruction::ICmp:
00411       case Instruction::FCmp:
00412         if (I->getOperand(0)->getType()->isFPOrFPVector())
00413           return false;  // FP arithmetic might trap.
00414         break;   // These are all cheap and non-trapping instructions.
00415       }
00416 
00417       // Okay, we can only really hoist these out if their operands are not
00418       // defined in the conditional region.
00419       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
00420         if (!DominatesMergePoint(*i, BB, 0))
00421           return false;
00422       // Okay, it's safe to do this!  Remember this instruction.
00423       AggressiveInsts->insert(I);
00424     }
00425 
00426   return true;
00427 }
00428 
00429 /// GatherConstantSetEQs - Given a potentially 'or'd together collection of
00430 /// icmp_eq instructions that compare a value against a constant, return the
00431 /// value being compared, and stick the constant into the Values vector.
00432 static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
00433   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
00434     if (Inst->getOpcode() == Instruction::ICmp &&
00435         cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
00436       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
00437         Values.push_back(C);
00438         return Inst->getOperand(0);
00439       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
00440         Values.push_back(C);
00441         return Inst->getOperand(1);
00442       }
00443     } else if (Inst->getOpcode() == Instruction::Or) {
00444       if (Value *LHS = GatherConstantSetEQs(Inst->getOperand(0), Values))
00445         if (Value *RHS = GatherConstantSetEQs(Inst->getOperand(1), Values))
00446           if (LHS == RHS)
00447             return LHS;
00448     }
00449   }
00450   return 0;
00451 }
00452 
00453 /// GatherConstantSetNEs - Given a potentially 'and'd together collection of
00454 /// setne instructions that compare a value against a constant, return the value
00455 /// being compared, and stick the constant into the Values vector.
00456 static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
00457   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
00458     if (Inst->getOpcode() == Instruction::ICmp &&
00459                cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
00460       if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
00461         Values.push_back(C);
00462         return Inst->getOperand(0);
00463       } else if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(0))) {
00464         Values.push_back(C);
00465         return Inst->getOperand(1);
00466       }
00467     } else if (Inst->getOpcode() == Instruction::And) {
00468       if (Value *LHS = GatherConstantSetNEs(Inst->getOperand(0), Values))
00469         if (Value *RHS = GatherConstantSetNEs(Inst->getOperand(1), Values))
00470           if (LHS == RHS)
00471             return LHS;
00472     }
00473   }
00474   return 0;
00475 }
00476 
00477 /// GatherValueComparisons - If the specified Cond is an 'and' or 'or' of a
00478 /// bunch of comparisons of one value against constants, return the value and
00479 /// the constants being compared.
00480 static bool GatherValueComparisons(Instruction *Cond, Value *&CompVal,
00481                                    std::vector<ConstantInt*> &Values) {
00482   if (Cond->getOpcode() == Instruction::Or) {
00483     CompVal = GatherConstantSetEQs(Cond, Values);
00484 
00485     // Return true to indicate that the condition is true if the CompVal is
00486     // equal to one of the constants.
00487     return true;
00488   } else if (Cond->getOpcode() == Instruction::And) {
00489     CompVal = GatherConstantSetNEs(Cond, Values);
00490 
00491     // Return false to indicate that the condition is false if the CompVal is
00492     // equal to one of the constants.
00493     return false;
00494   }
00495   return false;
00496 }
00497 
00498 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
00499   Instruction* Cond = 0;
00500   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00501     Cond = dyn_cast<Instruction>(SI->getCondition());
00502   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00503     if (BI->isConditional())
00504       Cond = dyn_cast<Instruction>(BI->getCondition());
00505   }
00506 
00507   TI->eraseFromParent();
00508   if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
00509 }
00510 
00511 /// isValueEqualityComparison - Return true if the specified terminator checks
00512 /// to see if a value is equal to constant integer value.
00513 static Value *isValueEqualityComparison(TerminatorInst *TI) {
00514   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00515     // Do not permit merging of large switch instructions into their
00516     // predecessors unless there is only one predecessor.
00517     if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
00518                                                pred_end(SI->getParent())) > 128)
00519       return 0;
00520 
00521     return SI->getCondition();
00522   }
00523   if (BranchInst *BI = dyn_cast<BranchInst>(TI))
00524     if (BI->isConditional() && BI->getCondition()->hasOneUse())
00525       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
00526         if ((ICI->getPredicate() == ICmpInst::ICMP_EQ ||
00527              ICI->getPredicate() == ICmpInst::ICMP_NE) &&
00528             isa<ConstantInt>(ICI->getOperand(1)))
00529           return ICI->getOperand(0);
00530   return 0;
00531 }
00532 
00533 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
00534 /// decode all of the 'cases' that it represents and return the 'default' block.
00535 static BasicBlock *
00536 GetValueEqualityComparisonCases(TerminatorInst *TI,
00537                                 std::vector<std::pair<ConstantInt*,
00538                                                       BasicBlock*> > &Cases) {
00539   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00540     Cases.reserve(SI->getNumCases());
00541     for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
00542       Cases.push_back(std::make_pair(SI->getCaseValue(i), SI->getSuccessor(i)));
00543     return SI->getDefaultDest();
00544   }
00545 
00546   BranchInst *BI = cast<BranchInst>(TI);
00547   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
00548   Cases.push_back(std::make_pair(cast<ConstantInt>(ICI->getOperand(1)),
00549                                  BI->getSuccessor(ICI->getPredicate() ==
00550                                                   ICmpInst::ICMP_NE)));
00551   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
00552 }
00553 
00554 
00555 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
00556 /// in the list that match the specified block.
00557 static void EliminateBlockCases(BasicBlock *BB,
00558                std::vector<std::pair<ConstantInt*, BasicBlock*> > &Cases) {
00559   for (unsigned i = 0, e = Cases.size(); i != e; ++i)
00560     if (Cases[i].second == BB) {
00561       Cases.erase(Cases.begin()+i);
00562       --i; --e;
00563     }
00564 }
00565 
00566 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
00567 /// well.
00568 static bool
00569 ValuesOverlap(std::vector<std::pair<ConstantInt*, BasicBlock*> > &C1,
00570               std::vector<std::pair<ConstantInt*, BasicBlock*> > &C2) {
00571   std::vector<std::pair<ConstantInt*, BasicBlock*> > *V1 = &C1, *V2 = &C2;
00572 
00573   // Make V1 be smaller than V2.
00574   if (V1->size() > V2->size())
00575     std::swap(V1, V2);
00576 
00577   if (V1->size() == 0) return false;
00578   if (V1->size() == 1) {
00579     // Just scan V2.
00580     ConstantInt *TheVal = (*V1)[0].first;
00581     for (unsigned i = 0, e = V2->size(); i != e; ++i)
00582       if (TheVal == (*V2)[i].first)
00583         return true;
00584   }
00585 
00586   // Otherwise, just sort both lists and compare element by element.
00587   std::sort(V1->begin(), V1->end());
00588   std::sort(V2->begin(), V2->end());
00589   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
00590   while (i1 != e1 && i2 != e2) {
00591     if ((*V1)[i1].first == (*V2)[i2].first)
00592       return true;
00593     if ((*V1)[i1].first < (*V2)[i2].first)
00594       ++i1;
00595     else
00596       ++i2;
00597   }
00598   return false;
00599 }
00600 
00601 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
00602 /// terminator instruction and its block is known to only have a single
00603 /// predecessor block, check to see if that predecessor is also a value
00604 /// comparison with the same value, and if that comparison determines the
00605 /// outcome of this comparison.  If so, simplify TI.  This does a very limited
00606 /// form of jump threading.
00607 static bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
00608                                                           BasicBlock *Pred) {
00609   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
00610   if (!PredVal) return false;  // Not a value comparison in predecessor.
00611 
00612   Value *ThisVal = isValueEqualityComparison(TI);
00613   assert(ThisVal && "This isn't a value comparison!!");
00614   if (ThisVal != PredVal) return false;  // Different predicates.
00615 
00616   // Find out information about when control will move from Pred to TI's block.
00617   std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
00618   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
00619                                                         PredCases);
00620   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
00621 
00622   // Find information about how control leaves this block.
00623   std::vector<std::pair<ConstantInt*, BasicBlock*> > ThisCases;
00624   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
00625   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
00626 
00627   // If TI's block is the default block from Pred's comparison, potentially
00628   // simplify TI based on this knowledge.
00629   if (PredDef == TI->getParent()) {
00630     // If we are here, we know that the value is none of those cases listed in
00631     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
00632     // can simplify TI.
00633     if (ValuesOverlap(PredCases, ThisCases)) {
00634       if (isa<BranchInst>(TI)) {
00635         // Okay, one of the successors of this condbr is dead.  Convert it to a
00636         // uncond br.
00637         assert(ThisCases.size() == 1 && "Branch can only have one case!");
00638         // Insert the new branch.
00639         Instruction *NI = BranchInst::Create(ThisDef, TI);
00640 
00641         // Remove PHI node entries for the dead edge.
00642         ThisCases[0].second->removePredecessor(TI->getParent());
00643 
00644         DOUT << "Threading pred instr: " << *Pred->getTerminator()
00645              << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
00646 
00647         EraseTerminatorInstAndDCECond(TI);
00648         return true;
00649 
00650       } else {
00651         SwitchInst *SI = cast<SwitchInst>(TI);
00652         // Okay, TI has cases that are statically dead, prune them away.
00653         SmallPtrSet<Constant*, 16> DeadCases;
00654         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00655           DeadCases.insert(PredCases[i].first);
00656 
00657         DOUT << "Threading pred instr: " << *Pred->getTerminator()
00658              << "Through successor TI: " << *TI;
00659 
00660         for (unsigned i = SI->getNumCases()-1; i != 0; --i)
00661           if (DeadCases.count(SI->getCaseValue(i))) {
00662             SI->getSuccessor(i)->removePredecessor(TI->getParent());
00663             SI->removeCase(i);
00664           }
00665 
00666         DOUT << "Leaving: " << *TI << "\n";
00667         return true;
00668       }
00669     }
00670 
00671   } else {
00672     // Otherwise, TI's block must correspond to some matched value.  Find out
00673     // which value (or set of values) this is.
00674     ConstantInt *TIV = 0;
00675     BasicBlock *TIBB = TI->getParent();
00676     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00677       if (PredCases[i].second == TIBB) {
00678         if (TIV == 0)
00679           TIV = PredCases[i].first;
00680         else
00681           return false;  // Cannot handle multiple values coming to this block.
00682       }
00683     assert(TIV && "No edge from pred to succ?");
00684 
00685     // Okay, we found the one constant that our value can be if we get into TI's
00686     // BB.  Find out which successor will unconditionally be branched to.
00687     BasicBlock *TheRealDest = 0;
00688     for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
00689       if (ThisCases[i].first == TIV) {
00690         TheRealDest = ThisCases[i].second;
00691         break;
00692       }
00693 
00694     // If not handled by any explicit cases, it is handled by the default case.
00695     if (TheRealDest == 0) TheRealDest = ThisDef;
00696 
00697     // Remove PHI node entries for dead edges.
00698     BasicBlock *CheckEdge = TheRealDest;
00699     for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
00700       if (*SI != CheckEdge)
00701         (*SI)->removePredecessor(TIBB);
00702       else
00703         CheckEdge = 0;
00704 
00705     // Insert the new branch.
00706     Instruction *NI = BranchInst::Create(TheRealDest, TI);
00707 
00708     DOUT << "Threading pred instr: " << *Pred->getTerminator()
00709          << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
00710 
00711     EraseTerminatorInstAndDCECond(TI);
00712     return true;
00713   }
00714   return false;
00715 }
00716 
00717 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
00718 /// equality comparison instruction (either a switch or a branch on "X == c").
00719 /// See if any of the predecessors of the terminator block are value comparisons
00720 /// on the same value.  If so, and if safe to do so, fold them together.
00721 static bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI) {
00722   BasicBlock *BB = TI->getParent();
00723   Value *CV = isValueEqualityComparison(TI);  // CondVal
00724   assert(CV && "Not a comparison?");
00725   bool Changed = false;
00726 
00727   SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
00728   while (!Preds.empty()) {
00729     BasicBlock *Pred = Preds.back();
00730     Preds.pop_back();
00731 
00732     // See if the predecessor is a comparison with the same value.
00733     TerminatorInst *PTI = Pred->getTerminator();
00734     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
00735 
00736     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
00737       // Figure out which 'cases' to copy from SI to PSI.
00738       std::vector<std::pair<ConstantInt*, BasicBlock*> > BBCases;
00739       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
00740 
00741       std::vector<std::pair<ConstantInt*, BasicBlock*> > PredCases;
00742       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
00743 
00744       // Based on whether the default edge from PTI goes to BB or not, fill in
00745       // PredCases and PredDefault with the new switch cases we would like to
00746       // build.
00747       SmallVector<BasicBlock*, 8> NewSuccessors;
00748 
00749       if (PredDefault == BB) {
00750         // If this is the default destination from PTI, only the edges in TI
00751         // that don't occur in PTI, or that branch to BB will be activated.
00752         std::set<ConstantInt*> PTIHandled;
00753         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00754           if (PredCases[i].second != BB)
00755             PTIHandled.insert(PredCases[i].first);
00756           else {
00757             // The default destination is BB, we don't need explicit targets.
00758             std::swap(PredCases[i], PredCases.back());
00759             PredCases.pop_back();
00760             --i; --e;
00761           }
00762 
00763         // Reconstruct the new switch statement we will be building.
00764         if (PredDefault != BBDefault) {
00765           PredDefault->removePredecessor(Pred);
00766           PredDefault = BBDefault;
00767           NewSuccessors.push_back(BBDefault);
00768         }
00769         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00770           if (!PTIHandled.count(BBCases[i].first) &&
00771               BBCases[i].second != BBDefault) {
00772             PredCases.push_back(BBCases[i]);
00773             NewSuccessors.push_back(BBCases[i].second);
00774           }
00775 
00776       } else {
00777         // If this is not the default destination from PSI, only the edges
00778         // in SI that occur in PSI with a destination of BB will be
00779         // activated.
00780         std::set<ConstantInt*> PTIHandled;
00781         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00782           if (PredCases[i].second == BB) {
00783             PTIHandled.insert(PredCases[i].first);
00784             std::swap(PredCases[i], PredCases.back());
00785             PredCases.pop_back();
00786             --i; --e;
00787           }
00788 
00789         // Okay, now we know which constants were sent to BB from the
00790         // predecessor.  Figure out where they will all go now.
00791         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00792           if (PTIHandled.count(BBCases[i].first)) {
00793             // If this is one we are capable of getting...
00794             PredCases.push_back(BBCases[i]);
00795             NewSuccessors.push_back(BBCases[i].second);
00796             PTIHandled.erase(BBCases[i].first);// This constant is taken care of
00797           }
00798 
00799         // If there are any constants vectored to BB that TI doesn't handle,
00800         // they must go to the default destination of TI.
00801         for (std::set<ConstantInt*>::iterator I = PTIHandled.begin(),
00802                E = PTIHandled.end(); I != E; ++I) {
00803           PredCases.push_back(std::make_pair(*I, BBDefault));
00804           NewSuccessors.push_back(BBDefault);
00805         }
00806       }
00807 
00808       // Okay, at this point, we know which new successor Pred will get.  Make
00809       // sure we update the number of entries in the PHI nodes for these
00810       // successors.
00811       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
00812         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
00813 
00814       // Now that the successors are updated, create the new Switch instruction.
00815       SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault,
00816                                              PredCases.size(), PTI);
00817       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00818         NewSI->addCase(PredCases[i].first, PredCases[i].second);
00819 
00820       EraseTerminatorInstAndDCECond(PTI);
00821 
00822       // Okay, last check.  If BB is still a successor of PSI, then we must
00823       // have an infinite loop case.  If so, add an infinitely looping block
00824       // to handle the case to preserve the behavior of the code.
00825       BasicBlock *InfLoopBlock = 0;
00826       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
00827         if (NewSI->getSuccessor(i) == BB) {
00828           if (InfLoopBlock == 0) {
00829             // Insert it at the end of the function, because it's either code,
00830             // or it won't matter if it's hot. :)
00831             InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
00832             BranchInst::Create(InfLoopBlock, InfLoopBlock);
00833           }
00834           NewSI->setSuccessor(i, InfLoopBlock);
00835         }
00836 
00837       Changed = true;
00838     }
00839   }
00840   return Changed;
00841 }
00842 
00843 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
00844 /// BB2, hoist any common code in the two blocks up into the branch block.  The
00845 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
00846 static bool HoistThenElseCodeToIf(BranchInst *BI) {
00847   // This does very trivial matching, with limited scanning, to find identical
00848   // instructions in the two blocks.  In particular, we don't want to get into
00849   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
00850   // such, we currently just scan for obviously identical instructions in an
00851   // identical order.
00852   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
00853   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
00854 
00855   Instruction *I1 = BB1->begin(), *I2 = BB2->begin();
00856   if (I1->getOpcode() != I2->getOpcode() || isa<PHINode>(I1) || 
00857       isa<InvokeInst>(I1) || !I1->isIdenticalTo(I2))
00858     return false;
00859 
00860   // If we get here, we can hoist at least one instruction.
00861   BasicBlock *BIParent = BI->getParent();
00862 
00863   do {
00864     // If we are hoisting the terminator instruction, don't move one (making a
00865     // broken BB), instead clone it, and remove BI.
00866     if (isa<TerminatorInst>(I1))
00867       goto HoistTerminator;
00868 
00869     // For a normal instruction, we just move one to right before the branch,
00870     // then replace all uses of the other with the first.  Finally, we remove
00871     // the now redundant second instruction.
00872     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
00873     if (!I2->use_empty())
00874       I2->replaceAllUsesWith(I1);
00875     BB2->getInstList().erase(I2);
00876 
00877     I1 = BB1->begin();
00878     I2 = BB2->begin();
00879   } while (I1->getOpcode() == I2->getOpcode() && I1->isIdenticalTo(I2));
00880 
00881   return true;
00882 
00883 HoistTerminator:
00884   // Okay, it is safe to hoist the terminator.
00885   Instruction *NT = I1->clone();
00886   BIParent->getInstList().insert(BI, NT);
00887   if (NT->getType() != Type::VoidTy) {
00888     I1->replaceAllUsesWith(NT);
00889     I2->replaceAllUsesWith(NT);
00890     NT->takeName(I1);
00891   }
00892 
00893   // Hoisting one of the terminators from our successor is a great thing.
00894   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
00895   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
00896   // nodes, so we insert select instruction to compute the final result.
00897   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
00898   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
00899     PHINode *PN;
00900     for (BasicBlock::iterator BBI = SI->begin();
00901          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00902       Value *BB1V = PN->getIncomingValueForBlock(BB1);
00903       Value *BB2V = PN->getIncomingValueForBlock(BB2);
00904       if (BB1V != BB2V) {
00905         // These values do not agree.  Insert a select instruction before NT
00906         // that determines the right value.
00907         SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
00908         if (SI == 0)
00909           SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
00910                                   BB1V->getName()+"."+BB2V->getName(), NT);
00911         // Make the PHI node use the select for all incoming values for BB1/BB2
00912         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00913           if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
00914             PN->setIncomingValue(i, SI);
00915       }
00916     }
00917   }
00918 
00919   // Update any PHI nodes in our new successors.
00920   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
00921     AddPredecessorToBlock(*SI, BIParent, BB1);
00922 
00923   EraseTerminatorInstAndDCECond(BI);
00924   return true;
00925 }
00926 
00927 /// SpeculativelyExecuteBB - Given a conditional branch that goes to BB1
00928 /// and an BB2 and the only successor of BB1 is BB2, hoist simple code
00929 /// (for now, restricted to a single instruction that's side effect free) from
00930 /// the BB1 into the branch block to speculatively execute it.
00931 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *BB1) {
00932   // Only speculatively execution a single instruction (not counting the
00933   // terminator) for now.
00934   BasicBlock::iterator BBI = BB1->begin();
00935   ++BBI; // must have at least a terminator
00936   if (BBI == BB1->end()) return false; // only one inst
00937   ++BBI;
00938   if (BBI != BB1->end()) return false; // more than 2 insts.
00939 
00940   // Be conservative for now. FP select instruction can often be expensive.
00941   Value *BrCond = BI->getCondition();
00942   if (isa<Instruction>(BrCond) &&
00943       cast<Instruction>(BrCond)->getOpcode() == Instruction::FCmp)
00944     return false;
00945 
00946   // If BB1 is actually on the false edge of the conditional branch, remember
00947   // to swap the select operands later.
00948   bool Invert = false;
00949   if (BB1 != BI->getSuccessor(0)) {
00950     assert(BB1 == BI->getSuccessor(1) && "No edge from 'if' block?");
00951     Invert = true;
00952   }
00953 
00954   // Turn
00955   // BB:
00956   //     %t1 = icmp
00957   //     br i1 %t1, label %BB1, label %BB2
00958   // BB1:
00959   //     %t3 = add %t2, c
00960   //     br label BB2
00961   // BB2:
00962   // =>
00963   // BB:
00964   //     %t1 = icmp
00965   //     %t4 = add %t2, c
00966   //     %t3 = select i1 %t1, %t2, %t3
00967   Instruction *I = BB1->begin();
00968   switch (I->getOpcode()) {
00969   default: return false;  // Not safe / profitable to hoist.
00970   case Instruction::Add:
00971   case Instruction::Sub:
00972     // FP arithmetic might trap. Not worth doing for vector ops.
00973     if (I->getType()->isFloatingPoint() || isa<VectorType>(I->getType()))
00974       return false;
00975     break;
00976   case Instruction::And:
00977   case Instruction::Or:
00978   case Instruction::Xor:
00979   case Instruction::Shl:
00980   case Instruction::LShr:
00981   case Instruction::AShr:
00982     // Don't mess with vector operations.
00983     if (isa<VectorType>(I->getType()))
00984       return false;
00985     break;   // These are all cheap and non-trapping instructions.
00986   }
00987   
00988   // If the instruction is obviously dead, don't try to predicate it.
00989   if (I->use_empty()) {
00990     I->eraseFromParent();
00991     return true;
00992   }
00993 
00994   // Can we speculatively execute the instruction? And what is the value 
00995   // if the condition is false? Consider the phi uses, if the incoming value
00996   // from the "if" block are all the same V, then V is the value of the
00997   // select if the condition is false.
00998   BasicBlock *BIParent = BI->getParent();
00999   SmallVector<PHINode*, 4> PHIUses;
01000   Value *FalseV = NULL;
01001   
01002   BasicBlock *BB2 = BB1->getTerminator()->getSuccessor(0);
01003   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
01004        UI != E; ++UI) {
01005     // Ignore any user that is not a PHI node in BB2.  These can only occur in
01006     // unreachable blocks, because they would not be dominated by the instr.
01007     PHINode *PN = dyn_cast<PHINode>(UI);
01008     if (!PN || PN->getParent() != BB2)
01009       return false;
01010     PHIUses.push_back(PN);
01011     
01012     Value *PHIV = PN->getIncomingValueForBlock(BIParent);
01013     if (!FalseV)
01014       FalseV = PHIV;
01015     else if (FalseV != PHIV)
01016       return false;  // Inconsistent value when condition is false.
01017   }
01018   
01019   assert(FalseV && "Must have at least one user, and it must be a PHI");
01020 
01021   // Do not hoist the instruction if any of its operands are defined but not
01022   // used in this BB. The transformation will prevent the operand from
01023   // being sunk into the use block.
01024   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
01025     Instruction *OpI = dyn_cast<Instruction>(*i);
01026     if (OpI && OpI->getParent() == BIParent &&
01027         !OpI->isUsedInBasicBlock(BIParent))
01028       return false;
01029   }
01030 
01031   // If we get here, we can hoist the instruction. Try to place it
01032   // before the icmp instruction preceeding the conditional branch.
01033   BasicBlock::iterator InsertPos = BI;
01034   if (InsertPos != BIParent->begin()) 
01035     --InsertPos;
01036   if (InsertPos == BrCond && !isa<PHINode>(BrCond)) {
01037     SmallPtrSet<Instruction *, 4> BB1Insns;
01038     for(BasicBlock::iterator BB1I = BB1->begin(), BB1E = BB1->end(); 
01039         BB1I != BB1E; ++BB1I) 
01040       BB1Insns.insert(BB1I);
01041     for(Value::use_iterator UI = BrCond->use_begin(), UE = BrCond->use_end();
01042         UI != UE; ++UI) {
01043       Instruction *Use = cast<Instruction>(*UI);
01044       if (BB1Insns.count(Use)) {
01045         // If BrCond uses the instruction that place it just before
01046         // branch instruction.
01047         InsertPos = BI;
01048         break;
01049       }
01050     }
01051   } else
01052     InsertPos = BI;
01053   BIParent->getInstList().splice(InsertPos, BB1->getInstList(), I);
01054 
01055   // Create a select whose true value is the speculatively executed value and
01056   // false value is the previously determined FalseV.
01057   SelectInst *SI;
01058   if (Invert)
01059     SI = SelectInst::Create(BrCond, FalseV, I,
01060                             FalseV->getName() + "." + I->getName(), BI);
01061   else
01062     SI = SelectInst::Create(BrCond, I, FalseV,
01063                             I->getName() + "." + FalseV->getName(), BI);
01064 
01065   // Make the PHI node use the select for all incoming values for "then" and
01066   // "if" blocks.
01067   for (unsigned i = 0, e = PHIUses.size(); i != e; ++i) {
01068     PHINode *PN = PHIUses[i];
01069     for (unsigned j = 0, ee = PN->getNumIncomingValues(); j != ee; ++j)
01070       if (PN->getIncomingBlock(j) == BB1 ||
01071           PN->getIncomingBlock(j) == BIParent)
01072         PN->setIncomingValue(j, SI);
01073   }
01074 
01075   ++NumSpeculations;
01076   return true;
01077 }
01078 
01079 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
01080 /// across this block.
01081 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
01082   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
01083   unsigned Size = 0;
01084   
01085   // If this basic block contains anything other than a PHI (which controls the
01086   // branch) and branch itself, bail out.  FIXME: improve this in the future.
01087   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI, ++Size) {
01088     if (Size > 10) return false;  // Don't clone large BB's.
01089     
01090     // We can only support instructions that are do not define values that are
01091     // live outside of the current basic block.
01092     for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
01093          UI != E; ++UI) {
01094       Instruction *U = cast<Instruction>(*UI);
01095       if (U->getParent() != BB || isa<PHINode>(U)) return false;
01096     }
01097     
01098     // Looks ok, continue checking.
01099   }
01100 
01101   return true;
01102 }
01103 
01104 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
01105 /// that is defined in the same block as the branch and if any PHI entries are
01106 /// constants, thread edges corresponding to that entry to be branches to their
01107 /// ultimate destination.
01108 static bool FoldCondBranchOnPHI(BranchInst *BI) {
01109   BasicBlock *BB = BI->getParent();
01110   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
01111   // NOTE: we currently cannot transform this case if the PHI node is used
01112   // outside of the block.
01113   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
01114     return false;
01115   
01116   // Degenerate case of a single entry PHI.
01117   if (PN->getNumIncomingValues() == 1) {
01118     FoldSingleEntryPHINodes(PN->getParent());
01119     return true;    
01120   }
01121 
01122   // Now we know that this block has multiple preds and two succs.
01123   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
01124   
01125   // Okay, this is a simple enough basic block.  See if any phi values are
01126   // constants.
01127   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01128     ConstantInt *CB;
01129     if ((CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i))) &&
01130         CB->getType() == Type::Int1Ty) {
01131       // Okay, we now know that all edges from PredBB should be revectored to
01132       // branch to RealDest.
01133       BasicBlock *PredBB = PN->getIncomingBlock(i);
01134       BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
01135       
01136       if (RealDest == BB) continue;  // Skip self loops.
01137       
01138       // The dest block might have PHI nodes, other predecessors and other
01139       // difficult cases.  Instead of being smart about this, just insert a new
01140       // block that jumps to the destination block, effectively splitting
01141       // the edge we are about to create.
01142       BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
01143                                               RealDest->getParent(), RealDest);
01144       BranchInst::Create(RealDest, EdgeBB);
01145       PHINode *PN;
01146       for (BasicBlock::iterator BBI = RealDest->begin();
01147            (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
01148         Value *V = PN->getIncomingValueForBlock(BB);
01149         PN->addIncoming(V, EdgeBB);
01150       }
01151 
01152       // BB may have instructions that are being threaded over.  Clone these
01153       // instructions into EdgeBB.  We know that there will be no uses of the
01154       // cloned instructions outside of EdgeBB.
01155       BasicBlock::iterator InsertPt = EdgeBB->begin();
01156       std::map<Value*, Value*> TranslateMap;  // Track translated values.
01157       for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
01158         if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
01159           TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
01160         } else {
01161           // Clone the instruction.
01162           Instruction *N = BBI->clone();
01163           if (BBI->hasName()) N->setName(BBI->getName()+".c");
01164           
01165           // Update operands due to translation.
01166           for (User::op_iterator i = N->op_begin(), e = N->op_end();
01167                i != e; ++i) {
01168             std::map<Value*, Value*>::iterator PI =
01169               TranslateMap.find(*i);
01170             if (PI != TranslateMap.end())
01171               *i = PI->second;
01172           }
01173           
01174           // Check for trivial simplification.
01175           if (Constant *C = ConstantFoldInstruction(N)) {
01176             TranslateMap[BBI] = C;
01177             delete N;   // Constant folded away, don't need actual inst
01178           } else {
01179             // Insert the new instruction into its new home.
01180             EdgeBB->getInstList().insert(InsertPt, N);
01181             if (!BBI->use_empty())
01182               TranslateMap[BBI] = N;
01183           }
01184         }
01185       }
01186 
01187       // Loop over all of the edges from PredBB to BB, changing them to branch
01188       // to EdgeBB instead.
01189       TerminatorInst *PredBBTI = PredBB->getTerminator();
01190       for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
01191         if (PredBBTI->getSuccessor(i) == BB) {
01192           BB->removePredecessor(PredBB);
01193           PredBBTI->setSuccessor(i, EdgeBB);
01194         }
01195       
01196       // Recurse, simplifying any other constants.
01197       return FoldCondBranchOnPHI(BI) | true;
01198     }
01199   }
01200 
01201   return false;
01202 }
01203 
01204 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
01205 /// PHI node, see if we can eliminate it.
01206 static bool FoldTwoEntryPHINode(PHINode *PN) {
01207   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
01208   // statement", which has a very simple dominance structure.  Basically, we
01209   // are trying to find the condition that is being branched on, which
01210   // subsequently causes this merge to happen.  We really want control
01211   // dependence information for this check, but simplifycfg can't keep it up
01212   // to date, and this catches most of the cases we care about anyway.
01213   //
01214   BasicBlock *BB = PN->getParent();
01215   BasicBlock *IfTrue, *IfFalse;
01216   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
01217   if (!IfCond) return false;
01218   
01219   // Okay, we found that we can merge this two-entry phi node into a select.
01220   // Doing so would require us to fold *all* two entry phi nodes in this block.
01221   // At some point this becomes non-profitable (particularly if the target
01222   // doesn't support cmov's).  Only do this transformation if there are two or
01223   // fewer PHI nodes in this block.
01224   unsigned NumPhis = 0;
01225   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
01226     if (NumPhis > 2)
01227       return false;
01228   
01229   DOUT << "FOUND IF CONDITION!  " << *IfCond << "  T: "
01230        << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n";
01231   
01232   // Loop over the PHI's seeing if we can promote them all to select
01233   // instructions.  While we are at it, keep track of the instructions
01234   // that need to be moved to the dominating block.
01235   std::set<Instruction*> AggressiveInsts;
01236   
01237   BasicBlock::iterator AfterPHIIt = BB->begin();
01238   while (isa<PHINode>(AfterPHIIt)) {
01239     PHINode *PN = cast<PHINode>(AfterPHIIt++);
01240     if (PN->getIncomingValue(0) == PN->getIncomingValue(1)) {
01241       if (PN->getIncomingValue(0) != PN)
01242         PN->replaceAllUsesWith(PN->getIncomingValue(0));
01243       else
01244         PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
01245     } else if (!DominatesMergePoint(PN->getIncomingValue(0), BB,
01246                                     &AggressiveInsts) ||
01247                !DominatesMergePoint(PN->getIncomingValue(1), BB,
01248                                     &AggressiveInsts)) {
01249       return false;
01250     }
01251   }
01252   
01253   // If we all PHI nodes are promotable, check to make sure that all
01254   // instructions in the predecessor blocks can be promoted as well.  If
01255   // not, we won't be able to get rid of the control flow, so it's not
01256   // worth promoting to select instructions.
01257   BasicBlock *DomBlock = 0, *IfBlock1 = 0, *IfBlock2 = 0;
01258   PN = cast<PHINode>(BB->begin());
01259   BasicBlock *Pred = PN->getIncomingBlock(0);
01260   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
01261     IfBlock1 = Pred;
01262     DomBlock = *pred_begin(Pred);
01263     for (BasicBlock::iterator I = Pred->begin();
01264          !isa<TerminatorInst>(I); ++I)
01265       if (!AggressiveInsts.count(I)) {
01266         // This is not an aggressive instruction that we can promote.
01267         // Because of this, we won't be able to get rid of the control
01268         // flow, so the xform is not worth it.
01269         return false;
01270       }
01271   }
01272     
01273   Pred = PN->getIncomingBlock(1);
01274   if (cast<BranchInst>(Pred->getTerminator())->isUnconditional()) {
01275     IfBlock2 = Pred;
01276     DomBlock = *pred_begin(Pred);
01277     for (BasicBlock::iterator I = Pred->begin();
01278          !isa<TerminatorInst>(I); ++I)
01279       if (!AggressiveInsts.count(I)) {
01280         // This is not an aggressive instruction that we can promote.
01281         // Because of this, we won't be able to get rid of the control
01282         // flow, so the xform is not worth it.
01283         return false;
01284       }
01285   }
01286       
01287   // If we can still promote the PHI nodes after this gauntlet of tests,
01288   // do all of the PHI's now.
01289 
01290   // Move all 'aggressive' instructions, which are defined in the
01291   // conditional parts of the if's up to the dominating block.
01292   if (IfBlock1) {
01293     DomBlock->getInstList().splice(DomBlock->getTerminator(),
01294                                    IfBlock1->getInstList(),
01295                                    IfBlock1->begin(),
01296                                    IfBlock1->getTerminator());
01297   }
01298   if (IfBlock2) {
01299     DomBlock->getInstList().splice(DomBlock->getTerminator(),
01300                                    IfBlock2->getInstList(),
01301                                    IfBlock2->begin(),
01302                                    IfBlock2->getTerminator());
01303   }
01304   
01305   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
01306     // Change the PHI node into a select instruction.
01307     Value *TrueVal =
01308       PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
01309     Value *FalseVal =
01310       PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
01311     
01312     Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
01313     PN->replaceAllUsesWith(NV);
01314     NV->takeName(PN);
01315     
01316     BB->getInstList().erase(PN);
01317   }
01318   return true;
01319 }
01320 
01321 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
01322 /// to two returning blocks, try to merge them together into one return,
01323 /// introducing a select if the return values disagree.
01324 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
01325   assert(BI->isConditional() && "Must be a conditional branch");
01326   BasicBlock *TrueSucc = BI->getSuccessor(0);
01327   BasicBlock *FalseSucc = BI->getSuccessor(1);
01328   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
01329   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
01330   
01331   // Check to ensure both blocks are empty (just a return) or optionally empty
01332   // with PHI nodes.  If there are other instructions, merging would cause extra
01333   // computation on one path or the other.
01334   BasicBlock::iterator BBI = TrueRet;
01335   if (BBI != TrueSucc->begin() && !isa<PHINode>(--BBI))
01336     return false;  // Not empty with optional phi nodes.
01337   BBI = FalseRet;
01338   if (BBI != FalseSucc->begin() && !isa<PHINode>(--BBI))
01339     return false;  // Not empty with optional phi nodes.
01340 
01341   // Okay, we found a branch that is going to two return nodes.  If
01342   // there is no return value for this function, just change the
01343   // branch into a return.
01344   if (FalseRet->getNumOperands() == 0) {
01345     TrueSucc->removePredecessor(BI->getParent());
01346     FalseSucc->removePredecessor(BI->getParent());
01347     ReturnInst::Create(0, BI);
01348     EraseTerminatorInstAndDCECond(BI);
01349     return true;
01350   }
01351     
01352   // Otherwise, figure out what the true and false return values are
01353   // so we can insert a new select instruction.
01354   Value *TrueValue = TrueRet->getReturnValue();
01355   Value *FalseValue = FalseRet->getReturnValue();
01356   
01357   // Unwrap any PHI nodes in the return blocks.
01358   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
01359     if (TVPN->getParent() == TrueSucc)
01360       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
01361   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
01362     if (FVPN->getParent() == FalseSucc)
01363       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
01364   
01365   // In order for this transformation to be safe, we must be able to
01366   // unconditionally execute both operands to the return.  This is
01367   // normally the case, but we could have a potentially-trapping
01368   // constant expression that prevents this transformation from being
01369   // safe.
01370   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
01371     if (TCV->canTrap())
01372       return false;
01373   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
01374     if (FCV->canTrap())
01375       return false;
01376   
01377   // Okay, we collected all the mapped values and checked them for sanity, and
01378   // defined to really do this transformation.  First, update the CFG.
01379   TrueSucc->removePredecessor(BI->getParent());
01380   FalseSucc->removePredecessor(BI->getParent());
01381   
01382   // Insert select instructions where needed.
01383   Value *BrCond = BI->getCondition();
01384   if (TrueValue) {
01385     // Insert a select if the results differ.
01386     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
01387     } else if (isa<UndefValue>(TrueValue)) {
01388       TrueValue = FalseValue;
01389     } else {
01390       TrueValue = SelectInst::Create(BrCond, TrueValue,
01391                                      FalseValue, "retval", BI);
01392     }
01393   }
01394 
01395   Value *RI = !TrueValue ?
01396               ReturnInst::Create(BI) :
01397               ReturnInst::Create(TrueValue, BI);
01398       
01399   DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
01400        << "\n  " << *BI << "NewRet = " << *RI
01401        << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
01402       
01403   EraseTerminatorInstAndDCECond(BI);
01404 
01405   return true;
01406 }
01407 
01408 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
01409 /// and if a predecessor branches to us and one of our successors, fold the
01410 /// setcc into the predecessor and use logical operations to pick the right
01411 /// destination.
01412 static bool FoldBranchToCommonDest(BranchInst *BI) {
01413   BasicBlock *BB = BI->getParent();
01414   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
01415   if (Cond == 0) return false;
01416 
01417   
01418   // Only allow this if the condition is a simple instruction that can be
01419   // executed unconditionally.  It must be in the same block as the branch, and
01420   // must be at the front of the block.
01421   if ((!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
01422       Cond->getParent() != BB || &BB->front() != Cond || !Cond->hasOneUse())
01423     return false;
01424   
01425   // Make sure the instruction after the condition is the cond branch.
01426   BasicBlock::iterator CondIt = Cond; ++CondIt;
01427   if (&*CondIt != BI)
01428     return false;
01429 
01430   // Cond is known to be a compare or binary operator.  Check to make sure that
01431   // neither operand is a potentially-trapping constant expression.
01432   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
01433     if (CE->canTrap())
01434       return false;
01435   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
01436     if (CE->canTrap())
01437       return false;
01438   
01439   
01440   // Finally, don't infinitely unroll conditional loops.
01441   BasicBlock *TrueDest  = BI->getSuccessor(0);
01442   BasicBlock *FalseDest = BI->getSuccessor(1);
01443   if (TrueDest == BB || FalseDest == BB)
01444     return false;
01445   
01446   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
01447     BasicBlock *PredBlock = *PI;
01448     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
01449     
01450     // Check that we have two conditional branches.  If there is a PHI node in
01451     // the common successor, verify that the same value flows in from both
01452     // blocks.
01453     if (PBI == 0 || PBI->isUnconditional() ||
01454         !SafeToMergeTerminators(BI, PBI))
01455       continue;
01456     
01457     Instruction::BinaryOps Opc;
01458     bool InvertPredCond = false;
01459 
01460     if (PBI->getSuccessor(0) == TrueDest)
01461       Opc = Instruction::Or;
01462     else if (PBI->getSuccessor(1) == FalseDest)
01463       Opc = Instruction::And;
01464     else if (PBI->getSuccessor(0) == FalseDest)
01465       Opc = Instruction::And, InvertPredCond = true;
01466     else if (PBI->getSuccessor(1) == TrueDest)
01467       Opc = Instruction::Or, InvertPredCond = true;
01468     else
01469       continue;
01470 
01471     DOUT << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB;
01472     
01473     // If we need to invert the condition in the pred block to match, do so now.
01474     if (InvertPredCond) {
01475       Value *NewCond =
01476         BinaryOperator::CreateNot(PBI->getCondition(),
01477                                   PBI->getCondition()->getName()+".not", PBI);
01478       PBI->setCondition(NewCond);
01479       BasicBlock *OldTrue = PBI->getSuccessor(0);
01480       BasicBlock *OldFalse = PBI->getSuccessor(1);
01481       PBI->setSuccessor(0, OldFalse);
01482       PBI->setSuccessor(1, OldTrue);
01483     }
01484     
01485     // Clone Cond into the predecessor basic block, and or/and the
01486     // two conditions together.
01487     Instruction *New = Cond->clone();
01488     PredBlock->getInstList().insert(PBI, New);
01489     New->takeName(Cond);
01490     Cond->setName(New->getName()+".old");
01491     
01492     Value *NewCond = BinaryOperator::Create(Opc, PBI->getCondition(),
01493                                             New, "or.cond", PBI);
01494     PBI->setCondition(NewCond);
01495     if (PBI->getSuccessor(0) == BB) {
01496       AddPredecessorToBlock(TrueDest, PredBlock, BB);
01497       PBI->setSuccessor(0, TrueDest);
01498     }
01499     if (PBI->getSuccessor(1) == BB) {
01500       AddPredecessorToBlock(FalseDest, PredBlock, BB);
01501       PBI->setSuccessor(1, FalseDest);
01502     }
01503     return true;
01504   }
01505   return false;
01506 }
01507 
01508 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
01509 /// predecessor of another block, this function tries to simplify it.  We know
01510 /// that PBI and BI are both conditional branches, and BI is in one of the
01511 /// successor blocks of PBI - PBI branches to BI.
01512 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
01513   assert(PBI->isConditional() && BI->isConditional());
01514   BasicBlock *BB = BI->getParent();
01515   
01516   // If this block ends with a branch instruction, and if there is a
01517   // predecessor that ends on a branch of the same condition, make 
01518   // this conditional branch redundant.
01519   if (PBI->getCondition() == BI->getCondition() &&
01520       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
01521     // Okay, the outcome of this conditional branch is statically
01522     // knowable.  If this block had a single pred, handle specially.
01523     if (BB->getSinglePredecessor()) {
01524       // Turn this into a branch on constant.
01525       bool CondIsTrue = PBI->getSuccessor(0) == BB;
01526       BI->setCondition(ConstantInt::get(Type::Int1Ty, CondIsTrue));
01527       return true;  // Nuke the branch on constant.
01528     }
01529     
01530     // Otherwise, if there are multiple predecessors, insert a PHI that merges
01531     // in the constant and simplify the block result.  Subsequent passes of
01532     // simplifycfg will thread the block.
01533     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
01534       PHINode *NewPN = PHINode::Create(Type::Int1Ty,
01535                                        BI->getCondition()->getName() + ".pr",
01536                                        BB->begin());
01537       // Okay, we're going to insert the PHI node.  Since PBI is not the only
01538       // predecessor, compute the PHI'd conditional value for all of the preds.
01539       // Any predecessor where the condition is not computable we keep symbolic.
01540       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01541         if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
01542             PBI != BI && PBI->isConditional() &&
01543             PBI->getCondition() == BI->getCondition() &&
01544             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
01545           bool CondIsTrue = PBI->getSuccessor(0) == BB;
01546           NewPN->addIncoming(ConstantInt::get(Type::Int1Ty, 
01547                                               CondIsTrue), *PI);
01548         } else {
01549           NewPN->addIncoming(BI->getCondition(), *PI);
01550         }
01551       
01552       BI->setCondition(NewPN);
01553       return true;
01554     }
01555   }
01556   
01557   // If this is a conditional branch in an empty block, and if any
01558   // predecessors is a conditional branch to one of our destinations,
01559   // fold the conditions into logical ops and one cond br.
01560   if (&BB->front() != BI)
01561     return false;
01562 
01563   
01564   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
01565     if (CE->canTrap())
01566       return false;
01567   
01568   int PBIOp, BIOp;
01569   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
01570     PBIOp = BIOp = 0;
01571   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
01572     PBIOp = 0, BIOp = 1;
01573   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
01574     PBIOp = 1, BIOp = 0;
01575   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
01576     PBIOp = BIOp = 1;
01577   else
01578     return false;
01579     
01580   // Check to make sure that the other destination of this branch
01581   // isn't BB itself.  If so, this is an infinite loop that will
01582   // keep getting unwound.
01583   if (PBI->getSuccessor(PBIOp) == BB)
01584     return false;
01585     
01586   // Do not perform this transformation if it would require 
01587   // insertion of a large number of select instructions. For targets
01588   // without predication/cmovs, this is a big pessimization.
01589   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
01590       
01591   unsigned NumPhis = 0;
01592   for (BasicBlock::iterator II = CommonDest->begin();
01593        isa<PHINode>(II); ++II, ++NumPhis)
01594     if (NumPhis > 2) // Disable this xform.
01595       return false;
01596     
01597   // Finally, if everything is ok, fold the branches to logical ops.
01598   BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
01599   
01600   DOUT << "FOLDING BRs:" << *PBI->getParent()
01601        << "AND: " << *BI->getParent();
01602   
01603   
01604   // If OtherDest *is* BB, then BB is a basic block with a single conditional
01605   // branch in it, where one edge (OtherDest) goes back to itself but the other
01606   // exits.  We don't *know* that the program avoids the infinite loop
01607   // (even though that seems likely).  If we do this xform naively, we'll end up
01608   // recursively unpeeling the loop.  Since we know that (after the xform is
01609   // done) that the block *is* infinite if reached, we just make it an obviously
01610   // infinite loop with no cond branch.
01611   if (OtherDest == BB) {
01612     // Insert it at the end of the function, because it's either code,
01613     // or it won't matter if it's hot. :)
01614     BasicBlock *InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
01615     BranchInst::Create(InfLoopBlock, InfLoopBlock);
01616     OtherDest = InfLoopBlock;
01617   }  
01618   
01619   DOUT << *PBI->getParent()->getParent();
01620   
01621   // BI may have other predecessors.  Because of this, we leave
01622   // it alone, but modify PBI.
01623   
01624   // Make sure we get to CommonDest on True&True directions.
01625   Value *PBICond = PBI->getCondition();
01626   if (PBIOp)
01627     PBICond = BinaryOperator::CreateNot(PBICond,
01628                                         PBICond->getName()+".not",
01629                                         PBI);
01630   Value *BICond = BI->getCondition();
01631   if (BIOp)
01632     BICond = BinaryOperator::CreateNot(BICond,
01633                                        BICond->getName()+".not",
01634                                        PBI);
01635   // Merge the conditions.
01636   Value *Cond = BinaryOperator::CreateOr(PBICond, BICond, "brmerge", PBI);
01637   
01638   // Modify PBI to branch on the new condition to the new dests.
01639   PBI->setCondition(Cond);
01640   PBI->setSuccessor(0, CommonDest);
01641   PBI->setSuccessor(1, OtherDest);
01642   
01643   // OtherDest may have phi nodes.  If so, add an entry from PBI's
01644   // block that are identical to the entries for BI's block.
01645   PHINode *PN;
01646   for (BasicBlock::iterator II = OtherDest->begin();
01647        (PN = dyn_cast<PHINode>(II)); ++II) {
01648     Value *V = PN->getIncomingValueForBlock(BB);
01649     PN->addIncoming(V, PBI->getParent());
01650   }
01651   
01652   // We know that the CommonDest already had an edge from PBI to
01653   // it.  If it has PHIs though, the PHIs may have different
01654   // entries for BB and PBI's BB.  If so, insert a select to make
01655   // them agree.
01656   for (BasicBlock::iterator II = CommonDest->begin();
01657        (PN = dyn_cast<PHINode>(II)); ++II) {
01658     Value *BIV = PN->getIncomingValueForBlock(BB);
01659     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
01660     Value *PBIV = PN->getIncomingValue(PBBIdx);
01661     if (BIV != PBIV) {
01662       // Insert a select in PBI to pick the right value.
01663       Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
01664                                      PBIV->getName()+".mux", PBI);
01665       PN->setIncomingValue(PBBIdx, NV);
01666     }
01667   }
01668   
01669   DOUT << "INTO: " << *PBI->getParent();
01670   
01671   DOUT << *PBI->getParent()->getParent();
01672   
01673   // This basic block is probably dead.  We know it has at least
01674   // one fewer predecessor.
01675   return true;
01676 }
01677 
01678 
01679 namespace {
01680   /// ConstantIntOrdering - This class implements a stable ordering of constant
01681   /// integers that does not depend on their address.  This is important for
01682   /// applications that sort ConstantInt's to ensure uniqueness.
01683   struct ConstantIntOrdering {
01684     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
01685       return LHS->getValue().ult(RHS->getValue());
01686     }
01687   };
01688 }
01689 
01690 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
01691 /// example, it adjusts branches to branches to eliminate the extra hop, it
01692 /// eliminates unreachable basic blocks, and does other "peephole" optimization
01693 /// of the CFG.  It returns true if a modification was made.
01694 ///
01695 /// WARNING:  The entry node of a function may not be simplified.
01696 ///
01697 bool llvm::SimplifyCFG(BasicBlock *BB) {
01698   bool Changed = false;
01699   Function *M = BB->getParent();
01700 
01701   assert(BB && BB->getParent() && "Block not embedded in function!");
01702   assert(BB->getTerminator() && "Degenerate basic block encountered!");
01703   assert(&BB->getParent()->getEntryBlock() != BB &&
01704          "Can't Simplify entry block!");
01705 
01706   // Remove basic blocks that have no predecessors... or that just have themself
01707   // as a predecessor.  These are unreachable.
01708   if (pred_begin(BB) == pred_end(BB) || BB->getSinglePredecessor() == BB) {
01709     DOUT << "Removing BB: \n" << *BB;
01710     DeleteDeadBlock(BB);
01711     return true;
01712   }
01713 
01714   // Check to see if we can constant propagate this terminator instruction
01715   // away...
01716   Changed |= ConstantFoldTerminator(BB);
01717 
01718   // If there is a trivial two-entry PHI node in this basic block, and we can
01719   // eliminate it, do so now.
01720   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
01721     if (PN->getNumIncomingValues() == 2)
01722       Changed |= FoldTwoEntryPHINode(PN); 
01723 
01724   // If this is a returning block with only PHI nodes in it, fold the return
01725   // instruction into any unconditional branch predecessors.
01726   //
01727   // If any predecessor is a conditional branch that just selects among
01728   // different return values, fold the replace the branch/return with a select
01729   // and return.
01730   if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
01731     BasicBlock::iterator BBI = BB->getTerminator();
01732     if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
01733       // Find predecessors that end with branches.
01734       SmallVector<BasicBlock*, 8> UncondBranchPreds;
01735       SmallVector<BranchInst*, 8> CondBranchPreds;
01736       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
01737         TerminatorInst *PTI = (*PI)->getTerminator();
01738         if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
01739           if (BI->isUnconditional())
01740             UncondBranchPreds.push_back(*PI);
01741           else
01742             CondBranchPreds.push_back(BI);
01743         }
01744       }
01745 
01746       // If we found some, do the transformation!
01747       if (!UncondBranchPreds.empty()) {
01748         while (!UncondBranchPreds.empty()) {
01749           BasicBlock *Pred = UncondBranchPreds.back();
01750           DOUT << "FOLDING: " << *BB
01751                << "INTO UNCOND BRANCH PRED: " << *Pred;
01752           UncondBranchPreds.pop_back();
01753           Instruction *UncondBranch = Pred->getTerminator();
01754           // Clone the return and add it to the end of the predecessor.
01755           Instruction *NewRet = RI->clone();
01756           Pred->getInstList().push_back(NewRet);
01757 
01758           // If the return instruction returns a value, and if the value was a
01759           // PHI node in "BB", propagate the right value into the return.
01760           for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
01761                i != e; ++i)
01762             if (PHINode *PN = dyn_cast<PHINode>(*i))
01763               if (PN->getParent() == BB)
01764                 *i = PN->getIncomingValueForBlock(Pred);
01765           
01766           // Update any PHI nodes in the returning block to realize that we no
01767           // longer branch to them.
01768           BB->removePredecessor(Pred);
01769           Pred->getInstList().erase(UncondBranch);
01770         }
01771 
01772         // If we eliminated all predecessors of the block, delete the block now.
01773         if (pred_begin(BB) == pred_end(BB))
01774           // We know there are no successors, so just nuke the block.
01775           M->getBasicBlockList().erase(BB);
01776 
01777         return true;
01778       }
01779 
01780       // Check out all of the conditional branches going to this return
01781       // instruction.  If any of them just select between returns, change the
01782       // branch itself into a select/return pair.
01783       while (!CondBranchPreds.empty()) {
01784         BranchInst *BI = CondBranchPreds.back();
01785         CondBranchPreds.pop_back();
01786 
01787         // Check to see if the non-BB successor is also a return block.
01788         if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
01789             isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
01790             SimplifyCondBranchToTwoReturns(BI))
01791           return true;
01792       }
01793     }
01794   } else if (isa<UnwindInst>(BB->begin())) {
01795     // Check to see if the first instruction in this block is just an unwind.
01796     // If so, replace any invoke instructions which use this as an exception
01797     // destination with call instructions, and any unconditional branch
01798     // predecessor with an unwind.
01799     //
01800     SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
01801     while (!Preds.empty()) {
01802       BasicBlock *Pred = Preds.back();
01803       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
01804         if (BI->isUnconditional()) {
01805           Pred->getInstList().pop_back();  // nuke uncond branch
01806           new UnwindInst(Pred);            // Use unwind.
01807           Changed = true;
01808         }
01809       } else if (InvokeInst *II = dyn_cast<InvokeInst>(Pred->getTerminator()))
01810         if (II->getUnwindDest() == BB) {
01811           // Insert a new branch instruction before the invoke, because this
01812           // is now a fall through...
01813           BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
01814           Pred->getInstList().remove(II);   // Take out of symbol table
01815 
01816           // Insert the call now...
01817           SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
01818           CallInst *CI = CallInst::Create(II->getCalledValue(),
01819                                           Args.begin(), Args.end(),
01820                                           II->getName(), BI);
01821           CI->setCallingConv(II->getCallingConv());
01822           CI->setAttributes(II->getAttributes());
01823           // If the invoke produced a value, the Call now does instead
01824           II->replaceAllUsesWith(CI);
01825           delete II;
01826           Changed = true;
01827         }
01828 
01829       Preds.pop_back();
01830     }
01831 
01832     // If this block is now dead, remove it.
01833     if (pred_begin(BB) == pred_end(BB)) {
01834       // We know there are no successors, so just nuke the block.
01835       M->getBasicBlockList().erase(BB);
01836       return true;
01837     }
01838 
01839   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
01840     if (isValueEqualityComparison(SI)) {
01841       // If we only have one predecessor, and if it is a branch on this value,
01842       // see if that predecessor totally determines the outcome of this switch.
01843       if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
01844         if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred))
01845           return SimplifyCFG(BB) || 1;
01846 
01847       // If the block only contains the switch, see if we can fold the block
01848       // away into any preds.
01849       if (SI == &BB->front())
01850         if (FoldValueComparisonIntoPredecessors(SI))
01851           return SimplifyCFG(BB) || 1;
01852     }
01853   } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
01854     if (BI->isUnconditional()) {
01855       BasicBlock::iterator BBI = BB->getFirstNonPHI();
01856 
01857       BasicBlock *Succ = BI->getSuccessor(0);
01858       if (BBI->isTerminator() &&  // Terminator is the only non-phi instruction!
01859           Succ != BB)             // Don't hurt infinite loops!
01860         if (TryToSimplifyUncondBranchFromEmptyBlock(BB, Succ))
01861           return true;
01862       
01863     } else {  // Conditional branch
01864       if (isValueEqualityComparison(BI)) {
01865         // If we only have one predecessor, and if it is a branch on this value,
01866         // see if that predecessor totally determines the outcome of this
01867         // switch.
01868         if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
01869           if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred))
01870             return SimplifyCFG(BB) || 1;
01871 
01872         // This block must be empty, except for the setcond inst, if it exists.
01873         BasicBlock::iterator I = BB->begin();
01874         if (&*I == BI ||
01875             (&*I == cast<Instruction>(BI->getCondition()) &&
01876              &*++I == BI))
01877           if (FoldValueComparisonIntoPredecessors(BI))
01878             return SimplifyCFG(BB) | true;
01879       }
01880       
01881       // If this is a branch on a phi node in the current block, thread control
01882       // through this block if any PHI node entries are constants.
01883       if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
01884         if (PN->getParent() == BI->getParent())
01885           if (FoldCondBranchOnPHI(BI))
01886             return SimplifyCFG(BB) | true;
01887 
01888       // If this basic block is ONLY a setcc and a branch, and if a predecessor
01889       // branches to us and one of our successors, fold the setcc into the
01890       // predecessor and use logical operations to pick the right destination.
01891       if (FoldBranchToCommonDest(BI))
01892         return SimplifyCFG(BB) | 1;
01893 
01894 
01895       // Scan predecessor blocks for conditional branches.
01896       for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01897         if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
01898           if (PBI != BI && PBI->isConditional())
01899             if (SimplifyCondBranchToCondBranch(PBI, BI))
01900               return SimplifyCFG(BB) | true;
01901     }
01902   } else if (isa<UnreachableInst>(BB->getTerminator())) {
01903     // If there are any instructions immediately before the unreachable that can
01904     // be removed, do so.
01905     Instruction *Unreachable = BB->getTerminator();
01906     while (Unreachable != BB->begin()) {
01907       BasicBlock::iterator BBI = Unreachable;
01908       --BBI;
01909       // Do not delete instructions that can have side effects, like calls
01910       // (which may never return) and volatile loads and stores.
01911       if (isa<CallInst>(BBI)) break;
01912 
01913       if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
01914         if (SI->isVolatile())
01915           break;
01916 
01917       if (LoadInst *LI = dyn_cast<LoadInst>(BBI))
01918         if (LI->isVolatile())
01919           break;
01920 
01921       // Delete this instruction
01922       BB->getInstList().erase(BBI);
01923       Changed = true;
01924     }
01925 
01926     // If the unreachable instruction is the first in the block, take a gander
01927     // at all of the predecessors of this instruction, and simplify them.
01928     if (&BB->front() == Unreachable) {
01929       SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
01930       for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
01931         TerminatorInst *TI = Preds[i]->getTerminator();
01932 
01933         if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01934           if (BI->isUnconditional()) {
01935             if (BI->getSuccessor(0) == BB) {
01936               new UnreachableInst(TI);
01937               TI->eraseFromParent();
01938               Changed = true;
01939             }
01940           } else {
01941             if (BI->getSuccessor(0) == BB) {
01942               BranchInst::Create(BI->getSuccessor(1), BI);
01943               EraseTerminatorInstAndDCECond(BI);
01944             } else if (BI->getSuccessor(1) == BB) {
01945               BranchInst::Create(BI->getSuccessor(0), BI);
01946               EraseTerminatorInstAndDCECond(BI);
01947               Changed = true;
01948             }
01949           }
01950         } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01951           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
01952             if (SI->getSuccessor(i) == BB) {
01953               BB->removePredecessor(SI->getParent());
01954               SI->removeCase(i);
01955               --i; --e;
01956               Changed = true;
01957             }
01958           // If the default value is unreachable, figure out the most popular
01959           // destination and make it the default.
01960           if (SI->getSuccessor(0) == BB) {
01961             std::map<BasicBlock*, unsigned> Popularity;
01962             for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
01963               Popularity[SI->getSuccessor(i)]++;
01964 
01965             // Find the most popular block.
01966             unsigned MaxPop = 0;
01967             BasicBlock *MaxBlock = 0;
01968             for (std::map<BasicBlock*, unsigned>::iterator
01969                    I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
01970               if (I->second > MaxPop) {
01971                 MaxPop = I->second;
01972                 MaxBlock = I->first;
01973               }
01974             }
01975             if (MaxBlock) {
01976               // Make this the new default, allowing us to delete any explicit
01977               // edges to it.
01978               SI->setSuccessor(0, MaxBlock);
01979               Changed = true;
01980 
01981               // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
01982               // it.
01983               if (isa<PHINode>(MaxBlock->begin()))
01984                 for (unsigned i = 0; i != MaxPop-1; ++i)
01985                   MaxBlock->removePredecessor(SI->getParent());
01986 
01987               for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i)
01988                 if (SI->getSuccessor(i) == MaxBlock) {
01989                   SI->removeCase(i);
01990                   --i; --e;
01991                 }
01992             }
01993           }
01994         } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
01995           if (II->getUnwindDest() == BB) {
01996             // Convert the invoke to a call instruction.  This would be a good
01997             // place to note that the call does not throw though.
01998             BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
01999             II->removeFromParent();   // Take out of symbol table
02000 
02001             // Insert the call now...
02002             SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
02003             CallInst *CI = CallInst::Create(II->getCalledValue(),
02004                                             Args.begin(), Args.end(),
02005                                             II->getName(), BI);
02006             CI->setCallingConv(II->getCallingConv());
02007             CI->setAttributes(II->getAttributes());
02008             // If the invoke produced a value, the Call does now instead.
02009             II->replaceAllUsesWith(CI);
02010             delete II;
02011             Changed = true;
02012           }
02013         }
02014       }
02015 
02016       // If this block is now dead, remove it.
02017       if (pred_begin(BB) == pred_end(BB)) {
02018         // We know there are no successors, so just nuke the block.
02019         M->getBasicBlockList().erase(BB);
02020         return true;
02021       }
02022     }
02023   }
02024 
02025   // Merge basic blocks into their predecessor if there is only one distinct
02026   // pred, and if there is only one distinct successor of the predecessor, and
02027   // if there are no PHI nodes.
02028   //
02029   if (MergeBlockIntoPredecessor(BB))
02030     return true;
02031 
02032   // Otherwise, if this block only has a single predecessor, and if that block
02033   // is a conditional branch, see if we can hoist any code from this block up
02034   // into our predecessor.
02035   pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
02036   BasicBlock *OnlyPred = *PI++;
02037   for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
02038     if (*PI != OnlyPred) {
02039       OnlyPred = 0;       // There are multiple different predecessors...
02040       break;
02041     }
02042   
02043   if (OnlyPred)
02044     if (BranchInst *BI = dyn_cast<BranchInst>(OnlyPred->getTerminator()))
02045       if (BI->isConditional()) {
02046         // Get the other block.
02047         BasicBlock *OtherBB = BI->getSuccessor(BI->getSuccessor(0) == BB);
02048         PI = pred_begin(OtherBB);
02049         ++PI;
02050         
02051         if (PI == pred_end(OtherBB)) {
02052           // We have a conditional branch to two blocks that are only reachable
02053           // from the condbr.  We know that the condbr dominates the two blocks,
02054           // so see if there is any identical code in the "then" and "else"
02055           // blocks.  If so, we can hoist it up to the branching block.
02056           Changed |= HoistThenElseCodeToIf(BI);
02057         } else {
02058           BasicBlock* OnlySucc = NULL;
02059           for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
02060                SI != SE; ++SI) {
02061             if (!OnlySucc)
02062               OnlySucc = *SI;
02063             else if (*SI != OnlySucc) {
02064               OnlySucc = 0;     // There are multiple distinct successors!
02065               break;
02066             }
02067           }
02068 
02069           if (OnlySucc == OtherBB) {
02070             // If BB's only successor is the other successor of the predecessor,
02071             // i.e. a triangle, see if we can hoist any code from this block up
02072             // to the "if" block.
02073             Changed |= SpeculativelyExecuteBB(BI, BB);
02074           }
02075         }
02076       }
02077 
02078   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
02079     if (BranchInst *BI = dyn_cast<BranchInst>((*PI)->getTerminator()))
02080       // Change br (X == 0 | X == 1), T, F into a switch instruction.
02081       if (BI->isConditional() && isa<Instruction>(BI->getCondition())) {
02082         Instruction *Cond = cast<Instruction>(BI->getCondition());
02083         // If this is a bunch of seteq's or'd together, or if it's a bunch of
02084         // 'setne's and'ed together, collect them.
02085         Value *CompVal = 0;
02086         std::vector<ConstantInt*> Values;
02087         bool TrueWhenEqual = GatherValueComparisons(Cond, CompVal, Values);
02088         if (CompVal && CompVal->getType()->isInteger()) {
02089           // There might be duplicate constants in the list, which the switch
02090           // instruction can't handle, remove them now.
02091           std::sort(Values.begin(), Values.end(), ConstantIntOrdering());
02092           Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
02093 
02094           // Figure out which block is which destination.
02095           BasicBlock *DefaultBB = BI->getSuccessor(1);
02096           BasicBlock *EdgeBB    = BI->getSuccessor(0);
02097           if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
02098 
02099           // Create the new switch instruction now.
02100           SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,
02101                                                Values.size(), BI);
02102 
02103           // Add all of the 'cases' to the switch instruction.
02104           for (unsigned i = 0, e = Values.size(); i != e; ++i)
02105             New->addCase(Values[i], EdgeBB);
02106 
02107           // We added edges from PI to the EdgeBB.  As such, if there were any
02108           // PHI nodes in EdgeBB, they need entries to be added corresponding to
02109           // the number of edges added.
02110           for (BasicBlock::iterator BBI = EdgeBB->begin();
02111                isa<PHINode>(BBI); ++BBI) {
02112             PHINode *PN = cast<PHINode>(BBI);
02113             Value *InVal = PN->getIncomingValueForBlock(*PI);
02114             for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
02115               PN->addIncoming(InVal, *PI);
02116           }
02117 
02118           // Erase the old branch instruction.
02119           EraseTerminatorInstAndDCECond(BI);
02120           return true;
02121         }
02122       }
02123 
02124   return Changed;
02125 }