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/ADT/DenseMap.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SetVector.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/ADT/Statistic.h"
00022 #include "llvm/Analysis/ConstantFolding.h"
00023 #include "llvm/Analysis/InstructionSimplify.h"
00024 #include "llvm/Analysis/TargetTransformInfo.h"
00025 #include "llvm/Analysis/ValueTracking.h"
00026 #include "llvm/IR/CFG.h"
00027 #include "llvm/IR/ConstantRange.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/DerivedTypes.h"
00031 #include "llvm/IR/GlobalVariable.h"
00032 #include "llvm/IR/IRBuilder.h"
00033 #include "llvm/IR/Instructions.h"
00034 #include "llvm/IR/IntrinsicInst.h"
00035 #include "llvm/IR/LLVMContext.h"
00036 #include "llvm/IR/MDBuilder.h"
00037 #include "llvm/IR/Metadata.h"
00038 #include "llvm/IR/Module.h"
00039 #include "llvm/IR/NoFolder.h"
00040 #include "llvm/IR/Operator.h"
00041 #include "llvm/IR/PatternMatch.h"
00042 #include "llvm/IR/Type.h"
00043 #include "llvm/Support/CommandLine.h"
00044 #include "llvm/Support/Debug.h"
00045 #include "llvm/Support/raw_ostream.h"
00046 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00047 #include <algorithm>
00048 #include <map>
00049 #include <set>
00050 using namespace llvm;
00051 using namespace PatternMatch;
00052 
00053 static cl::opt<unsigned>
00054 PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
00055    cl::desc("Control the amount of phi node folding to perform (default = 1)"));
00056 
00057 static cl::opt<bool>
00058 DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
00059        cl::desc("Duplicate return instructions into unconditional branches"));
00060 
00061 static cl::opt<bool>
00062 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
00063        cl::desc("Sink common instructions down to the end block"));
00064 
00065 static cl::opt<bool> HoistCondStores(
00066     "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
00067     cl::desc("Hoist conditional stores if an unconditional store precedes"));
00068 
00069 STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
00070 STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
00071 STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
00072 STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
00073 STATISTIC(NumSpeculations, "Number of speculative executed instructions");
00074 
00075 namespace {
00076   /// ValueEqualityComparisonCase - Represents a case of a switch.
00077   struct ValueEqualityComparisonCase {
00078     ConstantInt *Value;
00079     BasicBlock *Dest;
00080 
00081     ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
00082       : Value(Value), Dest(Dest) {}
00083 
00084     bool operator<(ValueEqualityComparisonCase RHS) const {
00085       // Comparing pointers is ok as we only rely on the order for uniquing.
00086       return Value < RHS.Value;
00087     }
00088 
00089     bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
00090   };
00091 
00092 class SimplifyCFGOpt {
00093   const TargetTransformInfo &TTI;
00094   const DataLayout *const DL;
00095   Value *isValueEqualityComparison(TerminatorInst *TI);
00096   BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
00097                                std::vector<ValueEqualityComparisonCase> &Cases);
00098   bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
00099                                                      BasicBlock *Pred,
00100                                                      IRBuilder<> &Builder);
00101   bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
00102                                            IRBuilder<> &Builder);
00103 
00104   bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
00105   bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
00106   bool SimplifyUnreachable(UnreachableInst *UI);
00107   bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
00108   bool SimplifyIndirectBr(IndirectBrInst *IBI);
00109   bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
00110   bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
00111 
00112 public:
00113   SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout *DL)
00114       : TTI(TTI), DL(DL) {}
00115   bool run(BasicBlock *BB);
00116 };
00117 }
00118 
00119 /// SafeToMergeTerminators - Return true if it is safe to merge these two
00120 /// terminator instructions together.
00121 ///
00122 static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
00123   if (SI1 == SI2) return false;  // Can't merge with self!
00124 
00125   // It is not safe to merge these two switch instructions if they have a common
00126   // successor, and if that successor has a PHI node, and if *that* PHI node has
00127   // conflicting incoming values from the two switch blocks.
00128   BasicBlock *SI1BB = SI1->getParent();
00129   BasicBlock *SI2BB = SI2->getParent();
00130   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
00131 
00132   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
00133     if (SI1Succs.count(*I))
00134       for (BasicBlock::iterator BBI = (*I)->begin();
00135            isa<PHINode>(BBI); ++BBI) {
00136         PHINode *PN = cast<PHINode>(BBI);
00137         if (PN->getIncomingValueForBlock(SI1BB) !=
00138             PN->getIncomingValueForBlock(SI2BB))
00139           return false;
00140       }
00141 
00142   return true;
00143 }
00144 
00145 /// isProfitableToFoldUnconditional - Return true if it is safe and profitable
00146 /// to merge these two terminator instructions together, where SI1 is an
00147 /// unconditional branch. PhiNodes will store all PHI nodes in common
00148 /// successors.
00149 ///
00150 static bool isProfitableToFoldUnconditional(BranchInst *SI1,
00151                                           BranchInst *SI2,
00152                                           Instruction *Cond,
00153                                           SmallVectorImpl<PHINode*> &PhiNodes) {
00154   if (SI1 == SI2) return false;  // Can't merge with self!
00155   assert(SI1->isUnconditional() && SI2->isConditional());
00156 
00157   // We fold the unconditional branch if we can easily update all PHI nodes in
00158   // common successors:
00159   // 1> We have a constant incoming value for the conditional branch;
00160   // 2> We have "Cond" as the incoming value for the unconditional branch;
00161   // 3> SI2->getCondition() and Cond have same operands.
00162   CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
00163   if (!Ci2) return false;
00164   if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
00165         Cond->getOperand(1) == Ci2->getOperand(1)) &&
00166       !(Cond->getOperand(0) == Ci2->getOperand(1) &&
00167         Cond->getOperand(1) == Ci2->getOperand(0)))
00168     return false;
00169 
00170   BasicBlock *SI1BB = SI1->getParent();
00171   BasicBlock *SI2BB = SI2->getParent();
00172   SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
00173   for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
00174     if (SI1Succs.count(*I))
00175       for (BasicBlock::iterator BBI = (*I)->begin();
00176            isa<PHINode>(BBI); ++BBI) {
00177         PHINode *PN = cast<PHINode>(BBI);
00178         if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
00179             !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
00180           return false;
00181         PhiNodes.push_back(PN);
00182       }
00183   return true;
00184 }
00185 
00186 /// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
00187 /// now be entries in it from the 'NewPred' block.  The values that will be
00188 /// flowing into the PHI nodes will be the same as those coming in from
00189 /// ExistPred, an existing predecessor of Succ.
00190 static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
00191                                   BasicBlock *ExistPred) {
00192   if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
00193 
00194   PHINode *PN;
00195   for (BasicBlock::iterator I = Succ->begin();
00196        (PN = dyn_cast<PHINode>(I)); ++I)
00197     PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
00198 }
00199 
00200 /// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
00201 /// given instruction, which is assumed to be safe to speculate. 1 means
00202 /// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
00203 static unsigned ComputeSpeculationCost(const User *I) {
00204   assert(isSafeToSpeculativelyExecute(I) &&
00205          "Instruction is not safe to speculatively execute!");
00206   switch (Operator::getOpcode(I)) {
00207   default:
00208     // In doubt, be conservative.
00209     return UINT_MAX;
00210   case Instruction::GetElementPtr:
00211     // GEPs are cheap if all indices are constant.
00212     if (!cast<GEPOperator>(I)->hasAllConstantIndices())
00213       return UINT_MAX;
00214     return 1;
00215   case Instruction::Load:
00216   case Instruction::Add:
00217   case Instruction::Sub:
00218   case Instruction::And:
00219   case Instruction::Or:
00220   case Instruction::Xor:
00221   case Instruction::Shl:
00222   case Instruction::LShr:
00223   case Instruction::AShr:
00224   case Instruction::ICmp:
00225   case Instruction::Trunc:
00226   case Instruction::ZExt:
00227   case Instruction::SExt:
00228     return 1; // These are all cheap.
00229 
00230   case Instruction::Call:
00231   case Instruction::Select:
00232     return 2;
00233   }
00234 }
00235 
00236 /// DominatesMergePoint - If we have a merge point of an "if condition" as
00237 /// accepted above, return true if the specified value dominates the block.  We
00238 /// don't handle the true generality of domination here, just a special case
00239 /// which works well enough for us.
00240 ///
00241 /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
00242 /// see if V (which must be an instruction) and its recursive operands
00243 /// that do not dominate BB have a combined cost lower than CostRemaining and
00244 /// are non-trapping.  If both are true, the instruction is inserted into the
00245 /// set and true is returned.
00246 ///
00247 /// The cost for most non-trapping instructions is defined as 1 except for
00248 /// Select whose cost is 2.
00249 ///
00250 /// After this function returns, CostRemaining is decreased by the cost of
00251 /// V plus its non-dominating operands.  If that cost is greater than
00252 /// CostRemaining, false is returned and CostRemaining is undefined.
00253 static bool DominatesMergePoint(Value *V, BasicBlock *BB,
00254                                 SmallPtrSet<Instruction*, 4> *AggressiveInsts,
00255                                 unsigned &CostRemaining) {
00256   Instruction *I = dyn_cast<Instruction>(V);
00257   if (!I) {
00258     // Non-instructions all dominate instructions, but not all constantexprs
00259     // can be executed unconditionally.
00260     if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
00261       if (C->canTrap())
00262         return false;
00263     return true;
00264   }
00265   BasicBlock *PBB = I->getParent();
00266 
00267   // We don't want to allow weird loops that might have the "if condition" in
00268   // the bottom of this block.
00269   if (PBB == BB) return false;
00270 
00271   // If this instruction is defined in a block that contains an unconditional
00272   // branch to BB, then it must be in the 'conditional' part of the "if
00273   // statement".  If not, it definitely dominates the region.
00274   BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
00275   if (BI == 0 || BI->isConditional() || BI->getSuccessor(0) != BB)
00276     return true;
00277 
00278   // If we aren't allowing aggressive promotion anymore, then don't consider
00279   // instructions in the 'if region'.
00280   if (AggressiveInsts == 0) return false;
00281 
00282   // If we have seen this instruction before, don't count it again.
00283   if (AggressiveInsts->count(I)) return true;
00284 
00285   // Okay, it looks like the instruction IS in the "condition".  Check to
00286   // see if it's a cheap instruction to unconditionally compute, and if it
00287   // only uses stuff defined outside of the condition.  If so, hoist it out.
00288   if (!isSafeToSpeculativelyExecute(I))
00289     return false;
00290 
00291   unsigned Cost = ComputeSpeculationCost(I);
00292 
00293   if (Cost > CostRemaining)
00294     return false;
00295 
00296   CostRemaining -= Cost;
00297 
00298   // Okay, we can only really hoist these out if their operands do
00299   // not take us over the cost threshold.
00300   for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
00301     if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining))
00302       return false;
00303   // Okay, it's safe to do this!  Remember this instruction.
00304   AggressiveInsts->insert(I);
00305   return true;
00306 }
00307 
00308 /// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
00309 /// and PointerNullValue. Return NULL if value is not a constant int.
00310 static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
00311   // Normal constant int.
00312   ConstantInt *CI = dyn_cast<ConstantInt>(V);
00313   if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
00314     return CI;
00315 
00316   // This is some kind of pointer constant. Turn it into a pointer-sized
00317   // ConstantInt if possible.
00318   IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
00319 
00320   // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
00321   if (isa<ConstantPointerNull>(V))
00322     return ConstantInt::get(PtrTy, 0);
00323 
00324   // IntToPtr const int.
00325   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
00326     if (CE->getOpcode() == Instruction::IntToPtr)
00327       if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
00328         // The constant is very likely to have the right type already.
00329         if (CI->getType() == PtrTy)
00330           return CI;
00331         else
00332           return cast<ConstantInt>
00333             (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
00334       }
00335   return 0;
00336 }
00337 
00338 /// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
00339 /// collection of icmp eq/ne instructions that compare a value against a
00340 /// constant, return the value being compared, and stick the constant into the
00341 /// Values vector.
00342 static Value *
00343 GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
00344                        const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
00345   Instruction *I = dyn_cast<Instruction>(V);
00346   if (I == 0) return 0;
00347 
00348   // If this is an icmp against a constant, handle this as one of the cases.
00349   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
00350     if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
00351       Value *RHSVal;
00352       ConstantInt *RHSC;
00353 
00354       if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
00355         // (x & ~2^x) == y --> x == y || x == y|2^x
00356         // This undoes a transformation done by instcombine to fuse 2 compares.
00357         if (match(ICI->getOperand(0),
00358                   m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
00359           APInt Not = ~RHSC->getValue();
00360           if (Not.isPowerOf2()) {
00361             Vals.push_back(C);
00362             Vals.push_back(
00363                 ConstantInt::get(C->getContext(), C->getValue() | Not));
00364             UsedICmps++;
00365             return RHSVal;
00366           }
00367         }
00368 
00369         UsedICmps++;
00370         Vals.push_back(C);
00371         return I->getOperand(0);
00372       }
00373 
00374       // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
00375       // the set.
00376       ConstantRange Span =
00377         ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
00378 
00379       // Shift the range if the compare is fed by an add. This is the range
00380       // compare idiom as emitted by instcombine.
00381       bool hasAdd =
00382           match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
00383       if (hasAdd)
00384         Span = Span.subtract(RHSC->getValue());
00385 
00386       // If this is an and/!= check then we want to optimize "x ugt 2" into
00387       // x != 0 && x != 1.
00388       if (!isEQ)
00389         Span = Span.inverse();
00390 
00391       // If there are a ton of values, we don't want to make a ginormous switch.
00392       if (Span.getSetSize().ugt(8) || Span.isEmptySet())
00393         return 0;
00394 
00395       for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
00396         Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
00397       UsedICmps++;
00398       return hasAdd ? RHSVal : I->getOperand(0);
00399     }
00400     return 0;
00401   }
00402 
00403   // Otherwise, we can only handle an | or &, depending on isEQ.
00404   if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
00405     return 0;
00406 
00407   unsigned NumValsBeforeLHS = Vals.size();
00408   unsigned UsedICmpsBeforeLHS = UsedICmps;
00409   if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
00410                                           isEQ, UsedICmps)) {
00411     unsigned NumVals = Vals.size();
00412     unsigned UsedICmpsBeforeRHS = UsedICmps;
00413     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
00414                                             isEQ, UsedICmps)) {
00415       if (LHS == RHS)
00416         return LHS;
00417       Vals.resize(NumVals);
00418       UsedICmps = UsedICmpsBeforeRHS;
00419     }
00420 
00421     // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
00422     // set it and return success.
00423     if (Extra == 0 || Extra == I->getOperand(1)) {
00424       Extra = I->getOperand(1);
00425       return LHS;
00426     }
00427 
00428     Vals.resize(NumValsBeforeLHS);
00429     UsedICmps = UsedICmpsBeforeLHS;
00430     return 0;
00431   }
00432 
00433   // If the LHS can't be folded in, but Extra is available and RHS can, try to
00434   // use LHS as Extra.
00435   if (Extra == 0 || Extra == I->getOperand(0)) {
00436     Value *OldExtra = Extra;
00437     Extra = I->getOperand(0);
00438     if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
00439                                             isEQ, UsedICmps))
00440       return RHS;
00441     assert(Vals.size() == NumValsBeforeLHS);
00442     Extra = OldExtra;
00443   }
00444 
00445   return 0;
00446 }
00447 
00448 static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
00449   Instruction *Cond = 0;
00450   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00451     Cond = dyn_cast<Instruction>(SI->getCondition());
00452   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00453     if (BI->isConditional())
00454       Cond = dyn_cast<Instruction>(BI->getCondition());
00455   } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
00456     Cond = dyn_cast<Instruction>(IBI->getAddress());
00457   }
00458 
00459   TI->eraseFromParent();
00460   if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
00461 }
00462 
00463 /// isValueEqualityComparison - Return true if the specified terminator checks
00464 /// to see if a value is equal to constant integer value.
00465 Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
00466   Value *CV = 0;
00467   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00468     // Do not permit merging of large switch instructions into their
00469     // predecessors unless there is only one predecessor.
00470     if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
00471                                              pred_end(SI->getParent())) <= 128)
00472       CV = SI->getCondition();
00473   } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
00474     if (BI->isConditional() && BI->getCondition()->hasOneUse())
00475       if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
00476         if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
00477           CV = ICI->getOperand(0);
00478 
00479   // Unwrap any lossless ptrtoint cast.
00480   if (DL && CV) {
00481     if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
00482       Value *Ptr = PTII->getPointerOperand();
00483       if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
00484         CV = Ptr;
00485     }
00486   }
00487   return CV;
00488 }
00489 
00490 /// GetValueEqualityComparisonCases - Given a value comparison instruction,
00491 /// decode all of the 'cases' that it represents and return the 'default' block.
00492 BasicBlock *SimplifyCFGOpt::
00493 GetValueEqualityComparisonCases(TerminatorInst *TI,
00494                                 std::vector<ValueEqualityComparisonCase>
00495                                                                        &Cases) {
00496   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00497     Cases.reserve(SI->getNumCases());
00498     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
00499       Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
00500                                                   i.getCaseSuccessor()));
00501     return SI->getDefaultDest();
00502   }
00503 
00504   BranchInst *BI = cast<BranchInst>(TI);
00505   ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
00506   BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
00507   Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
00508                                                              DL),
00509                                               Succ));
00510   return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
00511 }
00512 
00513 
00514 /// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
00515 /// in the list that match the specified block.
00516 static void EliminateBlockCases(BasicBlock *BB,
00517                               std::vector<ValueEqualityComparisonCase> &Cases) {
00518   Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
00519 }
00520 
00521 /// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
00522 /// well.
00523 static bool
00524 ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
00525               std::vector<ValueEqualityComparisonCase > &C2) {
00526   std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
00527 
00528   // Make V1 be smaller than V2.
00529   if (V1->size() > V2->size())
00530     std::swap(V1, V2);
00531 
00532   if (V1->size() == 0) return false;
00533   if (V1->size() == 1) {
00534     // Just scan V2.
00535     ConstantInt *TheVal = (*V1)[0].Value;
00536     for (unsigned i = 0, e = V2->size(); i != e; ++i)
00537       if (TheVal == (*V2)[i].Value)
00538         return true;
00539   }
00540 
00541   // Otherwise, just sort both lists and compare element by element.
00542   array_pod_sort(V1->begin(), V1->end());
00543   array_pod_sort(V2->begin(), V2->end());
00544   unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
00545   while (i1 != e1 && i2 != e2) {
00546     if ((*V1)[i1].Value == (*V2)[i2].Value)
00547       return true;
00548     if ((*V1)[i1].Value < (*V2)[i2].Value)
00549       ++i1;
00550     else
00551       ++i2;
00552   }
00553   return false;
00554 }
00555 
00556 /// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
00557 /// terminator instruction and its block is known to only have a single
00558 /// predecessor block, check to see if that predecessor is also a value
00559 /// comparison with the same value, and if that comparison determines the
00560 /// outcome of this comparison.  If so, simplify TI.  This does a very limited
00561 /// form of jump threading.
00562 bool SimplifyCFGOpt::
00563 SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
00564                                               BasicBlock *Pred,
00565                                               IRBuilder<> &Builder) {
00566   Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
00567   if (!PredVal) return false;  // Not a value comparison in predecessor.
00568 
00569   Value *ThisVal = isValueEqualityComparison(TI);
00570   assert(ThisVal && "This isn't a value comparison!!");
00571   if (ThisVal != PredVal) return false;  // Different predicates.
00572 
00573   // TODO: Preserve branch weight metadata, similarly to how
00574   // FoldValueComparisonIntoPredecessors preserves it.
00575 
00576   // Find out information about when control will move from Pred to TI's block.
00577   std::vector<ValueEqualityComparisonCase> PredCases;
00578   BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
00579                                                         PredCases);
00580   EliminateBlockCases(PredDef, PredCases);  // Remove default from cases.
00581 
00582   // Find information about how control leaves this block.
00583   std::vector<ValueEqualityComparisonCase> ThisCases;
00584   BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
00585   EliminateBlockCases(ThisDef, ThisCases);  // Remove default from cases.
00586 
00587   // If TI's block is the default block from Pred's comparison, potentially
00588   // simplify TI based on this knowledge.
00589   if (PredDef == TI->getParent()) {
00590     // If we are here, we know that the value is none of those cases listed in
00591     // PredCases.  If there are any cases in ThisCases that are in PredCases, we
00592     // can simplify TI.
00593     if (!ValuesOverlap(PredCases, ThisCases))
00594       return false;
00595 
00596     if (isa<BranchInst>(TI)) {
00597       // Okay, one of the successors of this condbr is dead.  Convert it to a
00598       // uncond br.
00599       assert(ThisCases.size() == 1 && "Branch can only have one case!");
00600       // Insert the new branch.
00601       Instruction *NI = Builder.CreateBr(ThisDef);
00602       (void) NI;
00603 
00604       // Remove PHI node entries for the dead edge.
00605       ThisCases[0].Dest->removePredecessor(TI->getParent());
00606 
00607       DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
00608            << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
00609 
00610       EraseTerminatorInstAndDCECond(TI);
00611       return true;
00612     }
00613 
00614     SwitchInst *SI = cast<SwitchInst>(TI);
00615     // Okay, TI has cases that are statically dead, prune them away.
00616     SmallPtrSet<Constant*, 16> DeadCases;
00617     for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00618       DeadCases.insert(PredCases[i].Value);
00619 
00620     DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
00621                  << "Through successor TI: " << *TI);
00622 
00623     // Collect branch weights into a vector.
00624     SmallVector<uint32_t, 8> Weights;
00625     MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
00626     bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
00627     if (HasWeight)
00628       for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
00629            ++MD_i) {
00630         ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
00631         assert(CI);
00632         Weights.push_back(CI->getValue().getZExtValue());
00633       }
00634     for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
00635       --i;
00636       if (DeadCases.count(i.getCaseValue())) {
00637         if (HasWeight) {
00638           std::swap(Weights[i.getCaseIndex()+1], Weights.back());
00639           Weights.pop_back();
00640         }
00641         i.getCaseSuccessor()->removePredecessor(TI->getParent());
00642         SI->removeCase(i);
00643       }
00644     }
00645     if (HasWeight && Weights.size() >= 2)
00646       SI->setMetadata(LLVMContext::MD_prof,
00647                       MDBuilder(SI->getParent()->getContext()).
00648                       createBranchWeights(Weights));
00649 
00650     DEBUG(dbgs() << "Leaving: " << *TI << "\n");
00651     return true;
00652   }
00653 
00654   // Otherwise, TI's block must correspond to some matched value.  Find out
00655   // which value (or set of values) this is.
00656   ConstantInt *TIV = 0;
00657   BasicBlock *TIBB = TI->getParent();
00658   for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00659     if (PredCases[i].Dest == TIBB) {
00660       if (TIV != 0)
00661         return false;  // Cannot handle multiple values coming to this block.
00662       TIV = PredCases[i].Value;
00663     }
00664   assert(TIV && "No edge from pred to succ?");
00665 
00666   // Okay, we found the one constant that our value can be if we get into TI's
00667   // BB.  Find out which successor will unconditionally be branched to.
00668   BasicBlock *TheRealDest = 0;
00669   for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
00670     if (ThisCases[i].Value == TIV) {
00671       TheRealDest = ThisCases[i].Dest;
00672       break;
00673     }
00674 
00675   // If not handled by any explicit cases, it is handled by the default case.
00676   if (TheRealDest == 0) TheRealDest = ThisDef;
00677 
00678   // Remove PHI node entries for dead edges.
00679   BasicBlock *CheckEdge = TheRealDest;
00680   for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
00681     if (*SI != CheckEdge)
00682       (*SI)->removePredecessor(TIBB);
00683     else
00684       CheckEdge = 0;
00685 
00686   // Insert the new branch.
00687   Instruction *NI = Builder.CreateBr(TheRealDest);
00688   (void) NI;
00689 
00690   DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
00691             << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
00692 
00693   EraseTerminatorInstAndDCECond(TI);
00694   return true;
00695 }
00696 
00697 namespace {
00698   /// ConstantIntOrdering - This class implements a stable ordering of constant
00699   /// integers that does not depend on their address.  This is important for
00700   /// applications that sort ConstantInt's to ensure uniqueness.
00701   struct ConstantIntOrdering {
00702     bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
00703       return LHS->getValue().ult(RHS->getValue());
00704     }
00705   };
00706 }
00707 
00708 static int ConstantIntSortPredicate(ConstantInt *const *P1,
00709                                     ConstantInt *const *P2) {
00710   const ConstantInt *LHS = *P1;
00711   const ConstantInt *RHS = *P2;
00712   if (LHS->getValue().ult(RHS->getValue()))
00713     return 1;
00714   if (LHS->getValue() == RHS->getValue())
00715     return 0;
00716   return -1;
00717 }
00718 
00719 static inline bool HasBranchWeights(const Instruction* I) {
00720   MDNode* ProfMD = I->getMetadata(LLVMContext::MD_prof);
00721   if (ProfMD && ProfMD->getOperand(0))
00722     if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
00723       return MDS->getString().equals("branch_weights");
00724 
00725   return false;
00726 }
00727 
00728 /// Get Weights of a given TerminatorInst, the default weight is at the front
00729 /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
00730 /// metadata.
00731 static void GetBranchWeights(TerminatorInst *TI,
00732                              SmallVectorImpl<uint64_t> &Weights) {
00733   MDNode* MD = TI->getMetadata(LLVMContext::MD_prof);
00734   assert(MD);
00735   for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
00736     ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
00737     Weights.push_back(CI->getValue().getZExtValue());
00738   }
00739 
00740   // If TI is a conditional eq, the default case is the false case,
00741   // and the corresponding branch-weight data is at index 2. We swap the
00742   // default weight to be the first entry.
00743   if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
00744     assert(Weights.size() == 2);
00745     ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
00746     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
00747       std::swap(Weights.front(), Weights.back());
00748   }
00749 }
00750 
00751 /// Keep halving the weights until all can fit in uint32_t.
00752 static void FitWeights(MutableArrayRef<uint64_t> Weights) {
00753   uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
00754   if (Max > UINT_MAX) {
00755     unsigned Offset = 32 - countLeadingZeros(Max);
00756     for (uint64_t &I : Weights)
00757       I >>= Offset;
00758   }
00759 }
00760 
00761 /// FoldValueComparisonIntoPredecessors - The specified terminator is a value
00762 /// equality comparison instruction (either a switch or a branch on "X == c").
00763 /// See if any of the predecessors of the terminator block are value comparisons
00764 /// on the same value.  If so, and if safe to do so, fold them together.
00765 bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
00766                                                          IRBuilder<> &Builder) {
00767   BasicBlock *BB = TI->getParent();
00768   Value *CV = isValueEqualityComparison(TI);  // CondVal
00769   assert(CV && "Not a comparison?");
00770   bool Changed = false;
00771 
00772   SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
00773   while (!Preds.empty()) {
00774     BasicBlock *Pred = Preds.pop_back_val();
00775 
00776     // See if the predecessor is a comparison with the same value.
00777     TerminatorInst *PTI = Pred->getTerminator();
00778     Value *PCV = isValueEqualityComparison(PTI);  // PredCondVal
00779 
00780     if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
00781       // Figure out which 'cases' to copy from SI to PSI.
00782       std::vector<ValueEqualityComparisonCase> BBCases;
00783       BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
00784 
00785       std::vector<ValueEqualityComparisonCase> PredCases;
00786       BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
00787 
00788       // Based on whether the default edge from PTI goes to BB or not, fill in
00789       // PredCases and PredDefault with the new switch cases we would like to
00790       // build.
00791       SmallVector<BasicBlock*, 8> NewSuccessors;
00792 
00793       // Update the branch weight metadata along the way
00794       SmallVector<uint64_t, 8> Weights;
00795       bool PredHasWeights = HasBranchWeights(PTI);
00796       bool SuccHasWeights = HasBranchWeights(TI);
00797 
00798       if (PredHasWeights) {
00799         GetBranchWeights(PTI, Weights);
00800         // branch-weight metadata is inconsistent here.
00801         if (Weights.size() != 1 + PredCases.size())
00802           PredHasWeights = SuccHasWeights = false;
00803       } else if (SuccHasWeights)
00804         // If there are no predecessor weights but there are successor weights,
00805         // populate Weights with 1, which will later be scaled to the sum of
00806         // successor's weights
00807         Weights.assign(1 + PredCases.size(), 1);
00808 
00809       SmallVector<uint64_t, 8> SuccWeights;
00810       if (SuccHasWeights) {
00811         GetBranchWeights(TI, SuccWeights);
00812         // branch-weight metadata is inconsistent here.
00813         if (SuccWeights.size() != 1 + BBCases.size())
00814           PredHasWeights = SuccHasWeights = false;
00815       } else if (PredHasWeights)
00816         SuccWeights.assign(1 + BBCases.size(), 1);
00817 
00818       if (PredDefault == BB) {
00819         // If this is the default destination from PTI, only the edges in TI
00820         // that don't occur in PTI, or that branch to BB will be activated.
00821         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
00822         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00823           if (PredCases[i].Dest != BB)
00824             PTIHandled.insert(PredCases[i].Value);
00825           else {
00826             // The default destination is BB, we don't need explicit targets.
00827             std::swap(PredCases[i], PredCases.back());
00828 
00829             if (PredHasWeights || SuccHasWeights) {
00830               // Increase weight for the default case.
00831               Weights[0] += Weights[i+1];
00832               std::swap(Weights[i+1], Weights.back());
00833               Weights.pop_back();
00834             }
00835 
00836             PredCases.pop_back();
00837             --i; --e;
00838           }
00839 
00840         // Reconstruct the new switch statement we will be building.
00841         if (PredDefault != BBDefault) {
00842           PredDefault->removePredecessor(Pred);
00843           PredDefault = BBDefault;
00844           NewSuccessors.push_back(BBDefault);
00845         }
00846 
00847         unsigned CasesFromPred = Weights.size();
00848         uint64_t ValidTotalSuccWeight = 0;
00849         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00850           if (!PTIHandled.count(BBCases[i].Value) &&
00851               BBCases[i].Dest != BBDefault) {
00852             PredCases.push_back(BBCases[i]);
00853             NewSuccessors.push_back(BBCases[i].Dest);
00854             if (SuccHasWeights || PredHasWeights) {
00855               // The default weight is at index 0, so weight for the ith case
00856               // should be at index i+1. Scale the cases from successor by
00857               // PredDefaultWeight (Weights[0]).
00858               Weights.push_back(Weights[0] * SuccWeights[i+1]);
00859               ValidTotalSuccWeight += SuccWeights[i+1];
00860             }
00861           }
00862 
00863         if (SuccHasWeights || PredHasWeights) {
00864           ValidTotalSuccWeight += SuccWeights[0];
00865           // Scale the cases from predecessor by ValidTotalSuccWeight.
00866           for (unsigned i = 1; i < CasesFromPred; ++i)
00867             Weights[i] *= ValidTotalSuccWeight;
00868           // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
00869           Weights[0] *= SuccWeights[0];
00870         }
00871       } else {
00872         // If this is not the default destination from PSI, only the edges
00873         // in SI that occur in PSI with a destination of BB will be
00874         // activated.
00875         std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
00876         std::map<ConstantInt*, uint64_t> WeightsForHandled;
00877         for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00878           if (PredCases[i].Dest == BB) {
00879             PTIHandled.insert(PredCases[i].Value);
00880 
00881             if (PredHasWeights || SuccHasWeights) {
00882               WeightsForHandled[PredCases[i].Value] = Weights[i+1];
00883               std::swap(Weights[i+1], Weights.back());
00884               Weights.pop_back();
00885             }
00886 
00887             std::swap(PredCases[i], PredCases.back());
00888             PredCases.pop_back();
00889             --i; --e;
00890           }
00891 
00892         // Okay, now we know which constants were sent to BB from the
00893         // predecessor.  Figure out where they will all go now.
00894         for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
00895           if (PTIHandled.count(BBCases[i].Value)) {
00896             // If this is one we are capable of getting...
00897             if (PredHasWeights || SuccHasWeights)
00898               Weights.push_back(WeightsForHandled[BBCases[i].Value]);
00899             PredCases.push_back(BBCases[i]);
00900             NewSuccessors.push_back(BBCases[i].Dest);
00901             PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
00902           }
00903 
00904         // If there are any constants vectored to BB that TI doesn't handle,
00905         // they must go to the default destination of TI.
00906         for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
00907                                     PTIHandled.begin(),
00908                E = PTIHandled.end(); I != E; ++I) {
00909           if (PredHasWeights || SuccHasWeights)
00910             Weights.push_back(WeightsForHandled[*I]);
00911           PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
00912           NewSuccessors.push_back(BBDefault);
00913         }
00914       }
00915 
00916       // Okay, at this point, we know which new successor Pred will get.  Make
00917       // sure we update the number of entries in the PHI nodes for these
00918       // successors.
00919       for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
00920         AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
00921 
00922       Builder.SetInsertPoint(PTI);
00923       // Convert pointer to int before we switch.
00924       if (CV->getType()->isPointerTy()) {
00925         assert(DL && "Cannot switch on pointer without DataLayout");
00926         CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
00927                                     "magicptr");
00928       }
00929 
00930       // Now that the successors are updated, create the new Switch instruction.
00931       SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
00932                                                PredCases.size());
00933       NewSI->setDebugLoc(PTI->getDebugLoc());
00934       for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
00935         NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
00936 
00937       if (PredHasWeights || SuccHasWeights) {
00938         // Halve the weights if any of them cannot fit in an uint32_t
00939         FitWeights(Weights);
00940 
00941         SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
00942 
00943         NewSI->setMetadata(LLVMContext::MD_prof,
00944                            MDBuilder(BB->getContext()).
00945                            createBranchWeights(MDWeights));
00946       }
00947 
00948       EraseTerminatorInstAndDCECond(PTI);
00949 
00950       // Okay, last check.  If BB is still a successor of PSI, then we must
00951       // have an infinite loop case.  If so, add an infinitely looping block
00952       // to handle the case to preserve the behavior of the code.
00953       BasicBlock *InfLoopBlock = 0;
00954       for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
00955         if (NewSI->getSuccessor(i) == BB) {
00956           if (InfLoopBlock == 0) {
00957             // Insert it at the end of the function, because it's either code,
00958             // or it won't matter if it's hot. :)
00959             InfLoopBlock = BasicBlock::Create(BB->getContext(),
00960                                               "infloop", BB->getParent());
00961             BranchInst::Create(InfLoopBlock, InfLoopBlock);
00962           }
00963           NewSI->setSuccessor(i, InfLoopBlock);
00964         }
00965 
00966       Changed = true;
00967     }
00968   }
00969   return Changed;
00970 }
00971 
00972 // isSafeToHoistInvoke - If we would need to insert a select that uses the
00973 // value of this invoke (comments in HoistThenElseCodeToIf explain why we
00974 // would need to do this), we can't hoist the invoke, as there is nowhere
00975 // to put the select in this case.
00976 static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
00977                                 Instruction *I1, Instruction *I2) {
00978   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
00979     PHINode *PN;
00980     for (BasicBlock::iterator BBI = SI->begin();
00981          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00982       Value *BB1V = PN->getIncomingValueForBlock(BB1);
00983       Value *BB2V = PN->getIncomingValueForBlock(BB2);
00984       if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
00985         return false;
00986       }
00987     }
00988   }
00989   return true;
00990 }
00991 
00992 /// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
00993 /// BB2, hoist any common code in the two blocks up into the branch block.  The
00994 /// caller of this function guarantees that BI's block dominates BB1 and BB2.
00995 static bool HoistThenElseCodeToIf(BranchInst *BI) {
00996   // This does very trivial matching, with limited scanning, to find identical
00997   // instructions in the two blocks.  In particular, we don't want to get into
00998   // O(M*N) situations here where M and N are the sizes of BB1 and BB2.  As
00999   // such, we currently just scan for obviously identical instructions in an
01000   // identical order.
01001   BasicBlock *BB1 = BI->getSuccessor(0);  // The true destination.
01002   BasicBlock *BB2 = BI->getSuccessor(1);  // The false destination
01003 
01004   BasicBlock::iterator BB1_Itr = BB1->begin();
01005   BasicBlock::iterator BB2_Itr = BB2->begin();
01006 
01007   Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
01008   // Skip debug info if it is not identical.
01009   DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
01010   DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
01011   if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
01012     while (isa<DbgInfoIntrinsic>(I1))
01013       I1 = BB1_Itr++;
01014     while (isa<DbgInfoIntrinsic>(I2))
01015       I2 = BB2_Itr++;
01016   }
01017   if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
01018       (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
01019     return false;
01020 
01021   BasicBlock *BIParent = BI->getParent();
01022 
01023   bool Changed = false;
01024   do {
01025     // If we are hoisting the terminator instruction, don't move one (making a
01026     // broken BB), instead clone it, and remove BI.
01027     if (isa<TerminatorInst>(I1))
01028       goto HoistTerminator;
01029 
01030     // For a normal instruction, we just move one to right before the branch,
01031     // then replace all uses of the other with the first.  Finally, we remove
01032     // the now redundant second instruction.
01033     BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
01034     if (!I2->use_empty())
01035       I2->replaceAllUsesWith(I1);
01036     I1->intersectOptionalDataWith(I2);
01037     I2->eraseFromParent();
01038     Changed = true;
01039 
01040     I1 = BB1_Itr++;
01041     I2 = BB2_Itr++;
01042     // Skip debug info if it is not identical.
01043     DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
01044     DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
01045     if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
01046       while (isa<DbgInfoIntrinsic>(I1))
01047         I1 = BB1_Itr++;
01048       while (isa<DbgInfoIntrinsic>(I2))
01049         I2 = BB2_Itr++;
01050     }
01051   } while (I1->isIdenticalToWhenDefined(I2));
01052 
01053   return true;
01054 
01055 HoistTerminator:
01056   // It may not be possible to hoist an invoke.
01057   if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
01058     return Changed;
01059 
01060   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
01061     PHINode *PN;
01062     for (BasicBlock::iterator BBI = SI->begin();
01063          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
01064       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01065       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01066       if (BB1V == BB2V)
01067         continue;
01068 
01069       if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
01070         return Changed;
01071       if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
01072         return Changed;
01073     }
01074   }
01075 
01076   // Okay, it is safe to hoist the terminator.
01077   Instruction *NT = I1->clone();
01078   BIParent->getInstList().insert(BI, NT);
01079   if (!NT->getType()->isVoidTy()) {
01080     I1->replaceAllUsesWith(NT);
01081     I2->replaceAllUsesWith(NT);
01082     NT->takeName(I1);
01083   }
01084 
01085   IRBuilder<true, NoFolder> Builder(NT);
01086   // Hoisting one of the terminators from our successor is a great thing.
01087   // Unfortunately, the successors of the if/else blocks may have PHI nodes in
01088   // them.  If they do, all PHI entries for BB1/BB2 must agree for all PHI
01089   // nodes, so we insert select instruction to compute the final result.
01090   std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
01091   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
01092     PHINode *PN;
01093     for (BasicBlock::iterator BBI = SI->begin();
01094          (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
01095       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01096       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01097       if (BB1V == BB2V) continue;
01098 
01099       // These values do not agree.  Insert a select instruction before NT
01100       // that determines the right value.
01101       SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
01102       if (SI == 0)
01103         SI = cast<SelectInst>
01104           (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
01105                                 BB1V->getName()+"."+BB2V->getName()));
01106 
01107       // Make the PHI node use the select for all incoming values for BB1/BB2
01108       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01109         if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
01110           PN->setIncomingValue(i, SI);
01111     }
01112   }
01113 
01114   // Update any PHI nodes in our new successors.
01115   for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
01116     AddPredecessorToBlock(*SI, BIParent, BB1);
01117 
01118   EraseTerminatorInstAndDCECond(BI);
01119   return true;
01120 }
01121 
01122 /// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
01123 /// check whether BBEnd has only two predecessors and the other predecessor
01124 /// ends with an unconditional branch. If it is true, sink any common code
01125 /// in the two predecessors to BBEnd.
01126 static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
01127   assert(BI1->isUnconditional());
01128   BasicBlock *BB1 = BI1->getParent();
01129   BasicBlock *BBEnd = BI1->getSuccessor(0);
01130 
01131   // Check that BBEnd has two predecessors and the other predecessor ends with
01132   // an unconditional branch.
01133   pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
01134   BasicBlock *Pred0 = *PI++;
01135   if (PI == PE) // Only one predecessor.
01136     return false;
01137   BasicBlock *Pred1 = *PI++;
01138   if (PI != PE) // More than two predecessors.
01139     return false;
01140   BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
01141   BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
01142   if (!BI2 || !BI2->isUnconditional())
01143     return false;
01144 
01145   // Gather the PHI nodes in BBEnd.
01146   std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
01147   Instruction *FirstNonPhiInBBEnd = 0;
01148   for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
01149        I != E; ++I) {
01150     if (PHINode *PN = dyn_cast<PHINode>(I)) {
01151       Value *BB1V = PN->getIncomingValueForBlock(BB1);
01152       Value *BB2V = PN->getIncomingValueForBlock(BB2);
01153       MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
01154     } else {
01155       FirstNonPhiInBBEnd = &*I;
01156       break;
01157     }
01158   }
01159   if (!FirstNonPhiInBBEnd)
01160     return false;
01161 
01162 
01163   // This does very trivial matching, with limited scanning, to find identical
01164   // instructions in the two blocks.  We scan backward for obviously identical
01165   // instructions in an identical order.
01166   BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
01167       RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
01168       RE2 = BB2->getInstList().rend();
01169   // Skip debug info.
01170   while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
01171   if (RI1 == RE1)
01172     return false;
01173   while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
01174   if (RI2 == RE2)
01175     return false;
01176   // Skip the unconditional branches.
01177   ++RI1;
01178   ++RI2;
01179 
01180   bool Changed = false;
01181   while (RI1 != RE1 && RI2 != RE2) {
01182     // Skip debug info.
01183     while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
01184     if (RI1 == RE1)
01185       return Changed;
01186     while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
01187     if (RI2 == RE2)
01188       return Changed;
01189 
01190     Instruction *I1 = &*RI1, *I2 = &*RI2;
01191     // I1 and I2 should have a single use in the same PHI node, and they
01192     // perform the same operation.
01193     // Cannot move control-flow-involving, volatile loads, vaarg, etc.
01194     if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
01195         isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
01196         isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
01197         isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
01198         I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
01199         I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
01200         !I1->hasOneUse() || !I2->hasOneUse() ||
01201         MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
01202         MapValueFromBB1ToBB2[I1].first != I2)
01203       return Changed;
01204 
01205     // Check whether we should swap the operands of ICmpInst.
01206     ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
01207     bool SwapOpnds = false;
01208     if (ICmp1 && ICmp2 &&
01209         ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
01210         ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
01211         (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
01212          ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
01213       ICmp2->swapOperands();
01214       SwapOpnds = true;
01215     }
01216     if (!I1->isSameOperationAs(I2)) {
01217       if (SwapOpnds)
01218         ICmp2->swapOperands();
01219       return Changed;
01220     }
01221 
01222     // The operands should be either the same or they need to be generated
01223     // with a PHI node after sinking. We only handle the case where there is
01224     // a single pair of different operands.
01225     Value *DifferentOp1 = 0, *DifferentOp2 = 0;
01226     unsigned Op1Idx = 0;
01227     for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
01228       if (I1->getOperand(I) == I2->getOperand(I))
01229         continue;
01230       // Early exit if we have more-than one pair of different operands or
01231       // the different operand is already in MapValueFromBB1ToBB2.
01232       // Early exit if we need a PHI node to replace a constant.
01233       if (DifferentOp1 ||
01234           MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
01235           MapValueFromBB1ToBB2.end() ||
01236           isa<Constant>(I1->getOperand(I)) ||
01237           isa<Constant>(I2->getOperand(I))) {
01238         // If we can't sink the instructions, undo the swapping.
01239         if (SwapOpnds)
01240           ICmp2->swapOperands();
01241         return Changed;
01242       }
01243       DifferentOp1 = I1->getOperand(I);
01244       Op1Idx = I;
01245       DifferentOp2 = I2->getOperand(I);
01246     }
01247 
01248     // We insert the pair of different operands to MapValueFromBB1ToBB2 and
01249     // remove (I1, I2) from MapValueFromBB1ToBB2.
01250     if (DifferentOp1) {
01251       PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
01252                                        DifferentOp1->getName() + ".sink",
01253                                        BBEnd->begin());
01254       MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
01255       // I1 should use NewPN instead of DifferentOp1.
01256       I1->setOperand(Op1Idx, NewPN);
01257       NewPN->addIncoming(DifferentOp1, BB1);
01258       NewPN->addIncoming(DifferentOp2, BB2);
01259       DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
01260     }
01261     PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
01262     MapValueFromBB1ToBB2.erase(I1);
01263 
01264     DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
01265     DEBUG(dbgs() << "                         " << *I2 << "\n";);
01266     // We need to update RE1 and RE2 if we are going to sink the first
01267     // instruction in the basic block down.
01268     bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
01269     // Sink the instruction.
01270     BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
01271     if (!OldPN->use_empty())
01272       OldPN->replaceAllUsesWith(I1);
01273     OldPN->eraseFromParent();
01274 
01275     if (!I2->use_empty())
01276       I2->replaceAllUsesWith(I1);
01277     I1->intersectOptionalDataWith(I2);
01278     I2->eraseFromParent();
01279 
01280     if (UpdateRE1)
01281       RE1 = BB1->getInstList().rend();
01282     if (UpdateRE2)
01283       RE2 = BB2->getInstList().rend();
01284     FirstNonPhiInBBEnd = I1;
01285     NumSinkCommons++;
01286     Changed = true;
01287   }
01288   return Changed;
01289 }
01290 
01291 /// \brief Determine if we can hoist sink a sole store instruction out of a
01292 /// conditional block.
01293 ///
01294 /// We are looking for code like the following:
01295 ///   BrBB:
01296 ///     store i32 %add, i32* %arrayidx2
01297 ///     ... // No other stores or function calls (we could be calling a memory
01298 ///     ... // function).
01299 ///     %cmp = icmp ult %x, %y
01300 ///     br i1 %cmp, label %EndBB, label %ThenBB
01301 ///   ThenBB:
01302 ///     store i32 %add5, i32* %arrayidx2
01303 ///     br label EndBB
01304 ///   EndBB:
01305 ///     ...
01306 ///   We are going to transform this into:
01307 ///   BrBB:
01308 ///     store i32 %add, i32* %arrayidx2
01309 ///     ... //
01310 ///     %cmp = icmp ult %x, %y
01311 ///     %add.add5 = select i1 %cmp, i32 %add, %add5
01312 ///     store i32 %add.add5, i32* %arrayidx2
01313 ///     ...
01314 ///
01315 /// \return The pointer to the value of the previous store if the store can be
01316 ///         hoisted into the predecessor block. 0 otherwise.
01317 static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
01318                                      BasicBlock *StoreBB, BasicBlock *EndBB) {
01319   StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
01320   if (!StoreToHoist)
01321     return 0;
01322 
01323   // Volatile or atomic.
01324   if (!StoreToHoist->isSimple())
01325     return 0;
01326 
01327   Value *StorePtr = StoreToHoist->getPointerOperand();
01328 
01329   // Look for a store to the same pointer in BrBB.
01330   unsigned MaxNumInstToLookAt = 10;
01331   for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
01332        RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
01333     Instruction *CurI = &*RI;
01334 
01335     // Could be calling an instruction that effects memory like free().
01336     if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
01337       return 0;
01338 
01339     StoreInst *SI = dyn_cast<StoreInst>(CurI);
01340     // Found the previous store make sure it stores to the same location.
01341     if (SI && SI->getPointerOperand() == StorePtr)
01342       // Found the previous store, return its value operand.
01343       return SI->getValueOperand();
01344     else if (SI)
01345       return 0; // Unknown store.
01346   }
01347 
01348   return 0;
01349 }
01350 
01351 /// \brief Speculate a conditional basic block flattening the CFG.
01352 ///
01353 /// Note that this is a very risky transform currently. Speculating
01354 /// instructions like this is most often not desirable. Instead, there is an MI
01355 /// pass which can do it with full awareness of the resource constraints.
01356 /// However, some cases are "obvious" and we should do directly. An example of
01357 /// this is speculating a single, reasonably cheap instruction.
01358 ///
01359 /// There is only one distinct advantage to flattening the CFG at the IR level:
01360 /// it makes very common but simplistic optimizations such as are common in
01361 /// instcombine and the DAG combiner more powerful by removing CFG edges and
01362 /// modeling their effects with easier to reason about SSA value graphs.
01363 ///
01364 ///
01365 /// An illustration of this transform is turning this IR:
01366 /// \code
01367 ///   BB:
01368 ///     %cmp = icmp ult %x, %y
01369 ///     br i1 %cmp, label %EndBB, label %ThenBB
01370 ///   ThenBB:
01371 ///     %sub = sub %x, %y
01372 ///     br label BB2
01373 ///   EndBB:
01374 ///     %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
01375 ///     ...
01376 /// \endcode
01377 ///
01378 /// Into this IR:
01379 /// \code
01380 ///   BB:
01381 ///     %cmp = icmp ult %x, %y
01382 ///     %sub = sub %x, %y
01383 ///     %cond = select i1 %cmp, 0, %sub
01384 ///     ...
01385 /// \endcode
01386 ///
01387 /// \returns true if the conditional block is removed.
01388 static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB) {
01389   // Be conservative for now. FP select instruction can often be expensive.
01390   Value *BrCond = BI->getCondition();
01391   if (isa<FCmpInst>(BrCond))
01392     return false;
01393 
01394   BasicBlock *BB = BI->getParent();
01395   BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
01396 
01397   // If ThenBB is actually on the false edge of the conditional branch, remember
01398   // to swap the select operands later.
01399   bool Invert = false;
01400   if (ThenBB != BI->getSuccessor(0)) {
01401     assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
01402     Invert = true;
01403   }
01404   assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
01405 
01406   // Keep a count of how many times instructions are used within CondBB when
01407   // they are candidates for sinking into CondBB. Specifically:
01408   // - They are defined in BB, and
01409   // - They have no side effects, and
01410   // - All of their uses are in CondBB.
01411   SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
01412 
01413   unsigned SpeculationCost = 0;
01414   Value *SpeculatedStoreValue = 0;
01415   StoreInst *SpeculatedStore = 0;
01416   for (BasicBlock::iterator BBI = ThenBB->begin(),
01417                             BBE = std::prev(ThenBB->end());
01418        BBI != BBE; ++BBI) {
01419     Instruction *I = BBI;
01420     // Skip debug info.
01421     if (isa<DbgInfoIntrinsic>(I))
01422       continue;
01423 
01424     // Only speculatively execution a single instruction (not counting the
01425     // terminator) for now.
01426     ++SpeculationCost;
01427     if (SpeculationCost > 1)
01428       return false;
01429 
01430     // Don't hoist the instruction if it's unsafe or expensive.
01431     if (!isSafeToSpeculativelyExecute(I) &&
01432         !(HoistCondStores &&
01433           (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
01434                                                          EndBB))))
01435       return false;
01436     if (!SpeculatedStoreValue &&
01437         ComputeSpeculationCost(I) > PHINodeFoldingThreshold)
01438       return false;
01439 
01440     // Store the store speculation candidate.
01441     if (SpeculatedStoreValue)
01442       SpeculatedStore = cast<StoreInst>(I);
01443 
01444     // Do not hoist the instruction if any of its operands are defined but not
01445     // used in BB. The transformation will prevent the operand from
01446     // being sunk into the use block.
01447     for (User::op_iterator i = I->op_begin(), e = I->op_end();
01448          i != e; ++i) {
01449       Instruction *OpI = dyn_cast<Instruction>(*i);
01450       if (!OpI || OpI->getParent() != BB ||
01451           OpI->mayHaveSideEffects())
01452         continue; // Not a candidate for sinking.
01453 
01454       ++SinkCandidateUseCounts[OpI];
01455     }
01456   }
01457 
01458   // Consider any sink candidates which are only used in CondBB as costs for
01459   // speculation. Note, while we iterate over a DenseMap here, we are summing
01460   // and so iteration order isn't significant.
01461   for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
01462            SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
01463        I != E; ++I)
01464     if (I->first->getNumUses() == I->second) {
01465       ++SpeculationCost;
01466       if (SpeculationCost > 1)
01467         return false;
01468     }
01469 
01470   // Check that the PHI nodes can be converted to selects.
01471   bool HaveRewritablePHIs = false;
01472   for (BasicBlock::iterator I = EndBB->begin();
01473        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01474     Value *OrigV = PN->getIncomingValueForBlock(BB);
01475     Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
01476 
01477     // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
01478     // Skip PHIs which are trivial.
01479     if (ThenV == OrigV)
01480       continue;
01481 
01482     HaveRewritablePHIs = true;
01483     ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
01484     ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
01485     if (!OrigCE && !ThenCE)
01486       continue; // Known safe and cheap.
01487 
01488     if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
01489         (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
01490       return false;
01491     unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE) : 0;
01492     unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE) : 0;
01493     if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
01494       return false;
01495 
01496     // Account for the cost of an unfolded ConstantExpr which could end up
01497     // getting expanded into Instructions.
01498     // FIXME: This doesn't account for how many operations are combined in the
01499     // constant expression.
01500     ++SpeculationCost;
01501     if (SpeculationCost > 1)
01502       return false;
01503   }
01504 
01505   // If there are no PHIs to process, bail early. This helps ensure idempotence
01506   // as well.
01507   if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
01508     return false;
01509 
01510   // If we get here, we can hoist the instruction and if-convert.
01511   DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
01512 
01513   // Insert a select of the value of the speculated store.
01514   if (SpeculatedStoreValue) {
01515     IRBuilder<true, NoFolder> Builder(BI);
01516     Value *TrueV = SpeculatedStore->getValueOperand();
01517     Value *FalseV = SpeculatedStoreValue;
01518     if (Invert)
01519       std::swap(TrueV, FalseV);
01520     Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
01521                                     "." + FalseV->getName());
01522     SpeculatedStore->setOperand(0, S);
01523   }
01524 
01525   // Hoist the instructions.
01526   BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
01527                            std::prev(ThenBB->end()));
01528 
01529   // Insert selects and rewrite the PHI operands.
01530   IRBuilder<true, NoFolder> Builder(BI);
01531   for (BasicBlock::iterator I = EndBB->begin();
01532        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
01533     unsigned OrigI = PN->getBasicBlockIndex(BB);
01534     unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
01535     Value *OrigV = PN->getIncomingValue(OrigI);
01536     Value *ThenV = PN->getIncomingValue(ThenI);
01537 
01538     // Skip PHIs which are trivial.
01539     if (OrigV == ThenV)
01540       continue;
01541 
01542     // Create a select whose true value is the speculatively executed value and
01543     // false value is the preexisting value. Swap them if the branch
01544     // destinations were inverted.
01545     Value *TrueV = ThenV, *FalseV = OrigV;
01546     if (Invert)
01547       std::swap(TrueV, FalseV);
01548     Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
01549                                     TrueV->getName() + "." + FalseV->getName());
01550     PN->setIncomingValue(OrigI, V);
01551     PN->setIncomingValue(ThenI, V);
01552   }
01553 
01554   ++NumSpeculations;
01555   return true;
01556 }
01557 
01558 /// \returns True if this block contains a CallInst with the NoDuplicate
01559 /// attribute.
01560 static bool HasNoDuplicateCall(const BasicBlock *BB) {
01561   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
01562     const CallInst *CI = dyn_cast<CallInst>(I);
01563     if (!CI)
01564       continue;
01565     if (CI->cannotDuplicate())
01566       return true;
01567   }
01568   return false;
01569 }
01570 
01571 /// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
01572 /// across this block.
01573 static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
01574   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
01575   unsigned Size = 0;
01576 
01577   for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
01578     if (isa<DbgInfoIntrinsic>(BBI))
01579       continue;
01580     if (Size > 10) return false;  // Don't clone large BB's.
01581     ++Size;
01582 
01583     // We can only support instructions that do not define values that are
01584     // live outside of the current basic block.
01585     for (User *U : BBI->users()) {
01586       Instruction *UI = cast<Instruction>(U);
01587       if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
01588     }
01589 
01590     // Looks ok, continue checking.
01591   }
01592 
01593   return true;
01594 }
01595 
01596 /// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
01597 /// that is defined in the same block as the branch and if any PHI entries are
01598 /// constants, thread edges corresponding to that entry to be branches to their
01599 /// ultimate destination.
01600 static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
01601   BasicBlock *BB = BI->getParent();
01602   PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
01603   // NOTE: we currently cannot transform this case if the PHI node is used
01604   // outside of the block.
01605   if (!PN || PN->getParent() != BB || !PN->hasOneUse())
01606     return false;
01607 
01608   // Degenerate case of a single entry PHI.
01609   if (PN->getNumIncomingValues() == 1) {
01610     FoldSingleEntryPHINodes(PN->getParent());
01611     return true;
01612   }
01613 
01614   // Now we know that this block has multiple preds and two succs.
01615   if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
01616 
01617   if (HasNoDuplicateCall(BB)) return false;
01618 
01619   // Okay, this is a simple enough basic block.  See if any phi values are
01620   // constants.
01621   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01622     ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
01623     if (CB == 0 || !CB->getType()->isIntegerTy(1)) continue;
01624 
01625     // Okay, we now know that all edges from PredBB should be revectored to
01626     // branch to RealDest.
01627     BasicBlock *PredBB = PN->getIncomingBlock(i);
01628     BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
01629 
01630     if (RealDest == BB) continue;  // Skip self loops.
01631     // Skip if the predecessor's terminator is an indirect branch.
01632     if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
01633 
01634     // The dest block might have PHI nodes, other predecessors and other
01635     // difficult cases.  Instead of being smart about this, just insert a new
01636     // block that jumps to the destination block, effectively splitting
01637     // the edge we are about to create.
01638     BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
01639                                             RealDest->getName()+".critedge",
01640                                             RealDest->getParent(), RealDest);
01641     BranchInst::Create(RealDest, EdgeBB);
01642 
01643     // Update PHI nodes.
01644     AddPredecessorToBlock(RealDest, EdgeBB, BB);
01645 
01646     // BB may have instructions that are being threaded over.  Clone these
01647     // instructions into EdgeBB.  We know that there will be no uses of the
01648     // cloned instructions outside of EdgeBB.
01649     BasicBlock::iterator InsertPt = EdgeBB->begin();
01650     DenseMap<Value*, Value*> TranslateMap;  // Track translated values.
01651     for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
01652       if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
01653         TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
01654         continue;
01655       }
01656       // Clone the instruction.
01657       Instruction *N = BBI->clone();
01658       if (BBI->hasName()) N->setName(BBI->getName()+".c");
01659 
01660       // Update operands due to translation.
01661       for (User::op_iterator i = N->op_begin(), e = N->op_end();
01662            i != e; ++i) {
01663         DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
01664         if (PI != TranslateMap.end())
01665           *i = PI->second;
01666       }
01667 
01668       // Check for trivial simplification.
01669       if (Value *V = SimplifyInstruction(N, DL)) {
01670         TranslateMap[BBI] = V;
01671         delete N;   // Instruction folded away, don't need actual inst
01672       } else {
01673         // Insert the new instruction into its new home.
01674         EdgeBB->getInstList().insert(InsertPt, N);
01675         if (!BBI->use_empty())
01676           TranslateMap[BBI] = N;
01677       }
01678     }
01679 
01680     // Loop over all of the edges from PredBB to BB, changing them to branch
01681     // to EdgeBB instead.
01682     TerminatorInst *PredBBTI = PredBB->getTerminator();
01683     for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
01684       if (PredBBTI->getSuccessor(i) == BB) {
01685         BB->removePredecessor(PredBB);
01686         PredBBTI->setSuccessor(i, EdgeBB);
01687       }
01688 
01689     // Recurse, simplifying any other constants.
01690     return FoldCondBranchOnPHI(BI, DL) | true;
01691   }
01692 
01693   return false;
01694 }
01695 
01696 /// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
01697 /// PHI node, see if we can eliminate it.
01698 static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
01699   // Ok, this is a two entry PHI node.  Check to see if this is a simple "if
01700   // statement", which has a very simple dominance structure.  Basically, we
01701   // are trying to find the condition that is being branched on, which
01702   // subsequently causes this merge to happen.  We really want control
01703   // dependence information for this check, but simplifycfg can't keep it up
01704   // to date, and this catches most of the cases we care about anyway.
01705   BasicBlock *BB = PN->getParent();
01706   BasicBlock *IfTrue, *IfFalse;
01707   Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
01708   if (!IfCond ||
01709       // Don't bother if the branch will be constant folded trivially.
01710       isa<ConstantInt>(IfCond))
01711     return false;
01712 
01713   // Okay, we found that we can merge this two-entry phi node into a select.
01714   // Doing so would require us to fold *all* two entry phi nodes in this block.
01715   // At some point this becomes non-profitable (particularly if the target
01716   // doesn't support cmov's).  Only do this transformation if there are two or
01717   // fewer PHI nodes in this block.
01718   unsigned NumPhis = 0;
01719   for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
01720     if (NumPhis > 2)
01721       return false;
01722 
01723   // Loop over the PHI's seeing if we can promote them all to select
01724   // instructions.  While we are at it, keep track of the instructions
01725   // that need to be moved to the dominating block.
01726   SmallPtrSet<Instruction*, 4> AggressiveInsts;
01727   unsigned MaxCostVal0 = PHINodeFoldingThreshold,
01728            MaxCostVal1 = PHINodeFoldingThreshold;
01729 
01730   for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
01731     PHINode *PN = cast<PHINode>(II++);
01732     if (Value *V = SimplifyInstruction(PN, DL)) {
01733       PN->replaceAllUsesWith(V);
01734       PN->eraseFromParent();
01735       continue;
01736     }
01737 
01738     if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
01739                              MaxCostVal0) ||
01740         !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
01741                              MaxCostVal1))
01742       return false;
01743   }
01744 
01745   // If we folded the first phi, PN dangles at this point.  Refresh it.  If
01746   // we ran out of PHIs then we simplified them all.
01747   PN = dyn_cast<PHINode>(BB->begin());
01748   if (PN == 0) return true;
01749 
01750   // Don't fold i1 branches on PHIs which contain binary operators.  These can
01751   // often be turned into switches and other things.
01752   if (PN->getType()->isIntegerTy(1) &&
01753       (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
01754        isa<BinaryOperator>(PN->getIncomingValue(1)) ||
01755        isa<BinaryOperator>(IfCond)))
01756     return false;
01757 
01758   // If we all PHI nodes are promotable, check to make sure that all
01759   // instructions in the predecessor blocks can be promoted as well.  If
01760   // not, we won't be able to get rid of the control flow, so it's not
01761   // worth promoting to select instructions.
01762   BasicBlock *DomBlock = 0;
01763   BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
01764   BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
01765   if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
01766     IfBlock1 = 0;
01767   } else {
01768     DomBlock = *pred_begin(IfBlock1);
01769     for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
01770       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
01771         // This is not an aggressive instruction that we can promote.
01772         // Because of this, we won't be able to get rid of the control
01773         // flow, so the xform is not worth it.
01774         return false;
01775       }
01776   }
01777 
01778   if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
01779     IfBlock2 = 0;
01780   } else {
01781     DomBlock = *pred_begin(IfBlock2);
01782     for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
01783       if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
01784         // This is not an aggressive instruction that we can promote.
01785         // Because of this, we won't be able to get rid of the control
01786         // flow, so the xform is not worth it.
01787         return false;
01788       }
01789   }
01790 
01791   DEBUG(dbgs() << "FOUND IF CONDITION!  " << *IfCond << "  T: "
01792                << IfTrue->getName() << "  F: " << IfFalse->getName() << "\n");
01793 
01794   // If we can still promote the PHI nodes after this gauntlet of tests,
01795   // do all of the PHI's now.
01796   Instruction *InsertPt = DomBlock->getTerminator();
01797   IRBuilder<true, NoFolder> Builder(InsertPt);
01798 
01799   // Move all 'aggressive' instructions, which are defined in the
01800   // conditional parts of the if's up to the dominating block.
01801   if (IfBlock1)
01802     DomBlock->getInstList().splice(InsertPt,
01803                                    IfBlock1->getInstList(), IfBlock1->begin(),
01804                                    IfBlock1->getTerminator());
01805   if (IfBlock2)
01806     DomBlock->getInstList().splice(InsertPt,
01807                                    IfBlock2->getInstList(), IfBlock2->begin(),
01808                                    IfBlock2->getTerminator());
01809 
01810   while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
01811     // Change the PHI node into a select instruction.
01812     Value *TrueVal  = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
01813     Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
01814 
01815     SelectInst *NV =
01816       cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
01817     PN->replaceAllUsesWith(NV);
01818     NV->takeName(PN);
01819     PN->eraseFromParent();
01820   }
01821 
01822   // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
01823   // has been flattened.  Change DomBlock to jump directly to our new block to
01824   // avoid other simplifycfg's kicking in on the diamond.
01825   TerminatorInst *OldTI = DomBlock->getTerminator();
01826   Builder.SetInsertPoint(OldTI);
01827   Builder.CreateBr(BB);
01828   OldTI->eraseFromParent();
01829   return true;
01830 }
01831 
01832 /// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
01833 /// to two returning blocks, try to merge them together into one return,
01834 /// introducing a select if the return values disagree.
01835 static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
01836                                            IRBuilder<> &Builder) {
01837   assert(BI->isConditional() && "Must be a conditional branch");
01838   BasicBlock *TrueSucc = BI->getSuccessor(0);
01839   BasicBlock *FalseSucc = BI->getSuccessor(1);
01840   ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
01841   ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
01842 
01843   // Check to ensure both blocks are empty (just a return) or optionally empty
01844   // with PHI nodes.  If there are other instructions, merging would cause extra
01845   // computation on one path or the other.
01846   if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
01847     return false;
01848   if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
01849     return false;
01850 
01851   Builder.SetInsertPoint(BI);
01852   // Okay, we found a branch that is going to two return nodes.  If
01853   // there is no return value for this function, just change the
01854   // branch into a return.
01855   if (FalseRet->getNumOperands() == 0) {
01856     TrueSucc->removePredecessor(BI->getParent());
01857     FalseSucc->removePredecessor(BI->getParent());
01858     Builder.CreateRetVoid();
01859     EraseTerminatorInstAndDCECond(BI);
01860     return true;
01861   }
01862 
01863   // Otherwise, figure out what the true and false return values are
01864   // so we can insert a new select instruction.
01865   Value *TrueValue = TrueRet->getReturnValue();
01866   Value *FalseValue = FalseRet->getReturnValue();
01867 
01868   // Unwrap any PHI nodes in the return blocks.
01869   if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
01870     if (TVPN->getParent() == TrueSucc)
01871       TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
01872   if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
01873     if (FVPN->getParent() == FalseSucc)
01874       FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
01875 
01876   // In order for this transformation to be safe, we must be able to
01877   // unconditionally execute both operands to the return.  This is
01878   // normally the case, but we could have a potentially-trapping
01879   // constant expression that prevents this transformation from being
01880   // safe.
01881   if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
01882     if (TCV->canTrap())
01883       return false;
01884   if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
01885     if (FCV->canTrap())
01886       return false;
01887 
01888   // Okay, we collected all the mapped values and checked them for sanity, and
01889   // defined to really do this transformation.  First, update the CFG.
01890   TrueSucc->removePredecessor(BI->getParent());
01891   FalseSucc->removePredecessor(BI->getParent());
01892 
01893   // Insert select instructions where needed.
01894   Value *BrCond = BI->getCondition();
01895   if (TrueValue) {
01896     // Insert a select if the results differ.
01897     if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
01898     } else if (isa<UndefValue>(TrueValue)) {
01899       TrueValue = FalseValue;
01900     } else {
01901       TrueValue = Builder.CreateSelect(BrCond, TrueValue,
01902                                        FalseValue, "retval");
01903     }
01904   }
01905 
01906   Value *RI = !TrueValue ?
01907     Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
01908 
01909   (void) RI;
01910 
01911   DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
01912                << "\n  " << *BI << "NewRet = " << *RI
01913                << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
01914 
01915   EraseTerminatorInstAndDCECond(BI);
01916 
01917   return true;
01918 }
01919 
01920 /// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
01921 /// probabilities of the branch taking each edge. Fills in the two APInt
01922 /// parameters and return true, or returns false if no or invalid metadata was
01923 /// found.
01924 static bool ExtractBranchMetadata(BranchInst *BI,
01925                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
01926   assert(BI->isConditional() &&
01927          "Looking for probabilities on unconditional branch?");
01928   MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
01929   if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
01930   ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
01931   ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
01932   if (!CITrue || !CIFalse) return false;
01933   ProbTrue = CITrue->getValue().getZExtValue();
01934   ProbFalse = CIFalse->getValue().getZExtValue();
01935   return true;
01936 }
01937 
01938 /// checkCSEInPredecessor - Return true if the given instruction is available
01939 /// in its predecessor block. If yes, the instruction will be removed.
01940 ///
01941 static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
01942   if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
01943     return false;
01944   for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
01945     Instruction *PBI = &*I;
01946     // Check whether Inst and PBI generate the same value.
01947     if (Inst->isIdenticalTo(PBI)) {
01948       Inst->replaceAllUsesWith(PBI);
01949       Inst->eraseFromParent();
01950       return true;
01951     }
01952   }
01953   return false;
01954 }
01955 
01956 /// FoldBranchToCommonDest - If this basic block is simple enough, and if a
01957 /// predecessor branches to us and one of our successors, fold the block into
01958 /// the predecessor and use logical operations to pick the right destination.
01959 bool llvm::FoldBranchToCommonDest(BranchInst *BI) {
01960   BasicBlock *BB = BI->getParent();
01961 
01962   Instruction *Cond = 0;
01963   if (BI->isConditional())
01964     Cond = dyn_cast<Instruction>(BI->getCondition());
01965   else {
01966     // For unconditional branch, check for a simple CFG pattern, where
01967     // BB has a single predecessor and BB's successor is also its predecessor's
01968     // successor. If such pattern exisits, check for CSE between BB and its
01969     // predecessor.
01970     if (BasicBlock *PB = BB->getSinglePredecessor())
01971       if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
01972         if (PBI->isConditional() &&
01973             (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
01974              BI->getSuccessor(0) == PBI->getSuccessor(1))) {
01975           for (BasicBlock::iterator I = BB->begin(), E = BB->end();
01976                I != E; ) {
01977             Instruction *Curr = I++;
01978             if (isa<CmpInst>(Curr)) {
01979               Cond = Curr;
01980               break;
01981             }
01982             // Quit if we can't remove this instruction.
01983             if (!checkCSEInPredecessor(Curr, PB))
01984               return false;
01985           }
01986         }
01987 
01988     if (Cond == 0)
01989       return false;
01990   }
01991 
01992   if (Cond == 0 || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
01993     Cond->getParent() != BB || !Cond->hasOneUse())
01994   return false;
01995 
01996   // Only allow this if the condition is a simple instruction that can be
01997   // executed unconditionally.  It must be in the same block as the branch, and
01998   // must be at the front of the block.
01999   BasicBlock::iterator FrontIt = BB->front();
02000 
02001   // Ignore dbg intrinsics.
02002   while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
02003 
02004   // Allow a single instruction to be hoisted in addition to the compare
02005   // that feeds the branch.  We later ensure that any values that _it_ uses
02006   // were also live in the predecessor, so that we don't unnecessarily create
02007   // register pressure or inhibit out-of-order execution.
02008   Instruction *BonusInst = 0;
02009   if (&*FrontIt != Cond &&
02010       FrontIt->hasOneUse() && FrontIt->user_back() == Cond &&
02011       isSafeToSpeculativelyExecute(FrontIt)) {
02012     BonusInst = &*FrontIt;
02013     ++FrontIt;
02014 
02015     // Ignore dbg intrinsics.
02016     while (isa<DbgInfoIntrinsic>(FrontIt)) ++FrontIt;
02017   }
02018 
02019   // Only a single bonus inst is allowed.
02020   if (&*FrontIt != Cond)
02021     return false;
02022 
02023   // Make sure the instruction after the condition is the cond branch.
02024   BasicBlock::iterator CondIt = Cond; ++CondIt;
02025 
02026   // Ingore dbg intrinsics.
02027   while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
02028 
02029   if (&*CondIt != BI)
02030     return false;
02031 
02032   // Cond is known to be a compare or binary operator.  Check to make sure that
02033   // neither operand is a potentially-trapping constant expression.
02034   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
02035     if (CE->canTrap())
02036       return false;
02037   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
02038     if (CE->canTrap())
02039       return false;
02040 
02041   // Finally, don't infinitely unroll conditional loops.
02042   BasicBlock *TrueDest  = BI->getSuccessor(0);
02043   BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : 0;
02044   if (TrueDest == BB || FalseDest == BB)
02045     return false;
02046 
02047   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
02048     BasicBlock *PredBlock = *PI;
02049     BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
02050 
02051     // Check that we have two conditional branches.  If there is a PHI node in
02052     // the common successor, verify that the same value flows in from both
02053     // blocks.
02054     SmallVector<PHINode*, 4> PHIs;
02055     if (PBI == 0 || PBI->isUnconditional() ||
02056         (BI->isConditional() &&
02057          !SafeToMergeTerminators(BI, PBI)) ||
02058         (!BI->isConditional() &&
02059          !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
02060       continue;
02061 
02062     // Determine if the two branches share a common destination.
02063     Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
02064     bool InvertPredCond = false;
02065 
02066     if (BI->isConditional()) {
02067       if (PBI->getSuccessor(0) == TrueDest)
02068         Opc = Instruction::Or;
02069       else if (PBI->getSuccessor(1) == FalseDest)
02070         Opc = Instruction::And;
02071       else if (PBI->getSuccessor(0) == FalseDest)
02072         Opc = Instruction::And, InvertPredCond = true;
02073       else if (PBI->getSuccessor(1) == TrueDest)
02074         Opc = Instruction::Or, InvertPredCond = true;
02075       else
02076         continue;
02077     } else {
02078       if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
02079         continue;
02080     }
02081 
02082     // Ensure that any values used in the bonus instruction are also used
02083     // by the terminator of the predecessor.  This means that those values
02084     // must already have been resolved, so we won't be inhibiting the
02085     // out-of-order core by speculating them earlier. We also allow
02086     // instructions that are used by the terminator's condition because it
02087     // exposes more merging opportunities.
02088     bool UsedByBranch = (BonusInst && BonusInst->hasOneUse() &&
02089                          BonusInst->user_back() == Cond);
02090 
02091     if (BonusInst && !UsedByBranch) {
02092       // Collect the values used by the bonus inst
02093       SmallPtrSet<Value*, 4> UsedValues;
02094       for (Instruction::op_iterator OI = BonusInst->op_begin(),
02095            OE = BonusInst->op_end(); OI != OE; ++OI) {
02096         Value *V = *OI;
02097         if (!isa<Constant>(V) && !isa<Argument>(V))
02098           UsedValues.insert(V);
02099       }
02100 
02101       SmallVector<std::pair<Value*, unsigned>, 4> Worklist;
02102       Worklist.push_back(std::make_pair(PBI->getOperand(0), 0));
02103 
02104       // Walk up to four levels back up the use-def chain of the predecessor's
02105       // terminator to see if all those values were used.  The choice of four
02106       // levels is arbitrary, to provide a compile-time-cost bound.
02107       while (!Worklist.empty()) {
02108         std::pair<Value*, unsigned> Pair = Worklist.back();
02109         Worklist.pop_back();
02110 
02111         if (Pair.second >= 4) continue;
02112         UsedValues.erase(Pair.first);
02113         if (UsedValues.empty()) break;
02114 
02115         if (Instruction *I = dyn_cast<Instruction>(Pair.first)) {
02116           for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
02117                OI != OE; ++OI)
02118             Worklist.push_back(std::make_pair(OI->get(), Pair.second+1));
02119         }
02120       }
02121 
02122       if (!UsedValues.empty()) return false;
02123     }
02124 
02125     DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
02126     IRBuilder<> Builder(PBI);
02127 
02128     // If we need to invert the condition in the pred block to match, do so now.
02129     if (InvertPredCond) {
02130       Value *NewCond = PBI->getCondition();
02131 
02132       if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
02133         CmpInst *CI = cast<CmpInst>(NewCond);
02134         CI->setPredicate(CI->getInversePredicate());
02135       } else {
02136         NewCond = Builder.CreateNot(NewCond,
02137                                     PBI->getCondition()->getName()+".not");
02138       }
02139 
02140       PBI->setCondition(NewCond);
02141       PBI->swapSuccessors();
02142     }
02143 
02144     // If we have a bonus inst, clone it into the predecessor block.
02145     Instruction *NewBonus = 0;
02146     if (BonusInst) {
02147       NewBonus = BonusInst->clone();
02148 
02149       // If we moved a load, we cannot any longer claim any knowledge about
02150       // its potential value. The previous information might have been valid
02151       // only given the branch precondition.
02152       // For an analogous reason, we must also drop all the metadata whose
02153       // semantics we don't understand.
02154       NewBonus->dropUnknownMetadata(LLVMContext::MD_dbg);
02155 
02156       PredBlock->getInstList().insert(PBI, NewBonus);
02157       NewBonus->takeName(BonusInst);
02158       BonusInst->setName(BonusInst->getName()+".old");
02159     }
02160 
02161     // Clone Cond into the predecessor basic block, and or/and the
02162     // two conditions together.
02163     Instruction *New = Cond->clone();
02164     if (BonusInst) New->replaceUsesOfWith(BonusInst, NewBonus);
02165     PredBlock->getInstList().insert(PBI, New);
02166     New->takeName(Cond);
02167     Cond->setName(New->getName()+".old");
02168 
02169     if (BI->isConditional()) {
02170       Instruction *NewCond =
02171         cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
02172                                             New, "or.cond"));
02173       PBI->setCondition(NewCond);
02174 
02175       uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
02176       bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
02177                                                   PredFalseWeight);
02178       bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
02179                                                   SuccFalseWeight);
02180       SmallVector<uint64_t, 8> NewWeights;
02181 
02182       if (PBI->getSuccessor(0) == BB) {
02183         if (PredHasWeights && SuccHasWeights) {
02184           // PBI: br i1 %x, BB, FalseDest
02185           // BI:  br i1 %y, TrueDest, FalseDest
02186           //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
02187           NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
02188           //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
02189           //               TrueWeight for PBI * FalseWeight for BI.
02190           // We assume that total weights of a BranchInst can fit into 32 bits.
02191           // Therefore, we will not have overflow using 64-bit arithmetic.
02192           NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
02193                SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
02194         }
02195         AddPredecessorToBlock(TrueDest, PredBlock, BB);
02196         PBI->setSuccessor(0, TrueDest);
02197       }
02198       if (PBI->getSuccessor(1) == BB) {
02199         if (PredHasWeights && SuccHasWeights) {
02200           // PBI: br i1 %x, TrueDest, BB
02201           // BI:  br i1 %y, TrueDest, FalseDest
02202           //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
02203           //              FalseWeight for PBI * TrueWeight for BI.
02204           NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
02205               SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
02206           //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
02207           NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
02208         }
02209         AddPredecessorToBlock(FalseDest, PredBlock, BB);
02210         PBI->setSuccessor(1, FalseDest);
02211       }
02212       if (NewWeights.size() == 2) {
02213         // Halve the weights if any of them cannot fit in an uint32_t
02214         FitWeights(NewWeights);
02215 
02216         SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
02217         PBI->setMetadata(LLVMContext::MD_prof,
02218                          MDBuilder(BI->getContext()).
02219                          createBranchWeights(MDWeights));
02220       } else
02221         PBI->setMetadata(LLVMContext::MD_prof, NULL);
02222     } else {
02223       // Update PHI nodes in the common successors.
02224       for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
02225         ConstantInt *PBI_C = cast<ConstantInt>(
02226           PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
02227         assert(PBI_C->getType()->isIntegerTy(1));
02228         Instruction *MergedCond = 0;
02229         if (PBI->getSuccessor(0) == TrueDest) {
02230           // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
02231           // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
02232           //       is false: !PBI_Cond and BI_Value
02233           Instruction *NotCond =
02234             cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
02235                                 "not.cond"));
02236           MergedCond =
02237             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
02238                                 NotCond, New,
02239                                 "and.cond"));
02240           if (PBI_C->isOne())
02241             MergedCond =
02242               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
02243                                   PBI->getCondition(), MergedCond,
02244                                   "or.cond"));
02245         } else {
02246           // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
02247           // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
02248           //       is false: PBI_Cond and BI_Value
02249           MergedCond =
02250             cast<Instruction>(Builder.CreateBinOp(Instruction::And,
02251                                 PBI->getCondition(), New,
02252                                 "and.cond"));
02253           if (PBI_C->isOne()) {
02254             Instruction *NotCond =
02255               cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
02256                                   "not.cond"));
02257             MergedCond =
02258               cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
02259                                   NotCond, MergedCond,
02260                                   "or.cond"));
02261           }
02262         }
02263         // Update PHI Node.
02264         PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
02265                                   MergedCond);
02266       }
02267       // Change PBI from Conditional to Unconditional.
02268       BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
02269       EraseTerminatorInstAndDCECond(PBI);
02270       PBI = New_PBI;
02271     }
02272 
02273     // TODO: If BB is reachable from all paths through PredBlock, then we
02274     // could replace PBI's branch probabilities with BI's.
02275 
02276     // Copy any debug value intrinsics into the end of PredBlock.
02277     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
02278       if (isa<DbgInfoIntrinsic>(*I))
02279         I->clone()->insertBefore(PBI);
02280 
02281     return true;
02282   }
02283   return false;
02284 }
02285 
02286 /// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
02287 /// predecessor of another block, this function tries to simplify it.  We know
02288 /// that PBI and BI are both conditional branches, and BI is in one of the
02289 /// successor blocks of PBI - PBI branches to BI.
02290 static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
02291   assert(PBI->isConditional() && BI->isConditional());
02292   BasicBlock *BB = BI->getParent();
02293 
02294   // If this block ends with a branch instruction, and if there is a
02295   // predecessor that ends on a branch of the same condition, make
02296   // this conditional branch redundant.
02297   if (PBI->getCondition() == BI->getCondition() &&
02298       PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
02299     // Okay, the outcome of this conditional branch is statically
02300     // knowable.  If this block had a single pred, handle specially.
02301     if (BB->getSinglePredecessor()) {
02302       // Turn this into a branch on constant.
02303       bool CondIsTrue = PBI->getSuccessor(0) == BB;
02304       BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
02305                                         CondIsTrue));
02306       return true;  // Nuke the branch on constant.
02307     }
02308 
02309     // Otherwise, if there are multiple predecessors, insert a PHI that merges
02310     // in the constant and simplify the block result.  Subsequent passes of
02311     // simplifycfg will thread the block.
02312     if (BlockIsSimpleEnoughToThreadThrough(BB)) {
02313       pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
02314       PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
02315                                        std::distance(PB, PE),
02316                                        BI->getCondition()->getName() + ".pr",
02317                                        BB->begin());
02318       // Okay, we're going to insert the PHI node.  Since PBI is not the only
02319       // predecessor, compute the PHI'd conditional value for all of the preds.
02320       // Any predecessor where the condition is not computable we keep symbolic.
02321       for (pred_iterator PI = PB; PI != PE; ++PI) {
02322         BasicBlock *P = *PI;
02323         if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
02324             PBI != BI && PBI->isConditional() &&
02325             PBI->getCondition() == BI->getCondition() &&
02326             PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
02327           bool CondIsTrue = PBI->getSuccessor(0) == BB;
02328           NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
02329                                               CondIsTrue), P);
02330         } else {
02331           NewPN->addIncoming(BI->getCondition(), P);
02332         }
02333       }
02334 
02335       BI->setCondition(NewPN);
02336       return true;
02337     }
02338   }
02339 
02340   // If this is a conditional branch in an empty block, and if any
02341   // predecessors is a conditional branch to one of our destinations,
02342   // fold the conditions into logical ops and one cond br.
02343   BasicBlock::iterator BBI = BB->begin();
02344   // Ignore dbg intrinsics.
02345   while (isa<DbgInfoIntrinsic>(BBI))
02346     ++BBI;
02347   if (&*BBI != BI)
02348     return false;
02349 
02350 
02351   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
02352     if (CE->canTrap())
02353       return false;
02354 
02355   int PBIOp, BIOp;
02356   if (PBI->getSuccessor(0) == BI->getSuccessor(0))
02357     PBIOp = BIOp = 0;
02358   else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
02359     PBIOp = 0, BIOp = 1;
02360   else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
02361     PBIOp = 1, BIOp = 0;
02362   else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
02363     PBIOp = BIOp = 1;
02364   else
02365     return false;
02366 
02367   // Check to make sure that the other destination of this branch
02368   // isn't BB itself.  If so, this is an infinite loop that will
02369   // keep getting unwound.
02370   if (PBI->getSuccessor(PBIOp) == BB)
02371     return false;
02372 
02373   // Do not perform this transformation if it would require
02374   // insertion of a large number of select instructions. For targets
02375   // without predication/cmovs, this is a big pessimization.
02376   BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
02377 
02378   unsigned NumPhis = 0;
02379   for (BasicBlock::iterator II = CommonDest->begin();
02380        isa<PHINode>(II); ++II, ++NumPhis)
02381     if (NumPhis > 2) // Disable this xform.
02382       return false;
02383 
02384   // Finally, if everything is ok, fold the branches to logical ops.
02385   BasicBlock *OtherDest  = BI->getSuccessor(BIOp ^ 1);
02386 
02387   DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
02388                << "AND: " << *BI->getParent());
02389 
02390 
02391   // If OtherDest *is* BB, then BB is a basic block with a single conditional
02392   // branch in it, where one edge (OtherDest) goes back to itself but the other
02393   // exits.  We don't *know* that the program avoids the infinite loop
02394   // (even though that seems likely).  If we do this xform naively, we'll end up
02395   // recursively unpeeling the loop.  Since we know that (after the xform is
02396   // done) that the block *is* infinite if reached, we just make it an obviously
02397   // infinite loop with no cond branch.
02398   if (OtherDest == BB) {
02399     // Insert it at the end of the function, because it's either code,
02400     // or it won't matter if it's hot. :)
02401     BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
02402                                                   "infloop", BB->getParent());
02403     BranchInst::Create(InfLoopBlock, InfLoopBlock);
02404     OtherDest = InfLoopBlock;
02405   }
02406 
02407   DEBUG(dbgs() << *PBI->getParent()->getParent());
02408 
02409   // BI may have other predecessors.  Because of this, we leave
02410   // it alone, but modify PBI.
02411 
02412   // Make sure we get to CommonDest on True&True directions.
02413   Value *PBICond = PBI->getCondition();
02414   IRBuilder<true, NoFolder> Builder(PBI);
02415   if (PBIOp)
02416     PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
02417 
02418   Value *BICond = BI->getCondition();
02419   if (BIOp)
02420     BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
02421 
02422   // Merge the conditions.
02423   Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
02424 
02425   // Modify PBI to branch on the new condition to the new dests.
02426   PBI->setCondition(Cond);
02427   PBI->setSuccessor(0, CommonDest);
02428   PBI->setSuccessor(1, OtherDest);
02429 
02430   // Update branch weight for PBI.
02431   uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
02432   bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
02433                                               PredFalseWeight);
02434   bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
02435                                               SuccFalseWeight);
02436   if (PredHasWeights && SuccHasWeights) {
02437     uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
02438     uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
02439     uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
02440     uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
02441     // The weight to CommonDest should be PredCommon * SuccTotal +
02442     //                                    PredOther * SuccCommon.
02443     // The weight to OtherDest should be PredOther * SuccOther.
02444     SmallVector<uint64_t, 2> NewWeights;
02445     NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
02446                          PredOther * SuccCommon);
02447     NewWeights.push_back(PredOther * SuccOther);
02448     // Halve the weights if any of them cannot fit in an uint32_t
02449     FitWeights(NewWeights);
02450 
02451     SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
02452     PBI->setMetadata(LLVMContext::MD_prof,
02453                      MDBuilder(BI->getContext()).
02454                      createBranchWeights(MDWeights));
02455   }
02456 
02457   // OtherDest may have phi nodes.  If so, add an entry from PBI's
02458   // block that are identical to the entries for BI's block.
02459   AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
02460 
02461   // We know that the CommonDest already had an edge from PBI to
02462   // it.  If it has PHIs though, the PHIs may have different
02463   // entries for BB and PBI's BB.  If so, insert a select to make
02464   // them agree.
02465   PHINode *PN;
02466   for (BasicBlock::iterator II = CommonDest->begin();
02467        (PN = dyn_cast<PHINode>(II)); ++II) {
02468     Value *BIV = PN->getIncomingValueForBlock(BB);
02469     unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
02470     Value *PBIV = PN->getIncomingValue(PBBIdx);
02471     if (BIV != PBIV) {
02472       // Insert a select in PBI to pick the right value.
02473       Value *NV = cast<SelectInst>
02474         (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
02475       PN->setIncomingValue(PBBIdx, NV);
02476     }
02477   }
02478 
02479   DEBUG(dbgs() << "INTO: " << *PBI->getParent());
02480   DEBUG(dbgs() << *PBI->getParent()->getParent());
02481 
02482   // This basic block is probably dead.  We know it has at least
02483   // one fewer predecessor.
02484   return true;
02485 }
02486 
02487 // SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
02488 // branch to TrueBB if Cond is true or to FalseBB if Cond is false.
02489 // Takes care of updating the successors and removing the old terminator.
02490 // Also makes sure not to introduce new successors by assuming that edges to
02491 // non-successor TrueBBs and FalseBBs aren't reachable.
02492 static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
02493                                        BasicBlock *TrueBB, BasicBlock *FalseBB,
02494                                        uint32_t TrueWeight,
02495                                        uint32_t FalseWeight){
02496   // Remove any superfluous successor edges from the CFG.
02497   // First, figure out which successors to preserve.
02498   // If TrueBB and FalseBB are equal, only try to preserve one copy of that
02499   // successor.
02500   BasicBlock *KeepEdge1 = TrueBB;
02501   BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : 0;
02502 
02503   // Then remove the rest.
02504   for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
02505     BasicBlock *Succ = OldTerm->getSuccessor(I);
02506     // Make sure only to keep exactly one copy of each edge.
02507     if (Succ == KeepEdge1)
02508       KeepEdge1 = 0;
02509     else if (Succ == KeepEdge2)
02510       KeepEdge2 = 0;
02511     else
02512       Succ->removePredecessor(OldTerm->getParent());
02513   }
02514 
02515   IRBuilder<> Builder(OldTerm);
02516   Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
02517 
02518   // Insert an appropriate new terminator.
02519   if ((KeepEdge1 == 0) && (KeepEdge2 == 0)) {
02520     if (TrueBB == FalseBB)
02521       // We were only looking for one successor, and it was present.
02522       // Create an unconditional branch to it.
02523       Builder.CreateBr(TrueBB);
02524     else {
02525       // We found both of the successors we were looking for.
02526       // Create a conditional branch sharing the condition of the select.
02527       BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
02528       if (TrueWeight != FalseWeight)
02529         NewBI->setMetadata(LLVMContext::MD_prof,
02530                            MDBuilder(OldTerm->getContext()).
02531                            createBranchWeights(TrueWeight, FalseWeight));
02532     }
02533   } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
02534     // Neither of the selected blocks were successors, so this
02535     // terminator must be unreachable.
02536     new UnreachableInst(OldTerm->getContext(), OldTerm);
02537   } else {
02538     // One of the selected values was a successor, but the other wasn't.
02539     // Insert an unconditional branch to the one that was found;
02540     // the edge to the one that wasn't must be unreachable.
02541     if (KeepEdge1 == 0)
02542       // Only TrueBB was found.
02543       Builder.CreateBr(TrueBB);
02544     else
02545       // Only FalseBB was found.
02546       Builder.CreateBr(FalseBB);
02547   }
02548 
02549   EraseTerminatorInstAndDCECond(OldTerm);
02550   return true;
02551 }
02552 
02553 // SimplifySwitchOnSelect - Replaces
02554 //   (switch (select cond, X, Y)) on constant X, Y
02555 // with a branch - conditional if X and Y lead to distinct BBs,
02556 // unconditional otherwise.
02557 static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
02558   // Check for constant integer values in the select.
02559   ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
02560   ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
02561   if (!TrueVal || !FalseVal)
02562     return false;
02563 
02564   // Find the relevant condition and destinations.
02565   Value *Condition = Select->getCondition();
02566   BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
02567   BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
02568 
02569   // Get weight for TrueBB and FalseBB.
02570   uint32_t TrueWeight = 0, FalseWeight = 0;
02571   SmallVector<uint64_t, 8> Weights;
02572   bool HasWeights = HasBranchWeights(SI);
02573   if (HasWeights) {
02574     GetBranchWeights(SI, Weights);
02575     if (Weights.size() == 1 + SI->getNumCases()) {
02576       TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
02577                                      getSuccessorIndex()];
02578       FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
02579                                       getSuccessorIndex()];
02580     }
02581   }
02582 
02583   // Perform the actual simplification.
02584   return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
02585                                     TrueWeight, FalseWeight);
02586 }
02587 
02588 // SimplifyIndirectBrOnSelect - Replaces
02589 //   (indirectbr (select cond, blockaddress(@fn, BlockA),
02590 //                             blockaddress(@fn, BlockB)))
02591 // with
02592 //   (br cond, BlockA, BlockB).
02593 static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
02594   // Check that both operands of the select are block addresses.
02595   BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
02596   BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
02597   if (!TBA || !FBA)
02598     return false;
02599 
02600   // Extract the actual blocks.
02601   BasicBlock *TrueBB = TBA->getBasicBlock();
02602   BasicBlock *FalseBB = FBA->getBasicBlock();
02603 
02604   // Perform the actual simplification.
02605   return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
02606                                     0, 0);
02607 }
02608 
02609 /// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
02610 /// instruction (a seteq/setne with a constant) as the only instruction in a
02611 /// block that ends with an uncond branch.  We are looking for a very specific
02612 /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified.  In
02613 /// this case, we merge the first two "or's of icmp" into a switch, but then the
02614 /// default value goes to an uncond block with a seteq in it, we get something
02615 /// like:
02616 ///
02617 ///   switch i8 %A, label %DEFAULT [ i8 1, label %end    i8 2, label %end ]
02618 /// DEFAULT:
02619 ///   %tmp = icmp eq i8 %A, 92
02620 ///   br label %end
02621 /// end:
02622 ///   ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
02623 ///
02624 /// We prefer to split the edge to 'end' so that there is a true/false entry to
02625 /// the PHI, merging the third icmp into the switch.
02626 static bool TryToSimplifyUncondBranchWithICmpInIt(
02627     ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
02628     const DataLayout *DL) {
02629   BasicBlock *BB = ICI->getParent();
02630 
02631   // If the block has any PHIs in it or the icmp has multiple uses, it is too
02632   // complex.
02633   if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
02634 
02635   Value *V = ICI->getOperand(0);
02636   ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
02637 
02638   // The pattern we're looking for is where our only predecessor is a switch on
02639   // 'V' and this block is the default case for the switch.  In this case we can
02640   // fold the compared value into the switch to simplify things.
02641   BasicBlock *Pred = BB->getSinglePredecessor();
02642   if (Pred == 0 || !isa<SwitchInst>(Pred->getTerminator())) return false;
02643 
02644   SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
02645   if (SI->getCondition() != V)
02646     return false;
02647 
02648   // If BB is reachable on a non-default case, then we simply know the value of
02649   // V in this block.  Substitute it and constant fold the icmp instruction
02650   // away.
02651   if (SI->getDefaultDest() != BB) {
02652     ConstantInt *VVal = SI->findCaseDest(BB);
02653     assert(VVal && "Should have a unique destination value");
02654     ICI->setOperand(0, VVal);
02655 
02656     if (Value *V = SimplifyInstruction(ICI, DL)) {
02657       ICI->replaceAllUsesWith(V);
02658       ICI->eraseFromParent();
02659     }
02660     // BB is now empty, so it is likely to simplify away.
02661     return SimplifyCFG(BB, TTI, DL) | true;
02662   }
02663 
02664   // Ok, the block is reachable from the default dest.  If the constant we're
02665   // comparing exists in one of the other edges, then we can constant fold ICI
02666   // and zap it.
02667   if (SI->findCaseValue(Cst) != SI->case_default()) {
02668     Value *V;
02669     if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
02670       V = ConstantInt::getFalse(BB->getContext());
02671     else
02672       V = ConstantInt::getTrue(BB->getContext());
02673 
02674     ICI->replaceAllUsesWith(V);
02675     ICI->eraseFromParent();
02676     // BB is now empty, so it is likely to simplify away.
02677     return SimplifyCFG(BB, TTI, DL) | true;
02678   }
02679 
02680   // The use of the icmp has to be in the 'end' block, by the only PHI node in
02681   // the block.
02682   BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
02683   PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
02684   if (PHIUse == 0 || PHIUse != &SuccBlock->front() ||
02685       isa<PHINode>(++BasicBlock::iterator(PHIUse)))
02686     return false;
02687 
02688   // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
02689   // true in the PHI.
02690   Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
02691   Constant *NewCst     = ConstantInt::getFalse(BB->getContext());
02692 
02693   if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
02694     std::swap(DefaultCst, NewCst);
02695 
02696   // Replace ICI (which is used by the PHI for the default value) with true or
02697   // false depending on if it is EQ or NE.
02698   ICI->replaceAllUsesWith(DefaultCst);
02699   ICI->eraseFromParent();
02700 
02701   // Okay, the switch goes to this block on a default value.  Add an edge from
02702   // the switch to the merge point on the compared value.
02703   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
02704                                          BB->getParent(), BB);
02705   SmallVector<uint64_t, 8> Weights;
02706   bool HasWeights = HasBranchWeights(SI);
02707   if (HasWeights) {
02708     GetBranchWeights(SI, Weights);
02709     if (Weights.size() == 1 + SI->getNumCases()) {
02710       // Split weight for default case to case for "Cst".
02711       Weights[0] = (Weights[0]+1) >> 1;
02712       Weights.push_back(Weights[0]);
02713 
02714       SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
02715       SI->setMetadata(LLVMContext::MD_prof,
02716                       MDBuilder(SI->getContext()).
02717                       createBranchWeights(MDWeights));
02718     }
02719   }
02720   SI->addCase(Cst, NewBB);
02721 
02722   // NewBB branches to the phi block, add the uncond branch and the phi entry.
02723   Builder.SetInsertPoint(NewBB);
02724   Builder.SetCurrentDebugLocation(SI->getDebugLoc());
02725   Builder.CreateBr(SuccBlock);
02726   PHIUse->addIncoming(NewCst, NewBB);
02727   return true;
02728 }
02729 
02730 /// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
02731 /// Check to see if it is branching on an or/and chain of icmp instructions, and
02732 /// fold it into a switch instruction if so.
02733 static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
02734                                       IRBuilder<> &Builder) {
02735   Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
02736   if (Cond == 0) return false;
02737 
02738 
02739   // Change br (X == 0 | X == 1), T, F into a switch instruction.
02740   // If this is a bunch of seteq's or'd together, or if it's a bunch of
02741   // 'setne's and'ed together, collect them.
02742   Value *CompVal = 0;
02743   std::vector<ConstantInt*> Values;
02744   bool TrueWhenEqual = true;
02745   Value *ExtraCase = 0;
02746   unsigned UsedICmps = 0;
02747 
02748   if (Cond->getOpcode() == Instruction::Or) {
02749     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
02750                                      UsedICmps);
02751   } else if (Cond->getOpcode() == Instruction::And) {
02752     CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
02753                                      UsedICmps);
02754     TrueWhenEqual = false;
02755   }
02756 
02757   // If we didn't have a multiply compared value, fail.
02758   if (CompVal == 0) return false;
02759 
02760   // Avoid turning single icmps into a switch.
02761   if (UsedICmps <= 1)
02762     return false;
02763 
02764   // There might be duplicate constants in the list, which the switch
02765   // instruction can't handle, remove them now.
02766   array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
02767   Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
02768 
02769   // If Extra was used, we require at least two switch values to do the
02770   // transformation.  A switch with one value is just an cond branch.
02771   if (ExtraCase && Values.size() < 2) return false;
02772 
02773   // TODO: Preserve branch weight metadata, similarly to how
02774   // FoldValueComparisonIntoPredecessors preserves it.
02775 
02776   // Figure out which block is which destination.
02777   BasicBlock *DefaultBB = BI->getSuccessor(1);
02778   BasicBlock *EdgeBB    = BI->getSuccessor(0);
02779   if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
02780 
02781   BasicBlock *BB = BI->getParent();
02782 
02783   DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
02784                << " cases into SWITCH.  BB is:\n" << *BB);
02785 
02786   // If there are any extra values that couldn't be folded into the switch
02787   // then we evaluate them with an explicit branch first.  Split the block
02788   // right before the condbr to handle it.
02789   if (ExtraCase) {
02790     BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
02791     // Remove the uncond branch added to the old block.
02792     TerminatorInst *OldTI = BB->getTerminator();
02793     Builder.SetInsertPoint(OldTI);
02794 
02795     if (TrueWhenEqual)
02796       Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
02797     else
02798       Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
02799 
02800     OldTI->eraseFromParent();
02801 
02802     // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
02803     // for the edge we just added.
02804     AddPredecessorToBlock(EdgeBB, BB, NewBB);
02805 
02806     DEBUG(dbgs() << "  ** 'icmp' chain unhandled condition: " << *ExtraCase
02807           << "\nEXTRABB = " << *BB);
02808     BB = NewBB;
02809   }
02810 
02811   Builder.SetInsertPoint(BI);
02812   // Convert pointer to int before we switch.
02813   if (CompVal->getType()->isPointerTy()) {
02814     assert(DL && "Cannot switch on pointer without DataLayout");
02815     CompVal = Builder.CreatePtrToInt(CompVal,
02816                                      DL->getIntPtrType(CompVal->getType()),
02817                                      "magicptr");
02818   }
02819 
02820   // Create the new switch instruction now.
02821   SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
02822 
02823   // Add all of the 'cases' to the switch instruction.
02824   for (unsigned i = 0, e = Values.size(); i != e; ++i)
02825     New->addCase(Values[i], EdgeBB);
02826 
02827   // We added edges from PI to the EdgeBB.  As such, if there were any
02828   // PHI nodes in EdgeBB, they need entries to be added corresponding to
02829   // the number of edges added.
02830   for (BasicBlock::iterator BBI = EdgeBB->begin();
02831        isa<PHINode>(BBI); ++BBI) {
02832     PHINode *PN = cast<PHINode>(BBI);
02833     Value *InVal = PN->getIncomingValueForBlock(BB);
02834     for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
02835       PN->addIncoming(InVal, BB);
02836   }
02837 
02838   // Erase the old branch instruction.
02839   EraseTerminatorInstAndDCECond(BI);
02840 
02841   DEBUG(dbgs() << "  ** 'icmp' chain result is:\n" << *BB << '\n');
02842   return true;
02843 }
02844 
02845 bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
02846   // If this is a trivial landing pad that just continues unwinding the caught
02847   // exception then zap the landing pad, turning its invokes into calls.
02848   BasicBlock *BB = RI->getParent();
02849   LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
02850   if (RI->getValue() != LPInst)
02851     // Not a landing pad, or the resume is not unwinding the exception that
02852     // caused control to branch here.
02853     return false;
02854 
02855   // Check that there are no other instructions except for debug intrinsics.
02856   BasicBlock::iterator I = LPInst, E = RI;
02857   while (++I != E)
02858     if (!isa<DbgInfoIntrinsic>(I))
02859       return false;
02860 
02861   // Turn all invokes that unwind here into calls and delete the basic block.
02862   bool InvokeRequiresTableEntry = false;
02863   bool Changed = false;
02864   for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
02865     InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
02866 
02867     if (II->hasFnAttr(Attribute::UWTable)) {
02868       // Don't remove an `invoke' instruction if the ABI requires an entry into
02869       // the table.
02870       InvokeRequiresTableEntry = true;
02871       continue;
02872     }
02873 
02874     SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
02875 
02876     // Insert a call instruction before the invoke.
02877     CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
02878     Call->takeName(II);
02879     Call->setCallingConv(II->getCallingConv());
02880     Call->setAttributes(II->getAttributes());
02881     Call->setDebugLoc(II->getDebugLoc());
02882 
02883     // Anything that used the value produced by the invoke instruction now uses
02884     // the value produced by the call instruction.  Note that we do this even
02885     // for void functions and calls with no uses so that the callgraph edge is
02886     // updated.
02887     II->replaceAllUsesWith(Call);
02888     BB->removePredecessor(II->getParent());
02889 
02890     // Insert a branch to the normal destination right before the invoke.
02891     BranchInst::Create(II->getNormalDest(), II);
02892 
02893     // Finally, delete the invoke instruction!
02894     II->eraseFromParent();
02895     Changed = true;
02896   }
02897 
02898   if (!InvokeRequiresTableEntry)
02899     // The landingpad is now unreachable.  Zap it.
02900     BB->eraseFromParent();
02901 
02902   return Changed;
02903 }
02904 
02905 bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
02906   BasicBlock *BB = RI->getParent();
02907   if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
02908 
02909   // Find predecessors that end with branches.
02910   SmallVector<BasicBlock*, 8> UncondBranchPreds;
02911   SmallVector<BranchInst*, 8> CondBranchPreds;
02912   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
02913     BasicBlock *P = *PI;
02914     TerminatorInst *PTI = P->getTerminator();
02915     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
02916       if (BI->isUnconditional())
02917         UncondBranchPreds.push_back(P);
02918       else
02919         CondBranchPreds.push_back(BI);
02920     }
02921   }
02922 
02923   // If we found some, do the transformation!
02924   if (!UncondBranchPreds.empty() && DupRet) {
02925     while (!UncondBranchPreds.empty()) {
02926       BasicBlock *Pred = UncondBranchPreds.pop_back_val();
02927       DEBUG(dbgs() << "FOLDING: " << *BB
02928             << "INTO UNCOND BRANCH PRED: " << *Pred);
02929       (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
02930     }
02931 
02932     // If we eliminated all predecessors of the block, delete the block now.
02933     if (pred_begin(BB) == pred_end(BB))
02934       // We know there are no successors, so just nuke the block.
02935       BB->eraseFromParent();
02936 
02937     return true;
02938   }
02939 
02940   // Check out all of the conditional branches going to this return
02941   // instruction.  If any of them just select between returns, change the
02942   // branch itself into a select/return pair.
02943   while (!CondBranchPreds.empty()) {
02944     BranchInst *BI = CondBranchPreds.pop_back_val();
02945 
02946     // Check to see if the non-BB successor is also a return block.
02947     if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
02948         isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
02949         SimplifyCondBranchToTwoReturns(BI, Builder))
02950       return true;
02951   }
02952   return false;
02953 }
02954 
02955 bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
02956   BasicBlock *BB = UI->getParent();
02957 
02958   bool Changed = false;
02959 
02960   // If there are any instructions immediately before the unreachable that can
02961   // be removed, do so.
02962   while (UI != BB->begin()) {
02963     BasicBlock::iterator BBI = UI;
02964     --BBI;
02965     // Do not delete instructions that can have side effects which might cause
02966     // the unreachable to not be reachable; specifically, calls and volatile
02967     // operations may have this effect.
02968     if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
02969 
02970     if (BBI->mayHaveSideEffects()) {
02971       if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
02972         if (SI->isVolatile())
02973           break;
02974       } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
02975         if (LI->isVolatile())
02976           break;
02977       } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
02978         if (RMWI->isVolatile())
02979           break;
02980       } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
02981         if (CXI->isVolatile())
02982           break;
02983       } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
02984                  !isa<LandingPadInst>(BBI)) {
02985         break;
02986       }
02987       // Note that deleting LandingPad's here is in fact okay, although it
02988       // involves a bit of subtle reasoning. If this inst is a LandingPad,
02989       // all the predecessors of this block will be the unwind edges of Invokes,
02990       // and we can therefore guarantee this block will be erased.
02991     }
02992 
02993     // Delete this instruction (any uses are guaranteed to be dead)
02994     if (!BBI->use_empty())
02995       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
02996     BBI->eraseFromParent();
02997     Changed = true;
02998   }
02999 
03000   // If the unreachable instruction is the first in the block, take a gander
03001   // at all of the predecessors of this instruction, and simplify them.
03002   if (&BB->front() != UI) return Changed;
03003 
03004   SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
03005   for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
03006     TerminatorInst *TI = Preds[i]->getTerminator();
03007     IRBuilder<> Builder(TI);
03008     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
03009       if (BI->isUnconditional()) {
03010         if (BI->getSuccessor(0) == BB) {
03011           new UnreachableInst(TI->getContext(), TI);
03012           TI->eraseFromParent();
03013           Changed = true;
03014         }
03015       } else {
03016         if (BI->getSuccessor(0) == BB) {
03017           Builder.CreateBr(BI->getSuccessor(1));
03018           EraseTerminatorInstAndDCECond(BI);
03019         } else if (BI->getSuccessor(1) == BB) {
03020           Builder.CreateBr(BI->getSuccessor(0));
03021           EraseTerminatorInstAndDCECond(BI);
03022           Changed = true;
03023         }
03024       }
03025     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
03026       for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
03027            i != e; ++i)
03028         if (i.getCaseSuccessor() == BB) {
03029           BB->removePredecessor(SI->getParent());
03030           SI->removeCase(i);
03031           --i; --e;
03032           Changed = true;
03033         }
03034       // If the default value is unreachable, figure out the most popular
03035       // destination and make it the default.
03036       if (SI->getDefaultDest() == BB) {
03037         std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
03038         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
03039              i != e; ++i) {
03040           std::pair<unsigned, unsigned> &entry =
03041               Popularity[i.getCaseSuccessor()];
03042           if (entry.first == 0) {
03043             entry.first = 1;
03044             entry.second = i.getCaseIndex();
03045           } else {
03046             entry.first++;
03047           }
03048         }
03049 
03050         // Find the most popular block.
03051         unsigned MaxPop = 0;
03052         unsigned MaxIndex = 0;
03053         BasicBlock *MaxBlock = 0;
03054         for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
03055              I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
03056           if (I->second.first > MaxPop ||
03057               (I->second.first == MaxPop && MaxIndex > I->second.second)) {
03058             MaxPop = I->second.first;
03059             MaxIndex = I->second.second;
03060             MaxBlock = I->first;
03061           }
03062         }
03063         if (MaxBlock) {
03064           // Make this the new default, allowing us to delete any explicit
03065           // edges to it.
03066           SI->setDefaultDest(MaxBlock);
03067           Changed = true;
03068 
03069           // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
03070           // it.
03071           if (isa<PHINode>(MaxBlock->begin()))
03072             for (unsigned i = 0; i != MaxPop-1; ++i)
03073               MaxBlock->removePredecessor(SI->getParent());
03074 
03075           for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
03076                i != e; ++i)
03077             if (i.getCaseSuccessor() == MaxBlock) {
03078               SI->removeCase(i);
03079               --i; --e;
03080             }
03081         }
03082       }
03083     } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
03084       if (II->getUnwindDest() == BB) {
03085         // Convert the invoke to a call instruction.  This would be a good
03086         // place to note that the call does not throw though.
03087         BranchInst *BI = Builder.CreateBr(II->getNormalDest());
03088         II->removeFromParent();   // Take out of symbol table
03089 
03090         // Insert the call now...
03091         SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
03092         Builder.SetInsertPoint(BI);
03093         CallInst *CI = Builder.CreateCall(II->getCalledValue(),
03094                                           Args, II->getName());
03095         CI->setCallingConv(II->getCallingConv());
03096         CI->setAttributes(II->getAttributes());
03097         // If the invoke produced a value, the call does now instead.
03098         II->replaceAllUsesWith(CI);
03099         delete II;
03100         Changed = true;
03101       }
03102     }
03103   }
03104 
03105   // If this block is now dead, remove it.
03106   if (pred_begin(BB) == pred_end(BB) &&
03107       BB != &BB->getParent()->getEntryBlock()) {
03108     // We know there are no successors, so just nuke the block.
03109     BB->eraseFromParent();
03110     return true;
03111   }
03112 
03113   return Changed;
03114 }
03115 
03116 /// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
03117 /// integer range comparison into a sub, an icmp and a branch.
03118 static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
03119   assert(SI->getNumCases() > 1 && "Degenerate switch?");
03120 
03121   // Make sure all cases point to the same destination and gather the values.
03122   SmallVector<ConstantInt *, 16> Cases;
03123   SwitchInst::CaseIt I = SI->case_begin();
03124   Cases.push_back(I.getCaseValue());
03125   SwitchInst::CaseIt PrevI = I++;
03126   for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
03127     if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
03128       return false;
03129     Cases.push_back(I.getCaseValue());
03130   }
03131   assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
03132 
03133   // Sort the case values, then check if they form a range we can transform.
03134   array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
03135   for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
03136     if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
03137       return false;
03138   }
03139 
03140   Constant *Offset = ConstantExpr::getNeg(Cases.back());
03141   Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
03142 
03143   Value *Sub = SI->getCondition();
03144   if (!Offset->isNullValue())
03145     Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
03146   Value *Cmp;
03147   // If NumCases overflowed, then all possible values jump to the successor.
03148   if (NumCases->isNullValue() && SI->getNumCases() != 0)
03149     Cmp = ConstantInt::getTrue(SI->getContext());
03150   else
03151     Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
03152   BranchInst *NewBI = Builder.CreateCondBr(
03153       Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
03154 
03155   // Update weight for the newly-created conditional branch.
03156   SmallVector<uint64_t, 8> Weights;
03157   bool HasWeights = HasBranchWeights(SI);
03158   if (HasWeights) {
03159     GetBranchWeights(SI, Weights);
03160     if (Weights.size() == 1 + SI->getNumCases()) {
03161       // Combine all weights for the cases to be the true weight of NewBI.
03162       // We assume that the sum of all weights for a Terminator can fit into 32
03163       // bits.
03164       uint32_t NewTrueWeight = 0;
03165       for (unsigned I = 1, E = Weights.size(); I != E; ++I)
03166         NewTrueWeight += (uint32_t)Weights[I];
03167       NewBI->setMetadata(LLVMContext::MD_prof,
03168                          MDBuilder(SI->getContext()).
03169                          createBranchWeights(NewTrueWeight,
03170                                              (uint32_t)Weights[0]));
03171     }
03172   }
03173 
03174   // Prune obsolete incoming values off the successor's PHI nodes.
03175   for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
03176        isa<PHINode>(BBI); ++BBI) {
03177     for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
03178       cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
03179   }
03180   SI->eraseFromParent();
03181 
03182   return true;
03183 }
03184 
03185 /// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
03186 /// and use it to remove dead cases.
03187 static bool EliminateDeadSwitchCases(SwitchInst *SI) {
03188   Value *Cond = SI->getCondition();
03189   unsigned Bits = Cond->getType()->getIntegerBitWidth();
03190   APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
03191   ComputeMaskedBits(Cond, KnownZero, KnownOne);
03192 
03193   // Gather dead cases.
03194   SmallVector<ConstantInt*, 8> DeadCases;
03195   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
03196     if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
03197         (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
03198       DeadCases.push_back(I.getCaseValue());
03199       DEBUG(dbgs() << "SimplifyCFG: switch case '"
03200                    << I.getCaseValue() << "' is dead.\n");
03201     }
03202   }
03203 
03204   SmallVector<uint64_t, 8> Weights;
03205   bool HasWeight = HasBranchWeights(SI);
03206   if (HasWeight) {
03207     GetBranchWeights(SI, Weights);
03208     HasWeight = (Weights.size() == 1 + SI->getNumCases());
03209   }
03210 
03211   // Remove dead cases from the switch.
03212   for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
03213     SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
03214     assert(Case != SI->case_default() &&
03215            "Case was not found. Probably mistake in DeadCases forming.");
03216     if (HasWeight) {
03217       std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
03218       Weights.pop_back();
03219     }
03220 
03221     // Prune unused values from PHI nodes.
03222     Case.getCaseSuccessor()->removePredecessor(SI->getParent());
03223     SI->removeCase(Case);
03224   }
03225   if (HasWeight && Weights.size() >= 2) {
03226     SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
03227     SI->setMetadata(LLVMContext::MD_prof,
03228                     MDBuilder(SI->getParent()->getContext()).
03229                     createBranchWeights(MDWeights));
03230   }
03231 
03232   return !DeadCases.empty();
03233 }
03234 
03235 /// FindPHIForConditionForwarding - If BB would be eligible for simplification
03236 /// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
03237 /// by an unconditional branch), look at the phi node for BB in the successor
03238 /// block and see if the incoming value is equal to CaseValue. If so, return
03239 /// the phi node, and set PhiIndex to BB's index in the phi node.
03240 static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
03241                                               BasicBlock *BB,
03242                                               int *PhiIndex) {
03243   if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
03244     return NULL; // BB must be empty to be a candidate for simplification.
03245   if (!BB->getSinglePredecessor())
03246     return NULL; // BB must be dominated by the switch.
03247 
03248   BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
03249   if (!Branch || !Branch->isUnconditional())
03250     return NULL; // Terminator must be unconditional branch.
03251 
03252   BasicBlock *Succ = Branch->getSuccessor(0);
03253 
03254   BasicBlock::iterator I = Succ->begin();
03255   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
03256     int Idx = PHI->getBasicBlockIndex(BB);
03257     assert(Idx >= 0 && "PHI has no entry for predecessor?");
03258 
03259     Value *InValue = PHI->getIncomingValue(Idx);
03260     if (InValue != CaseValue) continue;
03261 
03262     *PhiIndex = Idx;
03263     return PHI;
03264   }
03265 
03266   return NULL;
03267 }
03268 
03269 /// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
03270 /// instruction to a phi node dominated by the switch, if that would mean that
03271 /// some of the destination blocks of the switch can be folded away.
03272 /// Returns true if a change is made.
03273 static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
03274   typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
03275   ForwardingNodesMap ForwardingNodes;
03276 
03277   for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
03278     ConstantInt *CaseValue = I.getCaseValue();
03279     BasicBlock *CaseDest = I.getCaseSuccessor();
03280 
03281     int PhiIndex;
03282     PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
03283                                                  &PhiIndex);
03284     if (!PHI) continue;
03285 
03286     ForwardingNodes[PHI].push_back(PhiIndex);
03287   }
03288 
03289   bool Changed = false;
03290 
03291   for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
03292        E = ForwardingNodes.end(); I != E; ++I) {
03293     PHINode *Phi = I->first;
03294     SmallVectorImpl<int> &Indexes = I->second;
03295 
03296     if (Indexes.size() < 2) continue;
03297 
03298     for (size_t I = 0, E = Indexes.size(); I != E; ++I)
03299       Phi->setIncomingValue(Indexes[I], SI->getCondition());
03300     Changed = true;
03301   }
03302 
03303   return Changed;
03304 }
03305 
03306 /// ValidLookupTableConstant - Return true if the backend will be able to handle
03307 /// initializing an array of constants like C.
03308 static bool ValidLookupTableConstant(Constant *C) {
03309   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
03310     return CE->isGEPWithNoNotionalOverIndexing();
03311 
03312   return isa<ConstantFP>(C) ||
03313       isa<ConstantInt>(C) ||
03314       isa<ConstantPointerNull>(C) ||
03315       isa<GlobalValue>(C) ||
03316       isa<UndefValue>(C);
03317 }
03318 
03319 /// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
03320 /// its constant value in ConstantPool, returning 0 if it's not there.
03321 static Constant *LookupConstant(Value *V,
03322                          const SmallDenseMap<Value*, Constant*>& ConstantPool) {
03323   if (Constant *C = dyn_cast<Constant>(V))
03324     return C;
03325   return ConstantPool.lookup(V);
03326 }
03327 
03328 /// ConstantFold - Try to fold instruction I into a constant. This works for
03329 /// simple instructions such as binary operations where both operands are
03330 /// constant or can be replaced by constants from the ConstantPool. Returns the
03331 /// resulting constant on success, 0 otherwise.
03332 static Constant *
03333 ConstantFold(Instruction *I,
03334              const SmallDenseMap<Value *, Constant *> &ConstantPool,
03335              const DataLayout *DL) {
03336   if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
03337     Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
03338     if (!A)
03339       return 0;
03340     if (A->isAllOnesValue())
03341       return LookupConstant(Select->getTrueValue(), ConstantPool);
03342     if (A->isNullValue())
03343       return LookupConstant(Select->getFalseValue(), ConstantPool);
03344     return 0;
03345   }
03346 
03347   SmallVector<Constant *, 4> COps;
03348   for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
03349     if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
03350       COps.push_back(A);
03351     else
03352       return 0;
03353   }
03354 
03355   if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
03356     return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
03357                                            COps[1], DL);
03358 
03359   return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
03360 }
03361 
03362 /// GetCaseResults - Try to determine the resulting constant values in phi nodes
03363 /// at the common destination basic block, *CommonDest, for one of the case
03364 /// destionations CaseDest corresponding to value CaseVal (0 for the default
03365 /// case), of a switch instruction SI.
03366 static bool
03367 GetCaseResults(SwitchInst *SI,
03368                ConstantInt *CaseVal,
03369                BasicBlock *CaseDest,
03370                BasicBlock **CommonDest,
03371                SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
03372                const DataLayout *DL) {
03373   // The block from which we enter the common destination.
03374   BasicBlock *Pred = SI->getParent();
03375 
03376   // If CaseDest is empty except for some side-effect free instructions through
03377   // which we can constant-propagate the CaseVal, continue to its successor.
03378   SmallDenseMap<Value*, Constant*> ConstantPool;
03379   ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
03380   for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
03381        ++I) {
03382     if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
03383       // If the terminator is a simple branch, continue to the next block.
03384       if (T->getNumSuccessors() != 1)
03385         return false;
03386       Pred = CaseDest;
03387       CaseDest = T->getSuccessor(0);
03388     } else if (isa<DbgInfoIntrinsic>(I)) {
03389       // Skip debug intrinsic.
03390       continue;
03391     } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
03392       // Instruction is side-effect free and constant.
03393       ConstantPool.insert(std::make_pair(I, C));
03394     } else {
03395       break;
03396     }
03397   }
03398 
03399   // If we did not have a CommonDest before, use the current one.
03400   if (!*CommonDest)
03401     *CommonDest = CaseDest;
03402   // If the destination isn't the common one, abort.
03403   if (CaseDest != *CommonDest)
03404     return false;
03405 
03406   // Get the values for this case from phi nodes in the destination block.
03407   BasicBlock::iterator I = (*CommonDest)->begin();
03408   while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
03409     int Idx = PHI->getBasicBlockIndex(Pred);
03410     if (Idx == -1)
03411       continue;
03412 
03413     Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
03414                                         ConstantPool);
03415     if (!ConstVal)
03416       return false;
03417 
03418     // Note: If the constant comes from constant-propagating the case value
03419     // through the CaseDest basic block, it will be safe to remove the
03420     // instructions in that block. They cannot be used (except in the phi nodes
03421     // we visit) outside CaseDest, because that block does not dominate its
03422     // successor. If it did, we would not be in this phi node.
03423 
03424     // Be conservative about which kinds of constants we support.
03425     if (!ValidLookupTableConstant(ConstVal))
03426       return false;
03427 
03428     Res.push_back(std::make_pair(PHI, ConstVal));
03429   }
03430 
03431   return Res.size() > 0;
03432 }
03433 
03434 namespace {
03435   /// SwitchLookupTable - This class represents a lookup table that can be used
03436   /// to replace a switch.
03437   class SwitchLookupTable {
03438   public:
03439     /// SwitchLookupTable - Create a lookup table to use as a switch replacement
03440     /// with the contents of Values, using DefaultValue to fill any holes in the
03441     /// table.
03442     SwitchLookupTable(Module &M,
03443                       uint64_t TableSize,
03444                       ConstantInt *Offset,
03445              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
03446                       Constant *DefaultValue,
03447                       const DataLayout *DL);
03448 
03449     /// BuildLookup - Build instructions with Builder to retrieve the value at
03450     /// the position given by Index in the lookup table.
03451     Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
03452 
03453     /// WouldFitInRegister - Return true if a table with TableSize elements of
03454     /// type ElementType would fit in a target-legal register.
03455     static bool WouldFitInRegister(const DataLayout *DL,
03456                                    uint64_t TableSize,
03457                                    const Type *ElementType);
03458 
03459   private:
03460     // Depending on the contents of the table, it can be represented in
03461     // different ways.
03462     enum {
03463       // For tables where each element contains the same value, we just have to
03464       // store that single value and return it for each lookup.
03465       SingleValueKind,
03466 
03467       // For small tables with integer elements, we can pack them into a bitmap
03468       // that fits into a target-legal register. Values are retrieved by
03469       // shift and mask operations.
03470       BitMapKind,
03471 
03472       // The table is stored as an array of values. Values are retrieved by load
03473       // instructions from the table.
03474       ArrayKind
03475     } Kind;
03476 
03477     // For SingleValueKind, this is the single value.
03478     Constant *SingleValue;
03479 
03480     // For BitMapKind, this is the bitmap.
03481     ConstantInt *BitMap;
03482     IntegerType *BitMapElementTy;
03483 
03484     // For ArrayKind, this is the array.
03485     GlobalVariable *Array;
03486   };
03487 }
03488 
03489 SwitchLookupTable::SwitchLookupTable(Module &M,
03490                                      uint64_t TableSize,
03491                                      ConstantInt *Offset,
03492              const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
03493                                      Constant *DefaultValue,
03494                                      const DataLayout *DL)
03495     : SingleValue(0), BitMap(0), BitMapElementTy(0), Array(0) {
03496   assert(Values.size() && "Can't build lookup table without values!");
03497   assert(TableSize >= Values.size() && "Can't fit values in table!");
03498 
03499   // If all values in the table are equal, this is that value.
03500   SingleValue = Values.begin()->second;
03501 
03502   Type *ValueType = Values.begin()->second->getType();
03503 
03504   // Build up the table contents.
03505   SmallVector<Constant*, 64> TableContents(TableSize);
03506   for (size_t I = 0, E = Values.size(); I != E; ++I) {
03507     ConstantInt *CaseVal = Values[I].first;
03508     Constant *CaseRes = Values[I].second;
03509     assert(CaseRes->getType() == ValueType);
03510 
03511     uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
03512                    .getLimitedValue();
03513     TableContents[Idx] = CaseRes;
03514 
03515     if (CaseRes != SingleValue)
03516       SingleValue = 0;
03517   }
03518 
03519   // Fill in any holes in the table with the default result.
03520   if (Values.size() < TableSize) {
03521     assert(DefaultValue && "Need a default value to fill the lookup table holes.");
03522     assert(DefaultValue->getType() == ValueType);
03523     for (uint64_t I = 0; I < TableSize; ++I) {
03524       if (!TableContents[I])
03525         TableContents[I] = DefaultValue;
03526     }
03527 
03528     if (DefaultValue != SingleValue)
03529       SingleValue = 0;
03530   }
03531 
03532   // If each element in the table contains the same value, we only need to store
03533   // that single value.
03534   if (SingleValue) {
03535     Kind = SingleValueKind;
03536     return;
03537   }
03538 
03539   // If the type is integer and the table fits in a register, build a bitmap.
03540   if (WouldFitInRegister(DL, TableSize, ValueType)) {
03541     IntegerType *IT = cast<IntegerType>(ValueType);
03542     APInt TableInt(TableSize * IT->getBitWidth(), 0);
03543     for (uint64_t I = TableSize; I > 0; --I) {
03544       TableInt <<= IT->getBitWidth();
03545       // Insert values into the bitmap. Undef values are set to zero.
03546       if (!isa<UndefValue>(TableContents[I - 1])) {
03547         ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
03548         TableInt |= Val->getValue().zext(TableInt.getBitWidth());
03549       }
03550     }
03551     BitMap = ConstantInt::get(M.getContext(), TableInt);
03552     BitMapElementTy = IT;
03553     Kind = BitMapKind;
03554     ++NumBitMaps;
03555     return;
03556   }
03557 
03558   // Store the table in an array.
03559   ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
03560   Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
03561 
03562   Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
03563                              GlobalVariable::PrivateLinkage,
03564                              Initializer,
03565                              "switch.table");
03566   Array->setUnnamedAddr(true);
03567   Kind = ArrayKind;
03568 }
03569 
03570 Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
03571   switch (Kind) {
03572     case SingleValueKind:
03573       return SingleValue;
03574     case BitMapKind: {
03575       // Type of the bitmap (e.g. i59).
03576       IntegerType *MapTy = BitMap->getType();
03577 
03578       // Cast Index to the same type as the bitmap.
03579       // Note: The Index is <= the number of elements in the table, so
03580       // truncating it to the width of the bitmask is safe.
03581       Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
03582 
03583       // Multiply the shift amount by the element width.
03584       ShiftAmt = Builder.CreateMul(ShiftAmt,
03585                       ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
03586                                    "switch.shiftamt");
03587 
03588       // Shift down.
03589       Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
03590                                               "switch.downshift");
03591       // Mask off.
03592       return Builder.CreateTrunc(DownShifted, BitMapElementTy,
03593                                  "switch.masked");
03594     }
03595     case ArrayKind: {
03596       Value *GEPIndices[] = { Builder.getInt32(0), Index };
03597       Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
03598                                              "switch.gep");
03599       return Builder.CreateLoad(GEP, "switch.load");
03600     }
03601   }
03602   llvm_unreachable("Unknown lookup table kind!");
03603 }
03604 
03605 bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
03606                                            uint64_t TableSize,
03607                                            const Type *ElementType) {
03608   if (!DL)
03609     return false;
03610   const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
03611   if (!IT)
03612     return false;
03613   // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
03614   // are <= 15, we could try to narrow the type.
03615 
03616   // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
03617   if (TableSize >= UINT_MAX/IT->getBitWidth())
03618     return false;
03619   return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
03620 }
03621 
03622 /// ShouldBuildLookupTable - Determine whether a lookup table should be built
03623 /// for this switch, based on the number of cases, size of the table and the
03624 /// types of the results.
03625 static bool ShouldBuildLookupTable(SwitchInst *SI,
03626                                    uint64_t TableSize,
03627                                    const TargetTransformInfo &TTI,
03628                                    const DataLayout *DL,
03629                             const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
03630   if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
03631     return false; // TableSize overflowed, or mul below might overflow.
03632 
03633   bool AllTablesFitInRegister = true;
03634   bool HasIllegalType = false;
03635   for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
03636        E = ResultTypes.end(); I != E; ++I) {
03637     Type *Ty = I->second;
03638 
03639     // Saturate this flag to true.
03640     HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
03641 
03642     // Saturate this flag to false.
03643     AllTablesFitInRegister = AllTablesFitInRegister &&
03644       SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
03645 
03646     // If both flags saturate, we're done. NOTE: This *only* works with
03647     // saturating flags, and all flags have to saturate first due to the
03648     // non-deterministic behavior of iterating over a dense map.
03649     if (HasIllegalType && !AllTablesFitInRegister)
03650       break;
03651   }
03652 
03653   // If each table would fit in a register, we should build it anyway.
03654   if (AllTablesFitInRegister)
03655     return true;
03656 
03657   // Don't build a table that doesn't fit in-register if it has illegal types.
03658   if (HasIllegalType)
03659     return false;
03660 
03661   // The table density should be at least 40%. This is the same criterion as for
03662   // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
03663   // FIXME: Find the best cut-off.
03664   return SI->getNumCases() * 10 >= TableSize * 4;
03665 }
03666 
03667 /// SwitchToLookupTable - If the switch is only used to initialize one or more
03668 /// phi nodes in a common successor block with different constant values,
03669 /// replace the switch with lookup tables.
03670 static bool SwitchToLookupTable(SwitchInst *SI,
03671                                 IRBuilder<> &Builder,
03672                                 const TargetTransformInfo &TTI,
03673                                 const DataLayout* DL) {
03674   assert(SI->getNumCases() > 1 && "Degenerate switch?");
03675 
03676   // Only build lookup table when we have a target that supports it.
03677   if (!TTI.shouldBuildLookupTables())
03678     return false;
03679 
03680   // FIXME: If the switch is too sparse for a lookup table, perhaps we could
03681   // split off a dense part and build a lookup table for that.
03682 
03683   // FIXME: This creates arrays of GEPs to constant strings, which means each
03684   // GEP needs a runtime relocation in PIC code. We should just build one big
03685   // string and lookup indices into that.
03686 
03687   // Ignore switches with less than three cases. Lookup tables will not make them
03688   // faster, so we don't analyze them.
03689   if (SI->getNumCases() < 3)
03690     return false;
03691 
03692   // Figure out the corresponding result for each case value and phi node in the
03693   // common destination, as well as the the min and max case values.
03694   assert(SI->case_begin() != SI->case_end());
03695   SwitchInst::CaseIt CI = SI->case_begin();
03696   ConstantInt *MinCaseVal = CI.getCaseValue();
03697   ConstantInt *MaxCaseVal = CI.getCaseValue();
03698 
03699   BasicBlock *CommonDest = 0;
03700   typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
03701   SmallDenseMap<PHINode*, ResultListTy> ResultLists;
03702   SmallDenseMap<PHINode*, Constant*> DefaultResults;
03703   SmallDenseMap<PHINode*, Type*> ResultTypes;
03704   SmallVector<PHINode*, 4> PHIs;
03705 
03706   for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
03707     ConstantInt *CaseVal = CI.getCaseValue();
03708     if (CaseVal->getValue().slt(MinCaseVal->getValue()))
03709       MinCaseVal = CaseVal;
03710     if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
03711       MaxCaseVal = CaseVal;
03712 
03713     // Resulting value at phi nodes for this case value.
03714     typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
03715     ResultsTy Results;
03716     if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
03717                         Results, DL))
03718       return false;
03719 
03720     // Append the result from this case to the list for each phi.
03721     for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
03722       if (!ResultLists.count(I->first))
03723         PHIs.push_back(I->first);
03724       ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
03725     }
03726   }
03727 
03728   // Keep track of the result types.
03729   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
03730     PHINode *PHI = PHIs[I];
03731     ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
03732   }
03733 
03734   uint64_t NumResults = ResultLists[PHIs[0]].size();
03735   APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
03736   uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
03737   bool TableHasHoles = (NumResults < TableSize);
03738 
03739   // If the table has holes, we need a constant result for the default case
03740   // or a bitmask that fits in a register.
03741   SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
03742   bool HasDefaultResults = false;
03743   if (TableHasHoles) {
03744     HasDefaultResults = GetCaseResults(SI, 0, SI->getDefaultDest(), &CommonDest,
03745                                        DefaultResultsList, DL);
03746   }
03747   bool NeedMask = (TableHasHoles && !HasDefaultResults);
03748   if (NeedMask) {
03749     // As an extra penalty for the validity test we require more cases.
03750     if (SI->getNumCases() < 4)  // FIXME: Find best threshold value (benchmark).
03751       return false;
03752     if (!(DL && DL->fitsInLegalInteger(TableSize)))
03753       return false;
03754   }
03755 
03756   for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
03757     PHINode *PHI = DefaultResultsList[I].first;
03758     Constant *Result = DefaultResultsList[I].second;
03759     DefaultResults[PHI] = Result;
03760   }
03761 
03762   if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
03763     return false;
03764 
03765   // Create the BB that does the lookups.
03766   Module &Mod = *CommonDest->getParent()->getParent();
03767   BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
03768                                             "switch.lookup",
03769                                             CommonDest->getParent(),
03770                                             CommonDest);
03771 
03772   // Compute the table index value.
03773   Builder.SetInsertPoint(SI);
03774   Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
03775                                         "switch.tableidx");
03776 
03777   // Compute the maximum table size representable by the integer type we are
03778   // switching upon.
03779   unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
03780   uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
03781   assert(MaxTableSize >= TableSize &&
03782          "It is impossible for a switch to have more entries than the max "
03783          "representable value of its input integer type's size.");
03784 
03785   // If we have a fully covered lookup table, unconditionally branch to the
03786   // lookup table BB. Otherwise, check if the condition value is within the case
03787   // range. If it is so, branch to the new BB. Otherwise branch to SI's default
03788   // destination.
03789   const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
03790   if (GeneratingCoveredLookupTable) {
03791     Builder.CreateBr(LookupBB);
03792     SI->getDefaultDest()->removePredecessor(SI->getParent());
03793   } else {
03794     Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
03795                                          MinCaseVal->getType(), TableSize));
03796     Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
03797   }
03798 
03799   // Populate the BB that does the lookups.
03800   Builder.SetInsertPoint(LookupBB);
03801 
03802   if (NeedMask) {
03803     // Before doing the lookup we do the hole check.
03804     // The LookupBB is therefore re-purposed to do the hole check
03805     // and we create a new LookupBB.
03806     BasicBlock *MaskBB = LookupBB;
03807     MaskBB->setName("switch.hole_check");
03808     LookupBB = BasicBlock::Create(Mod.getContext(),
03809                                   "switch.lookup",
03810                                   CommonDest->getParent(),
03811                                   CommonDest);
03812 
03813     // Build bitmask; fill in a 1 bit for every case.
03814     APInt MaskInt(TableSize, 0);
03815     APInt One(TableSize, 1);
03816     const ResultListTy &ResultList = ResultLists[PHIs[0]];
03817     for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
03818       uint64_t Idx = (ResultList[I].first->getValue() -
03819                       MinCaseVal->getValue()).getLimitedValue();
03820       MaskInt |= One << Idx;
03821     }
03822     ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
03823 
03824     // Get the TableIndex'th bit of the bitmask.
03825     // If this bit is 0 (meaning hole) jump to the default destination,
03826     // else continue with table lookup.
03827     IntegerType *MapTy = TableMask->getType();
03828     Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
03829                                                  "switch.maskindex");
03830     Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
03831                                         "switch.shifted");
03832     Value *LoBit = Builder.CreateTrunc(Shifted,
03833                                        Type::getInt1Ty(Mod.getContext()),
03834                                        "switch.lobit");
03835     Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
03836 
03837     Builder.SetInsertPoint(LookupBB);
03838     AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
03839   }
03840 
03841   bool ReturnedEarly = false;
03842   for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
03843     PHINode *PHI = PHIs[I];
03844 
03845     // If using a bitmask, use any value to fill the lookup table holes.
03846     Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
03847     SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
03848                             DV, DL);
03849 
03850     Value *Result = Table.BuildLookup(TableIndex, Builder);
03851 
03852     // If the result is used to return immediately from the function, we want to
03853     // do that right here.
03854     if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
03855         PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
03856       Builder.CreateRet(Result);
03857       ReturnedEarly = true;
03858       break;
03859     }
03860 
03861     PHI->addIncoming(Result, LookupBB);
03862   }
03863 
03864   if (!ReturnedEarly)
03865     Builder.CreateBr(CommonDest);
03866 
03867   // Remove the switch.
03868   for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
03869     BasicBlock *Succ = SI->getSuccessor(i);
03870 
03871     if (Succ == SI->getDefaultDest())
03872       continue;
03873     Succ->removePredecessor(SI->getParent());
03874   }
03875   SI->eraseFromParent();
03876 
03877   ++NumLookupTables;
03878   if (NeedMask)
03879     ++NumLookupTablesHoles;
03880   return true;
03881 }
03882 
03883 bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
03884   BasicBlock *BB = SI->getParent();
03885 
03886   if (isValueEqualityComparison(SI)) {
03887     // If we only have one predecessor, and if it is a branch on this value,
03888     // see if that predecessor totally determines the outcome of this switch.
03889     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
03890       if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
03891         return SimplifyCFG(BB, TTI, DL) | true;
03892 
03893     Value *Cond = SI->getCondition();
03894     if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
03895       if (SimplifySwitchOnSelect(SI, Select))
03896         return SimplifyCFG(BB, TTI, DL) | true;
03897 
03898     // If the block only contains the switch, see if we can fold the block
03899     // away into any preds.
03900     BasicBlock::iterator BBI = BB->begin();
03901     // Ignore dbg intrinsics.
03902     while (isa<DbgInfoIntrinsic>(BBI))
03903       ++BBI;
03904     if (SI == &*BBI)
03905       if (FoldValueComparisonIntoPredecessors(SI, Builder))
03906         return SimplifyCFG(BB, TTI, DL) | true;
03907   }
03908 
03909   // Try to transform the switch into an icmp and a branch.
03910   if (TurnSwitchRangeIntoICmp(SI, Builder))
03911     return SimplifyCFG(BB, TTI, DL) | true;
03912 
03913   // Remove unreachable cases.
03914   if (EliminateDeadSwitchCases(SI))
03915     return SimplifyCFG(BB, TTI, DL) | true;
03916 
03917   if (ForwardSwitchConditionToPHI(SI))
03918     return SimplifyCFG(BB, TTI, DL) | true;
03919 
03920   if (SwitchToLookupTable(SI, Builder, TTI, DL))
03921     return SimplifyCFG(BB, TTI, DL) | true;
03922 
03923   return false;
03924 }
03925 
03926 bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
03927   BasicBlock *BB = IBI->getParent();
03928   bool Changed = false;
03929 
03930   // Eliminate redundant destinations.
03931   SmallPtrSet<Value *, 8> Succs;
03932   for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
03933     BasicBlock *Dest = IBI->getDestination(i);
03934     if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
03935       Dest->removePredecessor(BB);
03936       IBI->removeDestination(i);
03937       --i; --e;
03938       Changed = true;
03939     }
03940   }
03941 
03942   if (IBI->getNumDestinations() == 0) {
03943     // If the indirectbr has no successors, change it to unreachable.
03944     new UnreachableInst(IBI->getContext(), IBI);
03945     EraseTerminatorInstAndDCECond(IBI);
03946     return true;
03947   }
03948 
03949   if (IBI->getNumDestinations() == 1) {
03950     // If the indirectbr has one successor, change it to a direct branch.
03951     BranchInst::Create(IBI->getDestination(0), IBI);
03952     EraseTerminatorInstAndDCECond(IBI);
03953     return true;
03954   }
03955 
03956   if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
03957     if (SimplifyIndirectBrOnSelect(IBI, SI))
03958       return SimplifyCFG(BB, TTI, DL) | true;
03959   }
03960   return Changed;
03961 }
03962 
03963 bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
03964   BasicBlock *BB = BI->getParent();
03965 
03966   if (SinkCommon && SinkThenElseCodeToEnd(BI))
03967     return true;
03968 
03969   // If the Terminator is the only non-phi instruction, simplify the block.
03970   BasicBlock::iterator I = BB->getFirstNonPHIOrDbgOrLifetime();
03971   if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
03972       TryToSimplifyUncondBranchFromEmptyBlock(BB))
03973     return true;
03974 
03975   // If the only instruction in the block is a seteq/setne comparison
03976   // against a constant, try to simplify the block.
03977   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
03978     if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
03979       for (++I; isa<DbgInfoIntrinsic>(I); ++I)
03980         ;
03981       if (I->isTerminator() &&
03982           TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI, DL))
03983         return true;
03984     }
03985 
03986   // If this basic block is ONLY a compare and a branch, and if a predecessor
03987   // branches to us and our successor, fold the comparison into the
03988   // predecessor and use logical operations to update the incoming value
03989   // for PHI nodes in common successor.
03990   if (FoldBranchToCommonDest(BI))
03991     return SimplifyCFG(BB, TTI, DL) | true;
03992   return false;
03993 }
03994 
03995 
03996 bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
03997   BasicBlock *BB = BI->getParent();
03998 
03999   // Conditional branch
04000   if (isValueEqualityComparison(BI)) {
04001     // If we only have one predecessor, and if it is a branch on this value,
04002     // see if that predecessor totally determines the outcome of this
04003     // switch.
04004     if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
04005       if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
04006         return SimplifyCFG(BB, TTI, DL) | true;
04007 
04008     // This block must be empty, except for the setcond inst, if it exists.
04009     // Ignore dbg intrinsics.
04010     BasicBlock::iterator I = BB->begin();
04011     // Ignore dbg intrinsics.
04012     while (isa<DbgInfoIntrinsic>(I))
04013       ++I;
04014     if (&*I == BI) {
04015       if (FoldValueComparisonIntoPredecessors(BI, Builder))
04016         return SimplifyCFG(BB, TTI, DL) | true;
04017     } else if (&*I == cast<Instruction>(BI->getCondition())){
04018       ++I;
04019       // Ignore dbg intrinsics.
04020       while (isa<DbgInfoIntrinsic>(I))
04021         ++I;
04022       if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
04023         return SimplifyCFG(BB, TTI, DL) | true;
04024     }
04025   }
04026 
04027   // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
04028   if (SimplifyBranchOnICmpChain(BI, DL, Builder))
04029     return true;
04030 
04031   // If this basic block is ONLY a compare and a branch, and if a predecessor
04032   // branches to us and one of our successors, fold the comparison into the
04033   // predecessor and use logical operations to pick the right destination.
04034   if (FoldBranchToCommonDest(BI))
04035     return SimplifyCFG(BB, TTI, DL) | true;
04036 
04037   // We have a conditional branch to two blocks that are only reachable
04038   // from BI.  We know that the condbr dominates the two blocks, so see if
04039   // there is any identical code in the "then" and "else" blocks.  If so, we
04040   // can hoist it up to the branching block.
04041   if (BI->getSuccessor(0)->getSinglePredecessor() != 0) {
04042     if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
04043       if (HoistThenElseCodeToIf(BI))
04044         return SimplifyCFG(BB, TTI, DL) | true;
04045     } else {
04046       // If Successor #1 has multiple preds, we may be able to conditionally
04047       // execute Successor #0 if it branches to successor #1.
04048       TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
04049       if (Succ0TI->getNumSuccessors() == 1 &&
04050           Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
04051         if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0)))
04052           return SimplifyCFG(BB, TTI, DL) | true;
04053     }
04054   } else if (BI->getSuccessor(1)->getSinglePredecessor() != 0) {
04055     // If Successor #0 has multiple preds, we may be able to conditionally
04056     // execute Successor #1 if it branches to successor #0.
04057     TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
04058     if (Succ1TI->getNumSuccessors() == 1 &&
04059         Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
04060       if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1)))
04061         return SimplifyCFG(BB, TTI, DL) | true;
04062   }
04063 
04064   // If this is a branch on a phi node in the current block, thread control
04065   // through this block if any PHI node entries are constants.
04066   if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
04067     if (PN->getParent() == BI->getParent())
04068       if (FoldCondBranchOnPHI(BI, DL))
04069         return SimplifyCFG(BB, TTI, DL) | true;
04070 
04071   // Scan predecessor blocks for conditional branches.
04072   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
04073     if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
04074       if (PBI != BI && PBI->isConditional())
04075         if (SimplifyCondBranchToCondBranch(PBI, BI))
04076           return SimplifyCFG(BB, TTI, DL) | true;
04077 
04078   return false;
04079 }
04080 
04081 /// Check if passing a value to an instruction will cause undefined behavior.
04082 static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
04083   Constant *C = dyn_cast<Constant>(V);
04084   if (!C)
04085     return false;
04086 
04087   if (I->use_empty())
04088     return false;
04089 
04090   if (C->isNullValue()) {
04091     // Only look at the first use, avoid hurting compile time with long uselists
04092     User *Use = *I->user_begin();
04093 
04094     // Now make sure that there are no instructions in between that can alter
04095     // control flow (eg. calls)
04096     for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
04097       if (i == I->getParent()->end() || i->mayHaveSideEffects())
04098         return false;
04099 
04100     // Look through GEPs. A load from a GEP derived from NULL is still undefined
04101     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
04102       if (GEP->getPointerOperand() == I)
04103         return passingValueIsAlwaysUndefined(V, GEP);
04104 
04105     // Look through bitcasts.
04106     if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
04107       return passingValueIsAlwaysUndefined(V, BC);
04108 
04109     // Load from null is undefined.
04110     if (LoadInst *LI = dyn_cast<LoadInst>(Use))
04111       if (!LI->isVolatile())
04112         return LI->getPointerAddressSpace() == 0;
04113 
04114     // Store to null is undefined.
04115     if (StoreInst *SI = dyn_cast<StoreInst>(Use))
04116       if (!SI->isVolatile())
04117         return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
04118   }
04119   return false;
04120 }
04121 
04122 /// If BB has an incoming value that will always trigger undefined behavior
04123 /// (eg. null pointer dereference), remove the branch leading here.
04124 static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
04125   for (BasicBlock::iterator i = BB->begin();
04126        PHINode *PHI = dyn_cast<PHINode>(i); ++i)
04127     for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
04128       if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
04129         TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
04130         IRBuilder<> Builder(T);
04131         if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
04132           BB->removePredecessor(PHI->getIncomingBlock(i));
04133           // Turn uncoditional branches into unreachables and remove the dead
04134           // destination from conditional branches.
04135           if (BI->isUnconditional())
04136             Builder.CreateUnreachable();
04137           else
04138             Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
04139                                                          BI->getSuccessor(0));
04140           BI->eraseFromParent();
04141           return true;
04142         }
04143         // TODO: SwitchInst.
04144       }
04145 
04146   return false;
04147 }
04148 
04149 bool SimplifyCFGOpt::run(BasicBlock *BB) {
04150   bool Changed = false;
04151 
04152   assert(BB && BB->getParent() && "Block not embedded in function!");
04153   assert(BB->getTerminator() && "Degenerate basic block encountered!");
04154 
04155   // Remove basic blocks that have no predecessors (except the entry block)...
04156   // or that just have themself as a predecessor.  These are unreachable.
04157   if ((pred_begin(BB) == pred_end(BB) &&
04158        BB != &BB->getParent()->getEntryBlock()) ||
04159       BB->getSinglePredecessor() == BB) {
04160     DEBUG(dbgs() << "Removing BB: \n" << *BB);
04161     DeleteDeadBlock(BB);
04162     return true;
04163   }
04164 
04165   // Check to see if we can constant propagate this terminator instruction
04166   // away...
04167   Changed |= ConstantFoldTerminator(BB, true);
04168 
04169   // Check for and eliminate duplicate PHI nodes in this block.
04170   Changed |= EliminateDuplicatePHINodes(BB);
04171 
04172   // Check for and remove branches that will always cause undefined behavior.
04173   Changed |= removeUndefIntroducingPredecessor(BB);
04174 
04175   // Merge basic blocks into their predecessor if there is only one distinct
04176   // pred, and if there is only one distinct successor of the predecessor, and
04177   // if there are no PHI nodes.
04178   //
04179   if (MergeBlockIntoPredecessor(BB))
04180     return true;
04181 
04182   IRBuilder<> Builder(BB);
04183 
04184   // If there is a trivial two-entry PHI node in this basic block, and we can
04185   // eliminate it, do so now.
04186   if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
04187     if (PN->getNumIncomingValues() == 2)
04188       Changed |= FoldTwoEntryPHINode(PN, DL);
04189 
04190   Builder.SetInsertPoint(BB->getTerminator());
04191   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
04192     if (BI->isUnconditional()) {
04193       if (SimplifyUncondBranch(BI, Builder)) return true;
04194     } else {
04195       if (SimplifyCondBranch(BI, Builder)) return true;
04196     }
04197   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
04198     if (SimplifyReturn(RI, Builder)) return true;
04199   } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
04200     if (SimplifyResume(RI, Builder)) return true;
04201   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
04202     if (SimplifySwitch(SI, Builder)) return true;
04203   } else if (UnreachableInst *UI =
04204                dyn_cast<UnreachableInst>(BB->getTerminator())) {
04205     if (SimplifyUnreachable(UI)) return true;
04206   } else if (IndirectBrInst *IBI =
04207                dyn_cast<IndirectBrInst>(BB->getTerminator())) {
04208     if (SimplifyIndirectBr(IBI)) return true;
04209   }
04210 
04211   return Changed;
04212 }
04213 
04214 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
04215 /// example, it adjusts branches to branches to eliminate the extra hop, it
04216 /// eliminates unreachable basic blocks, and does other "peephole" optimization
04217 /// of the CFG.  It returns true if a modification was made.
04218 ///
04219 bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
04220                        const DataLayout *DL) {
04221   return SimplifyCFGOpt(TTI, DL).run(BB);
04222 }