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