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