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