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