LCOV - code coverage report
Current view: top level - lib/Analysis - ScalarEvolution.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 4224 4449 94.9 %
Date: 2018-07-13 00:08:38 Functions: 348 356 97.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file contains the implementation of the scalar evolution analysis
      11             : // engine, which is used primarily to analyze expressions involving induction
      12             : // variables in loops.
      13             : //
      14             : // There are several aspects to this library.  First is the representation of
      15             : // scalar expressions, which are represented as subclasses of the SCEV class.
      16             : // These classes are used to represent certain types of subexpressions that we
      17             : // can handle. We only create one SCEV of a particular shape, so
      18             : // pointer-comparisons for equality are legal.
      19             : //
      20             : // One important aspect of the SCEV objects is that they are never cyclic, even
      21             : // if there is a cycle in the dataflow for an expression (ie, a PHI node).  If
      22             : // the PHI node is one of the idioms that we can represent (e.g., a polynomial
      23             : // recurrence) then we represent it directly as a recurrence node, otherwise we
      24             : // represent it as a SCEVUnknown node.
      25             : //
      26             : // In addition to being able to represent expressions of various types, we also
      27             : // have folders that are used to build the *canonical* representation for a
      28             : // particular expression.  These folders are capable of using a variety of
      29             : // rewrite rules to simplify the expressions.
      30             : //
      31             : // Once the folders are defined, we can implement the more interesting
      32             : // higher-level code, such as the code that recognizes PHI nodes of various
      33             : // types, computes the execution count of a loop, etc.
      34             : //
      35             : // TODO: We should use these routines and value representations to implement
      36             : // dependence analysis!
      37             : //
      38             : //===----------------------------------------------------------------------===//
      39             : //
      40             : // There are several good references for the techniques used in this analysis.
      41             : //
      42             : //  Chains of recurrences -- a method to expedite the evaluation
      43             : //  of closed-form functions
      44             : //  Olaf Bachmann, Paul S. Wang, Eugene V. Zima
      45             : //
      46             : //  On computational properties of chains of recurrences
      47             : //  Eugene V. Zima
      48             : //
      49             : //  Symbolic Evaluation of Chains of Recurrences for Loop Optimization
      50             : //  Robert A. van Engelen
      51             : //
      52             : //  Efficient Symbolic Analysis for Optimizing Compilers
      53             : //  Robert A. van Engelen
      54             : //
      55             : //  Using the chains of recurrences algebra for data dependence testing and
      56             : //  induction variable substitution
      57             : //  MS Thesis, Johnie Birch
      58             : //
      59             : //===----------------------------------------------------------------------===//
      60             : 
      61             : #include "llvm/Analysis/ScalarEvolution.h"
      62             : #include "llvm/ADT/APInt.h"
      63             : #include "llvm/ADT/ArrayRef.h"
      64             : #include "llvm/ADT/DenseMap.h"
      65             : #include "llvm/ADT/DepthFirstIterator.h"
      66             : #include "llvm/ADT/EquivalenceClasses.h"
      67             : #include "llvm/ADT/FoldingSet.h"
      68             : #include "llvm/ADT/None.h"
      69             : #include "llvm/ADT/Optional.h"
      70             : #include "llvm/ADT/STLExtras.h"
      71             : #include "llvm/ADT/ScopeExit.h"
      72             : #include "llvm/ADT/Sequence.h"
      73             : #include "llvm/ADT/SetVector.h"
      74             : #include "llvm/ADT/SmallPtrSet.h"
      75             : #include "llvm/ADT/SmallSet.h"
      76             : #include "llvm/ADT/SmallVector.h"
      77             : #include "llvm/ADT/Statistic.h"
      78             : #include "llvm/ADT/StringRef.h"
      79             : #include "llvm/Analysis/AssumptionCache.h"
      80             : #include "llvm/Analysis/ConstantFolding.h"
      81             : #include "llvm/Analysis/InstructionSimplify.h"
      82             : #include "llvm/Analysis/LoopInfo.h"
      83             : #include "llvm/Analysis/ScalarEvolutionExpressions.h"
      84             : #include "llvm/Analysis/TargetLibraryInfo.h"
      85             : #include "llvm/Analysis/ValueTracking.h"
      86             : #include "llvm/Config/llvm-config.h"
      87             : #include "llvm/IR/Argument.h"
      88             : #include "llvm/IR/BasicBlock.h"
      89             : #include "llvm/IR/CFG.h"
      90             : #include "llvm/IR/CallSite.h"
      91             : #include "llvm/IR/Constant.h"
      92             : #include "llvm/IR/ConstantRange.h"
      93             : #include "llvm/IR/Constants.h"
      94             : #include "llvm/IR/DataLayout.h"
      95             : #include "llvm/IR/DerivedTypes.h"
      96             : #include "llvm/IR/Dominators.h"
      97             : #include "llvm/IR/Function.h"
      98             : #include "llvm/IR/GlobalAlias.h"
      99             : #include "llvm/IR/GlobalValue.h"
     100             : #include "llvm/IR/GlobalVariable.h"
     101             : #include "llvm/IR/InstIterator.h"
     102             : #include "llvm/IR/InstrTypes.h"
     103             : #include "llvm/IR/Instruction.h"
     104             : #include "llvm/IR/Instructions.h"
     105             : #include "llvm/IR/IntrinsicInst.h"
     106             : #include "llvm/IR/Intrinsics.h"
     107             : #include "llvm/IR/LLVMContext.h"
     108             : #include "llvm/IR/Metadata.h"
     109             : #include "llvm/IR/Operator.h"
     110             : #include "llvm/IR/PatternMatch.h"
     111             : #include "llvm/IR/Type.h"
     112             : #include "llvm/IR/Use.h"
     113             : #include "llvm/IR/User.h"
     114             : #include "llvm/IR/Value.h"
     115             : #include "llvm/Pass.h"
     116             : #include "llvm/Support/Casting.h"
     117             : #include "llvm/Support/CommandLine.h"
     118             : #include "llvm/Support/Compiler.h"
     119             : #include "llvm/Support/Debug.h"
     120             : #include "llvm/Support/ErrorHandling.h"
     121             : #include "llvm/Support/KnownBits.h"
     122             : #include "llvm/Support/SaveAndRestore.h"
     123             : #include "llvm/Support/raw_ostream.h"
     124             : #include <algorithm>
     125             : #include <cassert>
     126             : #include <climits>
     127             : #include <cstddef>
     128             : #include <cstdint>
     129             : #include <cstdlib>
     130             : #include <map>
     131             : #include <memory>
     132             : #include <tuple>
     133             : #include <utility>
     134             : #include <vector>
     135             : 
     136             : using namespace llvm;
     137             : 
     138             : #define DEBUG_TYPE "scalar-evolution"
     139             : 
     140             : STATISTIC(NumArrayLenItCounts,
     141             :           "Number of trip counts computed with array length");
     142             : STATISTIC(NumTripCountsComputed,
     143             :           "Number of loops with predictable loop counts");
     144             : STATISTIC(NumTripCountsNotComputed,
     145             :           "Number of loops without predictable loop counts");
     146             : STATISTIC(NumBruteForceTripCountsComputed,
     147             :           "Number of loops with trip counts computed by force");
     148             : 
     149             : static cl::opt<unsigned>
     150       99743 : MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
     151       99743 :                         cl::desc("Maximum number of iterations SCEV will "
     152             :                                  "symbolically execute a constant "
     153             :                                  "derived loop"),
     154      299229 :                         cl::init(100));
     155             : 
     156             : // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
     157       99743 : static cl::opt<bool> VerifySCEV(
     158             :     "verify-scev", cl::Hidden,
     159       99743 :     cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
     160             : static cl::opt<bool>
     161       99743 :     VerifySCEVMap("verify-scev-maps", cl::Hidden,
     162       99743 :                   cl::desc("Verify no dangling value in ScalarEvolution's "
     163       99743 :                            "ExprValueMap (slow)"));
     164             : 
     165       99743 : static cl::opt<unsigned> MulOpsInlineThreshold(
     166             :     "scev-mulops-inline-threshold", cl::Hidden,
     167       99743 :     cl::desc("Threshold for inlining multiplication operands into a SCEV"),
     168      299229 :     cl::init(32));
     169             : 
     170       99743 : static cl::opt<unsigned> AddOpsInlineThreshold(
     171             :     "scev-addops-inline-threshold", cl::Hidden,
     172       99743 :     cl::desc("Threshold for inlining addition operands into a SCEV"),
     173      299229 :     cl::init(500));
     174             : 
     175       99743 : static cl::opt<unsigned> MaxSCEVCompareDepth(
     176             :     "scalar-evolution-max-scev-compare-depth", cl::Hidden,
     177       99743 :     cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
     178      299229 :     cl::init(32));
     179             : 
     180       99743 : static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
     181             :     "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
     182       99743 :     cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
     183      299229 :     cl::init(2));
     184             : 
     185       99743 : static cl::opt<unsigned> MaxValueCompareDepth(
     186             :     "scalar-evolution-max-value-compare-depth", cl::Hidden,
     187       99743 :     cl::desc("Maximum depth of recursive value complexity comparisons"),
     188      299229 :     cl::init(2));
     189             : 
     190             : static cl::opt<unsigned>
     191       99743 :     MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
     192       99743 :                   cl::desc("Maximum depth of recursive arithmetics"),
     193      299229 :                   cl::init(32));
     194             : 
     195       99743 : static cl::opt<unsigned> MaxConstantEvolvingDepth(
     196             :     "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
     197      199486 :     cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
     198             : 
     199             : static cl::opt<unsigned>
     200       99743 :     MaxExtDepth("scalar-evolution-max-ext-depth", cl::Hidden,
     201       99743 :                 cl::desc("Maximum depth of recursive SExt/ZExt"),
     202      299229 :                 cl::init(8));
     203             : 
     204             : static cl::opt<unsigned>
     205       99743 :     MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
     206       99743 :                   cl::desc("Max coefficients in AddRec during evolving"),
     207      299229 :                   cl::init(16));
     208             : 
     209             : //===----------------------------------------------------------------------===//
     210             : //                           SCEV class definitions
     211             : //===----------------------------------------------------------------------===//
     212             : 
     213             : //===----------------------------------------------------------------------===//
     214             : // Implementation of the SCEV class.
     215             : //
     216             : 
     217             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     218             : LLVM_DUMP_METHOD void SCEV::dump() const {
     219             :   print(dbgs());
     220             :   dbgs() << '\n';
     221             : }
     222             : #endif
     223             : 
     224       51390 : void SCEV::print(raw_ostream &OS) const {
     225      102780 :   switch (static_cast<SCEVTypes>(getSCEVType())) {
     226             :   case scConstant:
     227       18045 :     cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
     228       18045 :     return;
     229             :   case scTruncate: {
     230             :     const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
     231        1249 :     const SCEV *Op = Trunc->getOperand();
     232        2498 :     OS << "(trunc " << *Op->getType() << " " << *Op << " to "
     233        2498 :        << *Trunc->getType() << ")";
     234        1249 :     return;
     235             :   }
     236             :   case scZeroExtend: {
     237             :     const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
     238        2540 :     const SCEV *Op = ZExt->getOperand();
     239        5080 :     OS << "(zext " << *Op->getType() << " " << *Op << " to "
     240        5080 :        << *ZExt->getType() << ")";
     241        2540 :     return;
     242             :   }
     243             :   case scSignExtend: {
     244             :     const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
     245         452 :     const SCEV *Op = SExt->getOperand();
     246         904 :     OS << "(sext " << *Op->getType() << " " << *Op << " to "
     247         904 :        << *SExt->getType() << ")";
     248         452 :     return;
     249             :   }
     250             :   case scAddRecExpr: {
     251             :     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
     252        6938 :     OS << "{" << *AR->getOperand(0);
     253        7266 :     for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
     254        7594 :       OS << ",+," << *AR->getOperand(i);
     255        3469 :     OS << "}<";
     256        3469 :     if (AR->hasNoUnsignedWrap())
     257         467 :       OS << "nuw><";
     258        3469 :     if (AR->hasNoSignedWrap())
     259         640 :       OS << "nsw><";
     260        4350 :     if (AR->hasNoSelfWrap() &&
     261             :         !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
     262         128 :       OS << "nw><";
     263        6938 :     AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
     264        3469 :     OS << ">";
     265        3469 :     return;
     266             :   }
     267             :   case scAddExpr:
     268             :   case scMulExpr:
     269             :   case scUMaxExpr:
     270             :   case scSMaxExpr: {
     271             :     const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
     272             :     const char *OpStr = nullptr;
     273       14721 :     switch (NAry->getSCEVType()) {
     274        5861 :     case scAddExpr: OpStr = " + "; break;
     275        5827 :     case scMulExpr: OpStr = " * "; break;
     276        2727 :     case scUMaxExpr: OpStr = " umax "; break;
     277         306 :     case scSMaxExpr: OpStr = " smax "; break;
     278             :     }
     279       14721 :     OS << "(";
     280       14721 :     for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
     281       46587 :          I != E; ++I) {
     282       31866 :       OS << **I;
     283       31866 :       if (std::next(I) != E)
     284       17145 :         OS << OpStr;
     285             :     }
     286       14721 :     OS << ")";
     287       29442 :     switch (NAry->getSCEVType()) {
     288             :     case scAddExpr:
     289             :     case scMulExpr:
     290       11688 :       if (NAry->hasNoUnsignedWrap())
     291         120 :         OS << "<nuw>";
     292       11688 :       if (NAry->hasNoSignedWrap())
     293        2681 :         OS << "<nsw>";
     294             :     }
     295             :     return;
     296             :   }
     297             :   case scUDivExpr: {
     298             :     const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
     299         453 :     OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
     300         453 :     return;
     301             :   }
     302             :   case scUnknown: {
     303             :     const SCEVUnknown *U = cast<SCEVUnknown>(this);
     304             :     Type *AllocTy;
     305       10461 :     if (U->isSizeOf(AllocTy)) {
     306           8 :       OS << "sizeof(" << *AllocTy << ")";
     307           4 :       return;
     308             :     }
     309       10457 :     if (U->isAlignOf(AllocTy)) {
     310           6 :       OS << "alignof(" << *AllocTy << ")";
     311           3 :       return;
     312             :     }
     313             : 
     314             :     Type *CTy;
     315             :     Constant *FieldNo;
     316       10454 :     if (U->isOffsetOf(CTy, FieldNo)) {
     317           2 :       OS << "offsetof(" << *CTy << ", ";
     318           1 :       FieldNo->printAsOperand(OS, false);
     319           1 :       OS << ")";
     320           1 :       return;
     321             :     }
     322             : 
     323             :     // Otherwise just print it normally.
     324       10453 :     U->getValue()->printAsOperand(OS, false);
     325       10453 :     return;
     326             :   }
     327           0 :   case scCouldNotCompute:
     328           0 :     OS << "***COULDNOTCOMPUTE***";
     329           0 :     return;
     330             :   }
     331           0 :   llvm_unreachable("Unknown SCEV kind!");
     332             : }
     333             : 
     334     7638649 : Type *SCEV::getType() const {
     335     7697494 :   switch (static_cast<SCEVTypes>(getSCEVType())) {
     336             :   case scConstant:
     337     6357048 :     return cast<SCEVConstant>(this)->getType();
     338             :   case scTruncate:
     339             :   case scZeroExtend:
     340             :   case scSignExtend:
     341      161037 :     return cast<SCEVCastExpr>(this)->getType();
     342             :   case scAddRecExpr:
     343             :   case scMulExpr:
     344             :   case scUMaxExpr:
     345             :   case scSMaxExpr:
     346     1599056 :     return cast<SCEVNAryExpr>(this)->getType();
     347             :   case scAddExpr:
     348      788612 :     return cast<SCEVAddExpr>(this)->getType();
     349             :   case scUDivExpr:
     350       58845 :     return cast<SCEVUDivExpr>(this)->getType();
     351             :   case scUnknown:
     352     1911420 :     return cast<SCEVUnknown>(this)->getType();
     353           0 :   case scCouldNotCompute:
     354           0 :     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
     355             :   }
     356           0 :   llvm_unreachable("Unknown SCEV kind!");
     357             : }
     358             : 
     359     1257416 : bool SCEV::isZero() const {
     360             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
     361      839442 :     return SC->getValue()->isZero();
     362             :   return false;
     363             : }
     364             : 
     365       43554 : bool SCEV::isOne() const {
     366             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
     367       27762 :     return SC->getValue()->isOne();
     368             :   return false;
     369             : }
     370             : 
     371      555508 : bool SCEV::isAllOnesValue() const {
     372             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
     373      552176 :     return SC->getValue()->isMinusOne();
     374             :   return false;
     375             : }
     376             : 
     377       20573 : bool SCEV::isNonConstantNegative() const {
     378             :   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
     379             :   if (!Mul) return false;
     380             : 
     381             :   // If there is a constant factor, it will be first.
     382        3837 :   const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
     383             :   if (!SC) return false;
     384             : 
     385             :   // Return true if the value is negative, this matches things like (-42 * V).
     386        6196 :   return SC->getAPInt().isNegative();
     387             : }
     388             : 
     389      492010 : SCEVCouldNotCompute::SCEVCouldNotCompute() :
     390      492010 :   SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
     391             : 
     392      568285 : bool SCEVCouldNotCompute::classof(const SCEV *S) {
     393      568285 :   return S->getSCEVType() == scCouldNotCompute;
     394             : }
     395             : 
     396     5037476 : const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
     397             :   FoldingSetNodeID ID;
     398     5037476 :   ID.AddInteger(scConstant);
     399     5037476 :   ID.AddPointer(V);
     400     5037476 :   void *IP = nullptr;
     401     5037476 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
     402      735578 :   SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
     403      367789 :   UniqueSCEVs.InsertNode(S, IP);
     404      367789 :   return S;
     405             : }
     406             : 
     407     1929890 : const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
     408     3859780 :   return getConstant(ConstantInt::get(getContext(), Val));
     409             : }
     410             : 
     411             : const SCEV *
     412     1220912 : ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
     413     1220912 :   IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
     414     1220912 :   return getConstant(ConstantInt::get(ITy, V, isSigned));
     415             : }
     416             : 
     417       56620 : SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
     418       56620 :                            unsigned SCEVTy, const SCEV *op, Type *ty)
     419       56620 :   : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
     420             : 
     421        3947 : SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
     422        3947 :                                    const SCEV *op, Type *ty)
     423        3947 :   : SCEVCastExpr(ID, scTruncate, op, ty) {
     424             :   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
     425             :          "Cannot truncate non-integer value!");
     426        3947 : }
     427             : 
     428       34074 : SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
     429       34074 :                                        const SCEV *op, Type *ty)
     430       34074 :   : SCEVCastExpr(ID, scZeroExtend, op, ty) {
     431             :   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
     432             :          "Cannot zero extend non-integer value!");
     433       34074 : }
     434             : 
     435       18599 : SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
     436       18599 :                                        const SCEV *op, Type *ty)
     437       18599 :   : SCEVCastExpr(ID, scSignExtend, op, ty) {
     438             :   assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
     439             :          "Cannot sign extend non-integer value!");
     440       18599 : }
     441             : 
     442         900 : void SCEVUnknown::deleted() {
     443             :   // Clear this SCEVUnknown from various maps.
     444         900 :   SE->forgetMemoizedResults(this);
     445             : 
     446             :   // Remove this SCEVUnknown from the uniquing map.
     447         900 :   SE->UniqueSCEVs.RemoveNode(this);
     448             : 
     449             :   // Release the value.
     450             :   setValPtr(nullptr);
     451         900 : }
     452             : 
     453        1321 : void SCEVUnknown::allUsesReplacedWith(Value *New) {
     454             :   // Remove this SCEVUnknown from the uniquing map.
     455        1321 :   SE->UniqueSCEVs.RemoveNode(this);
     456             : 
     457             :   // Update this SCEVUnknown to point to the new value. This is needed
     458             :   // because there may still be outstanding SCEVs which still point to
     459             :   // this SCEVUnknown.
     460             :   setValPtr(New);
     461        1321 : }
     462             : 
     463       10461 : bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
     464             :   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
     465          13 :     if (VCE->getOpcode() == Instruction::PtrToInt)
     466             :       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
     467           8 :         if (CE->getOpcode() == Instruction::GetElementPtr &&
     468          24 :             CE->getOperand(0)->isNullValue() &&
     469             :             CE->getNumOperands() == 2)
     470             :           if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
     471           4 :             if (CI->isOne()) {
     472           4 :               AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
     473           4 :                                  ->getElementType();
     474           4 :               return true;
     475             :             }
     476             : 
     477             :   return false;
     478             : }
     479             : 
     480       10457 : bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
     481             :   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
     482           9 :     if (VCE->getOpcode() == Instruction::PtrToInt)
     483             :       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
     484           8 :         if (CE->getOpcode() == Instruction::GetElementPtr &&
     485           4 :             CE->getOperand(0)->isNullValue()) {
     486             :           Type *Ty =
     487           4 :             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
     488             :           if (StructType *STy = dyn_cast<StructType>(Ty))
     489           4 :             if (!STy->isPacked() &&
     490           8 :                 CE->getNumOperands() == 3 &&
     491           4 :                 CE->getOperand(1)->isNullValue()) {
     492             :               if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
     493           3 :                 if (CI->isOne() &&
     494           7 :                     STy->getNumElements() == 2 &&
     495           6 :                     STy->getElementType(0)->isIntegerTy(1)) {
     496           6 :                   AllocTy = STy->getElementType(1);
     497           3 :                   return true;
     498             :                 }
     499             :             }
     500             :         }
     501             : 
     502             :   return false;
     503             : }
     504             : 
     505       10454 : bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
     506             :   if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
     507           6 :     if (VCE->getOpcode() == Instruction::PtrToInt)
     508             :       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
     509           1 :         if (CE->getOpcode() == Instruction::GetElementPtr &&
     510           1 :             CE->getNumOperands() == 3 &&
     511           3 :             CE->getOperand(0)->isNullValue() &&
     512           1 :             CE->getOperand(1)->isNullValue()) {
     513             :           Type *Ty =
     514           1 :             cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
     515             :           // Ignore vector types here so that ScalarEvolutionExpander doesn't
     516             :           // emit getelementptrs that index into vectors.
     517           1 :           if (Ty->isStructTy() || Ty->isArrayTy()) {
     518           1 :             CTy = Ty;
     519           1 :             FieldNo = CE->getOperand(2);
     520           1 :             return true;
     521             :           }
     522             :         }
     523             : 
     524             :   return false;
     525             : }
     526             : 
     527             : //===----------------------------------------------------------------------===//
     528             : //                               SCEV Utilities
     529             : //===----------------------------------------------------------------------===//
     530             : 
     531             : /// Compare the two values \p LV and \p RV in terms of their "complexity" where
     532             : /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
     533             : /// operands in SCEV expressions.  \p EqCache is a set of pairs of values that
     534             : /// have been previously deemed to be "equally complex" by this routine.  It is
     535             : /// intended to avoid exponential time complexity in cases like:
     536             : ///
     537             : ///   %a = f(%x, %y)
     538             : ///   %b = f(%a, %a)
     539             : ///   %c = f(%b, %b)
     540             : ///
     541             : ///   %d = f(%x, %y)
     542             : ///   %e = f(%d, %d)
     543             : ///   %f = f(%e, %e)
     544             : ///
     545             : ///   CompareValueComplexity(%f, %c)
     546             : ///
     547             : /// Since we do not continue running this routine on expression trees once we
     548             : /// have seen unequal values, there is no need to track them in the cache.
     549             : static int
     550     4097730 : CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
     551             :                        const LoopInfo *const LI, Value *LV, Value *RV,
     552             :                        unsigned Depth) {
     553     4097730 :   if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
     554             :     return 0;
     555             : 
     556             :   // Order pointer values after integer values. This helps SCEVExpander form
     557             :   // GEPs.
     558     2080708 :   bool LIsPointer = LV->getType()->isPointerTy(),
     559     2080708 :        RIsPointer = RV->getType()->isPointerTy();
     560     2080708 :   if (LIsPointer != RIsPointer)
     561       10084 :     return (int)LIsPointer - (int)RIsPointer;
     562             : 
     563             :   // Compare getValueID values.
     564     4141248 :   unsigned LID = LV->getValueID(), RID = RV->getValueID();
     565     2070624 :   if (LID != RID)
     566      697620 :     return (int)LID - (int)RID;
     567             : 
     568             :   // Sort arguments by their position.
     569             :   if (const auto *LA = dyn_cast<Argument>(LV)) {
     570             :     const auto *RA = cast<Argument>(RV);
     571       10609 :     unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
     572       10609 :     return (int)LArgNo - (int)RArgNo;
     573             :   }
     574             : 
     575             :   if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
     576             :     const auto *RGV = cast<GlobalValue>(RV);
     577             : 
     578             :     const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
     579             :       auto LT = GV->getLinkage();
     580       11364 :       return !(GlobalValue::isPrivateLinkage(LT) ||
     581             :                GlobalValue::isInternalLinkage(LT));
     582             :     };
     583             : 
     584             :     // Use the names to distinguish the two values, but only if the
     585             :     // names are semantically important.
     586             :     if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
     587       11364 :       return LGV->getName().compare(RGV->getName());
     588             :   }
     589             : 
     590             :   // For instructions, compare their loop depth, and their operand count.  This
     591             :   // is pretty loose.
     592             :   if (const auto *LInst = dyn_cast<Instruction>(LV)) {
     593             :     const auto *RInst = cast<Instruction>(RV);
     594             : 
     595             :     // Compare loop depths.
     596     1355105 :     const BasicBlock *LParent = LInst->getParent(),
     597     1355105 :                      *RParent = RInst->getParent();
     598     1355105 :     if (LParent != RParent) {
     599      936462 :       unsigned LDepth = LI->getLoopDepth(LParent),
     600      936462 :                RDepth = LI->getLoopDepth(RParent);
     601      936462 :       if (LDepth != RDepth)
     602         352 :         return (int)LDepth - (int)RDepth;
     603             :     }
     604             : 
     605             :     // Compare the number of operands.
     606             :     unsigned LNumOps = LInst->getNumOperands(),
     607             :              RNumOps = RInst->getNumOperands();
     608     1354753 :     if (LNumOps != RNumOps)
     609         113 :       return (int)LNumOps - (int)RNumOps;
     610             : 
     611     4120608 :     for (unsigned Idx : seq(0u, LNumOps)) {
     612             :       int Result =
     613     5664704 :           CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
     614     2832352 :                                  RInst->getOperand(Idx), Depth + 1);
     615     2832352 :       if (Result != 0)
     616             :         return Result;
     617             :     }
     618             :   }
     619             : 
     620     1289864 :   EqCacheValue.unionSets(LV, RV);
     621     1289864 :   return 0;
     622             : }
     623             : 
     624             : // Return negative, zero, or positive, if LHS is less than, equal to, or greater
     625             : // than RHS, respectively. A three-way result allows recursive comparisons to be
     626             : // more efficient.
     627     7966599 : static int CompareSCEVComplexity(
     628             :     EquivalenceClasses<const SCEV *> &EqCacheSCEV,
     629             :     EquivalenceClasses<const Value *> &EqCacheValue,
     630             :     const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
     631             :     DominatorTree &DT, unsigned Depth = 0) {
     632             :   // Fast-path: SCEVs are uniqued so we can do a quick equality check.
     633     7966599 :   if (LHS == RHS)
     634             :     return 0;
     635             : 
     636             :   // Primarily, sort the SCEVs by their getSCEVType().
     637    14088544 :   unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
     638     7044272 :   if (LType != RType)
     639     2731948 :     return (int)LType - (int)RType;
     640             : 
     641     4312324 :   if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
     642             :     return 0;
     643             :   // Aside from the getSCEVType() ordering, the particular ordering
     644             :   // isn't very important except that it's beneficial to be consistent,
     645             :   // so that (a + b) and (b + a) don't end up as different expressions.
     646     3363964 :   switch (static_cast<SCEVTypes>(LType)) {
     647     1265378 :   case scUnknown: {
     648     1265378 :     const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
     649     1265378 :     const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
     650             : 
     651     1265378 :     int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
     652     1265378 :                                    RU->getValue(), Depth + 1);
     653     1265378 :     if (X == 0)
     654      540918 :       EqCacheSCEV.unionSets(LHS, RHS);
     655             :     return X;
     656             :   }
     657             : 
     658     1318977 :   case scConstant: {
     659     1318977 :     const SCEVConstant *LC = cast<SCEVConstant>(LHS);
     660     1318977 :     const SCEVConstant *RC = cast<SCEVConstant>(RHS);
     661             : 
     662             :     // Compare constant values.
     663             :     const APInt &LA = LC->getAPInt();
     664             :     const APInt &RA = RC->getAPInt();
     665     1318977 :     unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
     666     1318977 :     if (LBitWidth != RBitWidth)
     667           1 :       return (int)LBitWidth - (int)RBitWidth;
     668     1318976 :     return LA.ult(RA) ? -1 : 1;
     669             :   }
     670             : 
     671       18394 :   case scAddRecExpr: {
     672       18394 :     const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
     673       18394 :     const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
     674             : 
     675             :     // There is always a dominance between two recs that are used by one SCEV,
     676             :     // so we can safely sort recs by loop header dominance. We require such
     677             :     // order in getAddExpr.
     678       18394 :     const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
     679       18394 :     if (LLoop != RLoop) {
     680             :       const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
     681             :       assert(LHead != RHead && "Two loops share the same header?");
     682        3952 :       if (DT.dominates(LHead, RHead))
     683             :         return 1;
     684             :       else
     685             :         assert(DT.dominates(RHead, LHead) &&
     686             :                "No dominance between recurrences used by one SCEV?");
     687        1829 :       return -1;
     688             :     }
     689             : 
     690             :     // Addrec complexity grows with operand count.
     691       14442 :     unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
     692       14442 :     if (LNumOps != RNumOps)
     693        3128 :       return (int)LNumOps - (int)RNumOps;
     694             : 
     695             :     // Compare NoWrap flags.
     696       33942 :     if (LA->getNoWrapFlags() != RA->getNoWrapFlags())
     697        2375 :       return (int)LA->getNoWrapFlags() - (int)RA->getNoWrapFlags();
     698             : 
     699             :     // Lexicographically compare.
     700        9103 :     for (unsigned i = 0; i != LNumOps; ++i) {
     701       18042 :       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     702             :                                     LA->getOperand(i), RA->getOperand(i), DT,
     703        9021 :                                     Depth + 1);
     704        9021 :       if (X != 0)
     705             :         return X;
     706             :     }
     707           0 :     EqCacheSCEV.unionSets(LHS, RHS);
     708           0 :     return 0;
     709             :   }
     710             : 
     711      745681 :   case scAddExpr:
     712             :   case scMulExpr:
     713             :   case scSMaxExpr:
     714             :   case scUMaxExpr: {
     715      745681 :     const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
     716      745681 :     const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
     717             : 
     718             :     // Lexicographically compare n-ary expressions.
     719      745681 :     unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
     720      745681 :     if (LNumOps != RNumOps)
     721       90301 :       return (int)LNumOps - (int)RNumOps;
     722             : 
     723             :     // Compare NoWrap flags.
     724     1966140 :     if (LC->getNoWrapFlags() != RC->getNoWrapFlags())
     725       28115 :       return (int)LC->getNoWrapFlags() - (int)RC->getNoWrapFlags();
     726             : 
     727     2207097 :     for (unsigned i = 0; i != LNumOps; ++i) {
     728     2313622 :       int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     729             :                                     LC->getOperand(i), RC->getOperand(i), DT,
     730     1156811 :                                     Depth + 1);
     731     1156811 :       if (X != 0)
     732             :         return X;
     733             :     }
     734      260370 :     EqCacheSCEV.unionSets(LHS, RHS);
     735      260370 :     return 0;
     736             :   }
     737             : 
     738        4255 :   case scUDivExpr: {
     739        4255 :     const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
     740        4255 :     const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
     741             : 
     742             :     // Lexicographically compare udiv expressions.
     743        4255 :     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
     744        4255 :                                   RC->getLHS(), DT, Depth + 1);
     745        4255 :     if (X != 0)
     746             :       return X;
     747         544 :     X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
     748             :                               RC->getRHS(), DT, Depth + 1);
     749         544 :     if (X == 0)
     750         343 :       EqCacheSCEV.unionSets(LHS, RHS);
     751             :     return X;
     752             :   }
     753             : 
     754       11279 :   case scTruncate:
     755             :   case scZeroExtend:
     756             :   case scSignExtend: {
     757       11279 :     const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
     758       11279 :     const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
     759             : 
     760             :     // Compare cast expressions by operand.
     761       11279 :     int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     762             :                                   LC->getOperand(), RC->getOperand(), DT,
     763       11279 :                                   Depth + 1);
     764       11279 :     if (X == 0)
     765        2397 :       EqCacheSCEV.unionSets(LHS, RHS);
     766             :     return X;
     767             :   }
     768             : 
     769           0 :   case scCouldNotCompute:
     770           0 :     llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
     771             :   }
     772           0 :   llvm_unreachable("Unknown SCEV kind!");
     773             : }
     774             : 
     775             : /// Given a list of SCEV objects, order them by their complexity, and group
     776             : /// objects of the same complexity together by value.  When this routine is
     777             : /// finished, we know that any duplicates in the vector are consecutive and that
     778             : /// complexity is monotonically increasing.
     779             : ///
     780             : /// Note that we go take special precautions to ensure that we get deterministic
     781             : /// results from this routine.  In other words, we don't want the results of
     782             : /// this to depend on where the addresses of various SCEV objects happened to
     783             : /// land in memory.
     784     3664431 : static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
     785             :                               LoopInfo *LI, DominatorTree &DT) {
     786     6957989 :   if (Ops.size() < 2) return;  // Noop
     787             : 
     788             :   EquivalenceClasses<const SCEV *> EqCacheSCEV;
     789             :   EquivalenceClasses<const Value *> EqCacheValue;
     790     3664431 :   if (Ops.size() == 2) {
     791             :     // This is the common case, which also happens to be trivially simple.
     792             :     // Special case it.
     793             :     const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
     794     3257303 :     if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
     795             :       std::swap(LHS, RHS);
     796             :     return;
     797             :   }
     798             : 
     799             :   // Do the rough sort by complexity.
     800             :   std::stable_sort(Ops.begin(), Ops.end(),
     801     3527386 :                    [&](const SCEV *LHS, const SCEV *RHS) {
     802     3527386 :                      return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
     803     3527386 :                                                   LHS, RHS, DT) < 0;
     804     3527386 :                    });
     805             : 
     806             :   // Now that we are sorted by complexity, group elements of the same
     807             :   // complexity.  Note that this is, at worst, N^2, but the vector is likely to
     808             :   // be extremely short in practice.  Note that we take this approach because we
     809             :   // do not want to depend on the addresses of the objects we are grouping.
     810     1422767 :   for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
     811     2103788 :     const SCEV *S = Ops[i];
     812     1051894 :     unsigned Complexity = S->getSCEVType();
     813             : 
     814             :     // If there are any objects of the same complexity and same value as this
     815             :     // one, group them.
     816    26424598 :     for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
     817    12358252 :       if (Ops[j] == S) { // Found a duplicate.
     818             :         // Move it to immediately after i'th element.
     819       64753 :         std::swap(Ops[i+1], Ops[j]);
     820             :         ++i;   // no need to rescan it.
     821       64753 :         if (i == e-2) return;  // Done!
     822             :       }
     823             :     }
     824             :   }
     825             : }
     826             : 
     827             : // Returns the size of the SCEV S.
     828          72 : static inline int sizeOfSCEV(const SCEV *S) {
     829             :   struct FindSCEVSize {
     830             :     int Size = 0;
     831             : 
     832             :     FindSCEVSize() = default;
     833             : 
     834             :     bool follow(const SCEV *S) {
     835         209 :       ++Size;
     836             :       // Keep looking at all operands of S.
     837             :       return true;
     838             :     }
     839             : 
     840             :     bool isDone() const {
     841             :       return false;
     842             :     }
     843             :   };
     844             : 
     845          72 :   FindSCEVSize F;
     846          72 :   SCEVTraversal<FindSCEVSize> ST(F);
     847          72 :   ST.visitAll(S);
     848         144 :   return F.Size;
     849             : }
     850             : 
     851             : namespace {
     852             : 
     853             : struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
     854             : public:
     855             :   // Computes the Quotient and Remainder of the division of Numerator by
     856             :   // Denominator.
     857       37763 :   static void divide(ScalarEvolution &SE, const SCEV *Numerator,
     858             :                      const SCEV *Denominator, const SCEV **Quotient,
     859             :                      const SCEV **Remainder) {
     860             :     assert(Numerator && Denominator && "Uninitialized SCEV");
     861             : 
     862       37763 :     SCEVDivision D(SE, Numerator, Denominator);
     863             : 
     864             :     // Check for the trivial case here to avoid having to check for it in the
     865             :     // rest of the code.
     866       37763 :     if (Numerator == Denominator) {
     867       11068 :       *Quotient = D.One;
     868       11068 :       *Remainder = D.Zero;
     869       24820 :       return;
     870             :     }
     871             : 
     872       26695 :     if (Numerator->isZero()) {
     873        2630 :       *Quotient = D.Zero;
     874        2630 :       *Remainder = D.Zero;
     875        2630 :       return;
     876             :     }
     877             : 
     878             :     // A simple case when N/1. The quotient is N.
     879       24065 :     if (Denominator->isOne()) {
     880          44 :       *Quotient = Numerator;
     881          44 :       *Remainder = D.Zero;
     882          44 :       return;
     883             :     }
     884             : 
     885             :     // Split the Denominator when it is a product.
     886             :     if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
     887             :       const SCEV *Q, *R;
     888          10 :       *Quotient = Numerator;
     889          18 :       for (const SCEV *Op : T->operands()) {
     890          12 :         divide(SE, *Quotient, Op, &Q, &R);
     891          12 :         *Quotient = Q;
     892             : 
     893             :         // Bail out when the Numerator is not divisible by one of the terms of
     894             :         // the Denominator.
     895          12 :         if (!R->isZero()) {
     896           8 :           *Quotient = D.Zero;
     897           8 :           *Remainder = Numerator;
     898           8 :           return;
     899             :         }
     900             :       }
     901           2 :       *Remainder = D.Zero;
     902           2 :       return;
     903             :     }
     904             : 
     905       24011 :     D.visit(Numerator);
     906       24011 :     *Quotient = D.Quotient;
     907       24011 :     *Remainder = D.Remainder;
     908             :   }
     909             : 
     910             :   // Except in the trivial case described above, we do not know how to divide
     911             :   // Expr by Denominator for the following functions with empty implementation.
     912             :   void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
     913             :   void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
     914             :   void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
     915             :   void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
     916             :   void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
     917             :   void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
     918             :   void visitUnknown(const SCEVUnknown *Numerator) {}
     919             :   void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
     920             : 
     921        3560 :   void visitConstant(const SCEVConstant *Numerator) {
     922        3560 :     if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
     923             :       APInt NumeratorVal = Numerator->getAPInt();
     924             :       APInt DenominatorVal = D->getAPInt();
     925         384 :       uint32_t NumeratorBW = NumeratorVal.getBitWidth();
     926         384 :       uint32_t DenominatorBW = DenominatorVal.getBitWidth();
     927             : 
     928         384 :       if (NumeratorBW > DenominatorBW)
     929           0 :         DenominatorVal = DenominatorVal.sext(NumeratorBW);
     930         384 :       else if (NumeratorBW < DenominatorBW)
     931           0 :         NumeratorVal = NumeratorVal.sext(DenominatorBW);
     932             : 
     933         384 :       APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
     934         384 :       APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
     935         384 :       APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
     936         384 :       Quotient = SE.getConstant(QuotientVal);
     937         384 :       Remainder = SE.getConstant(RemainderVal);
     938             :       return;
     939             :     }
     940             :   }
     941             : 
     942        9328 :   void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
     943             :     const SCEV *StartQ, *StartR, *StepQ, *StepR;
     944        9328 :     if (!Numerator->isAffine())
     945          13 :       return cannotDivide(Numerator);
     946       18654 :     divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
     947        9327 :     divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
     948             :     // Bail out if the types do not match.
     949        9327 :     Type *Ty = Denominator->getType();
     950       27969 :     if (Ty != StartQ->getType() || Ty != StartR->getType() ||
     951       27957 :         Ty != StepQ->getType() || Ty != StepR->getType())
     952             :       return cannotDivide(Numerator);
     953       18630 :     Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
     954             :                                 Numerator->getNoWrapFlags());
     955       18630 :     Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
     956             :                                  Numerator->getNoWrapFlags());
     957             :   }
     958             : 
     959        1079 :   void visitAddExpr(const SCEVAddExpr *Numerator) {
     960             :     SmallVector<const SCEV *, 2> Qs, Rs;
     961        1079 :     Type *Ty = Denominator->getType();
     962             : 
     963        5461 :     for (const SCEV *Op : Numerator->operands()) {
     964             :       const SCEV *Q, *R;
     965        2191 :       divide(SE, Op, Denominator, &Q, &R);
     966             : 
     967             :       // Bail out if types do not match.
     968        2191 :       if (Ty != Q->getType() || Ty != R->getType())
     969           0 :         return cannotDivide(Numerator);
     970             : 
     971        2191 :       Qs.push_back(Q);
     972        2191 :       Rs.push_back(R);
     973             :     }
     974             : 
     975        1079 :     if (Qs.size() == 1) {
     976           0 :       Quotient = Qs[0];
     977           0 :       Remainder = Rs[0];
     978           0 :       return;
     979             :     }
     980             : 
     981        1079 :     Quotient = SE.getAddExpr(Qs);
     982        1079 :     Remainder = SE.getAddExpr(Rs);
     983             :   }
     984             : 
     985        6996 :   void visitMulExpr(const SCEVMulExpr *Numerator) {
     986             :     SmallVector<const SCEV *, 2> Qs;
     987        6996 :     Type *Ty = Denominator->getType();
     988             : 
     989             :     bool FoundDenominatorTerm = false;
     990       41476 :     for (const SCEV *Op : Numerator->operands()) {
     991             :       // Bail out if types do not match.
     992       17240 :       if (Ty != Op->getType())
     993           0 :         return cannotDivide(Numerator);
     994             : 
     995       24414 :       if (FoundDenominatorTerm) {
     996        7174 :         Qs.push_back(Op);
     997       17478 :         continue;
     998             :       }
     999             : 
    1000             :       // Check whether Denominator divides one of the product operands.
    1001             :       const SCEV *Q, *R;
    1002       10066 :       divide(SE, Op, Denominator, &Q, &R);
    1003       13196 :       if (!R->isZero()) {
    1004        3130 :         Qs.push_back(Op);
    1005        3130 :         continue;
    1006             :       }
    1007             : 
    1008             :       // Bail out if types do not match.
    1009        6936 :       if (Ty != Q->getType())
    1010             :         return cannotDivide(Numerator);
    1011             : 
    1012             :       FoundDenominatorTerm = true;
    1013        6936 :       Qs.push_back(Q);
    1014             :     }
    1015             : 
    1016        6996 :     if (FoundDenominatorTerm) {
    1017        6936 :       Remainder = Zero;
    1018        6936 :       if (Qs.size() == 1)
    1019           0 :         Quotient = Qs[0];
    1020             :       else
    1021        6936 :         Quotient = SE.getMulExpr(Qs);
    1022             :       return;
    1023             :     }
    1024             : 
    1025          60 :     if (!isa<SCEVUnknown>(Denominator))
    1026             :       return cannotDivide(Numerator);
    1027             : 
    1028             :     // The Remainder is obtained by replacing Denominator by 0 in Numerator.
    1029             :     ValueToValueMap RewriteMap;
    1030         108 :     RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
    1031          72 :         cast<SCEVConstant>(Zero)->getValue();
    1032          36 :     Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
    1033             : 
    1034          36 :     if (Remainder->isZero()) {
    1035             :       // The Quotient is obtained by replacing Denominator by 1 in Numerator.
    1036           0 :       RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
    1037           0 :           cast<SCEVConstant>(One)->getValue();
    1038           0 :       Quotient =
    1039           0 :           SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
    1040           0 :       return;
    1041             :     }
    1042             : 
    1043             :     // Quotient is (Numerator - Remainder) divided by Denominator.
    1044             :     const SCEV *Q, *R;
    1045          36 :     const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
    1046             :     // This SCEV does not seem to simplify: fail the division here.
    1047          36 :     if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
    1048             :       return cannotDivide(Numerator);
    1049          36 :     divide(SE, Diff, Denominator, &Q, &R);
    1050          36 :     if (R != Zero)
    1051             :       return cannotDivide(Numerator);
    1052          36 :     Quotient = Q;
    1053             :   }
    1054             : 
    1055             : private:
    1056       37763 :   SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
    1057             :                const SCEV *Denominator)
    1058       37763 :       : SE(S), Denominator(Denominator) {
    1059       75526 :     Zero = SE.getZero(Denominator->getType());
    1060       75526 :     One = SE.getOne(Denominator->getType());
    1061             : 
    1062             :     // We generally do not know how to divide Expr by Denominator. We
    1063             :     // initialize the division to a "cannot divide" state to simplify the rest
    1064             :     // of the code.
    1065             :     cannotDivide(Numerator);
    1066       37763 :   }
    1067             : 
    1068             :   // Convenience function for giving up on the division. We set the quotient to
    1069             :   // be equal to zero and the remainder to be equal to the numerator.
    1070             :   void cannotDivide(const SCEV *Numerator) {
    1071       37800 :     Quotient = Zero;
    1072       37800 :     Remainder = Numerator;
    1073             :   }
    1074             : 
    1075             :   ScalarEvolution &SE;
    1076             :   const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
    1077             : };
    1078             : 
    1079             : } // end anonymous namespace
    1080             : 
    1081             : //===----------------------------------------------------------------------===//
    1082             : //                      Simple SCEV method implementations
    1083             : //===----------------------------------------------------------------------===//
    1084             : 
    1085             : /// Compute BC(It, K).  The result has width W.  Assume, K > 0.
    1086       29871 : static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
    1087             :                                        ScalarEvolution &SE,
    1088             :                                        Type *ResultTy) {
    1089             :   // Handle the simplest case efficiently.
    1090       29871 :   if (K == 1)
    1091       27469 :     return SE.getTruncateOrZeroExtend(It, ResultTy);
    1092             : 
    1093             :   // We are using the following formula for BC(It, K):
    1094             :   //
    1095             :   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
    1096             :   //
    1097             :   // Suppose, W is the bitwidth of the return value.  We must be prepared for
    1098             :   // overflow.  Hence, we must assure that the result of our computation is
    1099             :   // equal to the accurate one modulo 2^W.  Unfortunately, division isn't
    1100             :   // safe in modular arithmetic.
    1101             :   //
    1102             :   // However, this code doesn't use exactly that formula; the formula it uses
    1103             :   // is something like the following, where T is the number of factors of 2 in
    1104             :   // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
    1105             :   // exponentiation:
    1106             :   //
    1107             :   //   BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
    1108             :   //
    1109             :   // This formula is trivially equivalent to the previous formula.  However,
    1110             :   // this formula can be implemented much more efficiently.  The trick is that
    1111             :   // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
    1112             :   // arithmetic.  To do exact division in modular arithmetic, all we have
    1113             :   // to do is multiply by the inverse.  Therefore, this step can be done at
    1114             :   // width W.
    1115             :   //
    1116             :   // The next issue is how to safely do the division by 2^T.  The way this
    1117             :   // is done is by doing the multiplication step at a width of at least W + T
    1118             :   // bits.  This way, the bottom W+T bits of the product are accurate. Then,
    1119             :   // when we perform the division by 2^T (which is equivalent to a right shift
    1120             :   // by T), the bottom W bits are accurate.  Extra bits are okay; they'll get
    1121             :   // truncated out after the division by 2^T.
    1122             :   //
    1123             :   // In comparison to just directly using the first formula, this technique
    1124             :   // is much more efficient; using the first formula requires W * K bits,
    1125             :   // but this formula less than W + K bits. Also, the first formula requires
    1126             :   // a division step, whereas this formula only requires multiplies and shifts.
    1127             :   //
    1128             :   // It doesn't matter whether the subtraction step is done in the calculation
    1129             :   // width or the input iteration count's width; if the subtraction overflows,
    1130             :   // the result must be zero anyway.  We prefer here to do it in the width of
    1131             :   // the induction variable because it helps a lot for certain cases; CodeGen
    1132             :   // isn't smart enough to ignore the overflow, which leads to much less
    1133             :   // efficient code if the width of the subtraction is wider than the native
    1134             :   // register width.
    1135             :   //
    1136             :   // (It's possible to not widen at all by pulling out factors of 2 before
    1137             :   // the multiplication; for example, K=2 can be calculated as
    1138             :   // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
    1139             :   // extra arithmetic, so it's not an obvious win, and it gets
    1140             :   // much more complicated for K > 3.)
    1141             : 
    1142             :   // Protection from insane SCEVs; this bound is conservative,
    1143             :   // but it probably doesn't matter.
    1144        2402 :   if (K > 1000)
    1145           0 :     return SE.getCouldNotCompute();
    1146             : 
    1147        2402 :   unsigned W = SE.getTypeSizeInBits(ResultTy);
    1148             : 
    1149             :   // Calculate K! / 2^T and T; we divide out the factors of two before
    1150             :   // multiplying for calculating K! / 2^T to avoid overflow.
    1151             :   // Other overflow doesn't matter because we only care about the bottom
    1152             :   // W bits of the result.
    1153             :   APInt OddFactorial(W, 1);
    1154             :   unsigned T = 1;
    1155        5870 :   for (unsigned i = 3; i <= K; ++i) {
    1156        1734 :     APInt Mult(W, i);
    1157        1734 :     unsigned TwoFactors = Mult.countTrailingZeros();
    1158        1734 :     T += TwoFactors;
    1159             :     Mult.lshrInPlace(TwoFactors);
    1160        1734 :     OddFactorial *= Mult;
    1161             :   }
    1162             : 
    1163             :   // We need at least W + T bits for the multiplication step
    1164        2402 :   unsigned CalculationBits = W + T;
    1165             : 
    1166             :   // Calculate 2^T, at width T+W.
    1167        2402 :   APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
    1168             : 
    1169             :   // Calculate the multiplicative inverse of K! / 2^T;
    1170             :   // this multiplication factor will perform the exact division by
    1171             :   // K! / 2^T.
    1172        2402 :   APInt Mod = APInt::getSignedMinValue(W+1);
    1173        2402 :   APInt MultiplyFactor = OddFactorial.zext(W+1);
    1174        4804 :   MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
    1175        4804 :   MultiplyFactor = MultiplyFactor.trunc(W);
    1176             : 
    1177             :   // Calculate the product, at width T+W
    1178        2402 :   IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
    1179        2402 :                                                       CalculationBits);
    1180        2402 :   const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
    1181       10674 :   for (unsigned i = 1; i != K; ++i) {
    1182        4136 :     const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
    1183        4136 :     Dividend = SE.getMulExpr(Dividend,
    1184             :                              SE.getTruncateOrZeroExtend(S, CalculationTy));
    1185             :   }
    1186             : 
    1187             :   // Divide by 2^T
    1188        2402 :   const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
    1189             : 
    1190             :   // Truncate the result, and divide by K! / 2^T.
    1191             : 
    1192        2402 :   return SE.getMulExpr(SE.getConstant(MultiplyFactor),
    1193        2402 :                        SE.getTruncateOrZeroExtend(DivResult, ResultTy));
    1194             : }
    1195             : 
    1196             : /// Return the value of this chain of recurrences at the specified iteration
    1197             : /// number.  We can evaluate this recurrence by multiplying each element in the
    1198             : /// chain by the binomial coefficient corresponding to it.  In other words, we
    1199             : /// can evaluate {A,+,B,+,C,+,D} as:
    1200             : ///
    1201             : ///   A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
    1202             : ///
    1203             : /// where BC(It, k) stands for binomial coefficient.
    1204       27469 : const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
    1205             :                                                 ScalarEvolution &SE) const {
    1206       27469 :   const SCEV *Result = getStart();
    1207       57340 :   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
    1208             :     // The computation is correct in the face of overflow provided that the
    1209             :     // multiplication is performed _after_ the evaluation of the binomial
    1210             :     // coefficient.
    1211       29871 :     const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
    1212       29871 :     if (isa<SCEVCouldNotCompute>(Coeff))
    1213             :       return Coeff;
    1214             : 
    1215       59742 :     Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
    1216             :   }
    1217             :   return Result;
    1218             : }
    1219             : 
    1220             : //===----------------------------------------------------------------------===//
    1221             : //                    SCEV Expression folder implementations
    1222             : //===----------------------------------------------------------------------===//
    1223             : 
    1224       25994 : const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
    1225             :                                              Type *Ty) {
    1226             :   assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
    1227             :          "This is not a truncating conversion!");
    1228             :   assert(isSCEVable(Ty) &&
    1229             :          "This is not a conversion to a SCEVable type!");
    1230       25994 :   Ty = getEffectiveSCEVType(Ty);
    1231             : 
    1232             :   FoldingSetNodeID ID;
    1233       25994 :   ID.AddInteger(scTruncate);
    1234       25994 :   ID.AddPointer(Op);
    1235       25994 :   ID.AddPointer(Ty);
    1236       25994 :   void *IP = nullptr;
    1237       25994 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1238             : 
    1239             :   // Fold if the operand is constant.
    1240             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    1241       13447 :     return getConstant(
    1242       26894 :       cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
    1243             : 
    1244             :   // trunc(trunc(x)) --> trunc(x)
    1245             :   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
    1246          19 :     return getTruncateExpr(ST->getOperand(), Ty);
    1247             : 
    1248             :   // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
    1249             :   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
    1250         245 :     return getTruncateOrSignExtend(SS->getOperand(), Ty);
    1251             : 
    1252             :   // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
    1253             :   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
    1254         880 :     return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
    1255             : 
    1256             :   // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
    1257             :   // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
    1258             :   // if after transforming we have at most one truncate, not counting truncates
    1259             :   // that replace other casts.
    1260        8642 :   if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
    1261             :     auto *CommOp = cast<SCEVCommutativeExpr>(Op);
    1262             :     SmallVector<const SCEV *, 4> Operands;
    1263             :     unsigned numTruncs = 0;
    1264        5107 :     for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
    1265             :          ++i) {
    1266        6860 :       const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty);
    1267        5901 :       if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
    1268        1095 :         numTruncs++;
    1269        3430 :       Operands.push_back(S);
    1270             :     }
    1271        1677 :     if (numTruncs < 2) {
    1272        1539 :       if (isa<SCEVAddExpr>(Op))
    1273         955 :         return getAddExpr(Operands);
    1274         584 :       else if (isa<SCEVMulExpr>(Op))
    1275         584 :         return getMulExpr(Operands);
    1276             :       else
    1277           0 :         llvm_unreachable("Unexpected SCEV type for Op.");
    1278             :     }
    1279             :     // Although we checked in the beginning that ID is not in the cache, it is
    1280             :     // possible that during recursion and different modification ID was inserted
    1281             :     // into the cache. So if we find it, just return it.
    1282         138 :     if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
    1283             :       return S;
    1284             :   }
    1285             : 
    1286             :   // If the input value is a chrec scev, truncate the chrec's operands.
    1287             :   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
    1288             :     SmallVector<const SCEV *, 4> Operands;
    1289       15804 :     for (const SCEV *Op : AddRec->operands())
    1290        6324 :       Operands.push_back(getTruncateExpr(Op, Ty));
    1291        3156 :     return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
    1292             :   }
    1293             : 
    1294             :   // The cast wasn't folded; create an explicit cast node. We can reuse
    1295             :   // the existing insert position since if we get here, we won't have
    1296             :   // made any changes which would invalidate it.
    1297        7894 :   SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
    1298        3947 :                                                  Op, Ty);
    1299        3947 :   UniqueSCEVs.InsertNode(S, IP);
    1300        3947 :   addToLoopUseLists(S);
    1301        3947 :   return S;
    1302             : }
    1303             : 
    1304             : // Get the limit of a recurrence such that incrementing by Step cannot cause
    1305             : // signed overflow as long as the value of the recurrence within the
    1306             : // loop does not exceed this limit before incrementing.
    1307        5216 : static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
    1308             :                                                  ICmpInst::Predicate *Pred,
    1309             :                                                  ScalarEvolution *SE) {
    1310        5216 :   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
    1311        5216 :   if (SE->isKnownPositive(Step)) {
    1312        3199 :     *Pred = ICmpInst::ICMP_SLT;
    1313        9597 :     return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
    1314        6398 :                            SE->getSignedRangeMax(Step));
    1315             :   }
    1316        2017 :   if (SE->isKnownNegative(Step)) {
    1317        1899 :     *Pred = ICmpInst::ICMP_SGT;
    1318        5697 :     return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
    1319        3798 :                            SE->getSignedRangeMin(Step));
    1320             :   }
    1321             :   return nullptr;
    1322             : }
    1323             : 
    1324             : // Get the limit of a recurrence such that incrementing by Step cannot cause
    1325             : // unsigned overflow as long as the value of the recurrence within the loop does
    1326             : // not exceed this limit before incrementing.
    1327         543 : static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
    1328             :                                                    ICmpInst::Predicate *Pred,
    1329             :                                                    ScalarEvolution *SE) {
    1330         543 :   unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
    1331         543 :   *Pred = ICmpInst::ICMP_ULT;
    1332             : 
    1333        1629 :   return SE->getConstant(APInt::getMinValue(BitWidth) -
    1334        1086 :                          SE->getUnsignedRangeMax(Step));
    1335             : }
    1336             : 
    1337             : namespace {
    1338             : 
    1339             : struct ExtendOpTraitsBase {
    1340             :   typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
    1341             :                                                           unsigned);
    1342             : };
    1343             : 
    1344             : // Used to make code generic over signed and unsigned overflow.
    1345             : template <typename ExtendOp> struct ExtendOpTraits {
    1346             :   // Members present:
    1347             :   //
    1348             :   // static const SCEV::NoWrapFlags WrapType;
    1349             :   //
    1350             :   // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
    1351             :   //
    1352             :   // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
    1353             :   //                                           ICmpInst::Predicate *Pred,
    1354             :   //                                           ScalarEvolution *SE);
    1355             : };
    1356             : 
    1357             : template <>
    1358             : struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
    1359             :   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
    1360             : 
    1361             :   static const GetExtendExprTy GetExtendExpr;
    1362             : 
    1363         115 :   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
    1364             :                                              ICmpInst::Predicate *Pred,
    1365             :                                              ScalarEvolution *SE) {
    1366         149 :     return getSignedOverflowLimitForStep(Step, Pred, SE);
    1367             :   }
    1368             : };
    1369             : 
    1370             : const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
    1371             :     SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
    1372             : 
    1373             : template <>
    1374             : struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
    1375             :   static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
    1376             : 
    1377             :   static const GetExtendExprTy GetExtendExpr;
    1378             : 
    1379         244 :   static const SCEV *getOverflowLimitForStep(const SCEV *Step,
    1380             :                                              ICmpInst::Predicate *Pred,
    1381             :                                              ScalarEvolution *SE) {
    1382         543 :     return getUnsignedOverflowLimitForStep(Step, Pred, SE);
    1383             :   }
    1384             : };
    1385             : 
    1386             : const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
    1387             :     SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
    1388             : 
    1389             : } // end anonymous namespace
    1390             : 
    1391             : // The recurrence AR has been shown to have no signed/unsigned wrap or something
    1392             : // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
    1393             : // easily prove NSW/NUW for its preincrement or postincrement sibling. This
    1394             : // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
    1395             : // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
    1396             : // expression "Step + sext/zext(PreIncAR)" is congruent with
    1397             : // "sext/zext(PostIncAR)"
    1398             : template <typename ExtendOpTy>
    1399       32072 : static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
    1400             :                                         ScalarEvolution *SE, unsigned Depth) {
    1401             :   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
    1402             :   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
    1403             : 
    1404       32072 :   const Loop *L = AR->getLoop();
    1405       32072 :   const SCEV *Start = AR->getStart();
    1406       32072 :   const SCEV *Step = AR->getStepRecurrence(*SE);
    1407             : 
    1408             :   // Check for a simple looking step prior to loop entry.
    1409             :   const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
    1410             :   if (!SA)
    1411             :     return nullptr;
    1412             : 
    1413             :   // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
    1414             :   // subtraction is expensive. For this purpose, perform a quick and dirty
    1415             :   // difference, by checking for Step in the operand list.
    1416             :   SmallVector<const SCEV *, 4> DiffOps;
    1417        4492 :   for (const SCEV *Op : SA->operands())
    1418        1802 :     if (Op != Step)
    1419        1200 :       DiffOps.push_back(Op);
    1420             : 
    1421         888 :   if (DiffOps.size() == SA->getNumOperands())
    1422             :     return nullptr;
    1423             : 
    1424             :   // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
    1425             :   // `Step`:
    1426             : 
    1427             :   // 1. NSW/NUW flags on the step increment.
    1428             :   auto PreStartFlags =
    1429         602 :     ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
    1430         602 :   const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
    1431         602 :   const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
    1432             :       SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
    1433             : 
    1434             :   // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
    1435             :   // "S+X does not sign/unsign-overflow".
    1436             :   //
    1437             : 
    1438         602 :   const SCEV *BECount = SE->getBackedgeTakenCount(L);
    1439        1432 :   if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
    1440         793 :       !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
    1441             :     return PreStart;
    1442             : 
    1443             :   // 2. Direct overflow check on the step operation's expression.
    1444         593 :   unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
    1445        1186 :   Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
    1446         593 :   const SCEV *OperandExtendedStart =
    1447             :       SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
    1448             :                      (SE->*GetExtendExpr)(Step, WideTy, Depth));
    1449         593 :   if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
    1450         358 :     if (PreAR && AR->getNoWrapFlags(WrapType)) {
    1451             :       // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
    1452             :       // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
    1453             :       // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`.  Cache this fact.
    1454             :       const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
    1455             :     }
    1456             :     return PreStart;
    1457             :   }
    1458             : 
    1459             :   // 3. Loop precondition.
    1460             :   ICmpInst::Predicate Pred;
    1461         115 :   const SCEV *OverflowLimit =
    1462             :       ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
    1463             : 
    1464         828 :   if (OverflowLimit &&
    1465         414 :       SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
    1466             :     return PreStart;
    1467             : 
    1468             :   return nullptr;
    1469             : }
    1470             : 
    1471             : // Get the normalized zero or sign extended expression for this AddRec's Start.
    1472             : template <typename ExtendOpTy>
    1473       32072 : static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
    1474             :                                         ScalarEvolution *SE,
    1475             :                                         unsigned Depth) {
    1476             :   auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
    1477             : 
    1478       32072 :   const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
    1479       32072 :   if (!PreStart)
    1480       63596 :     return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
    1481             : 
    1482             :   return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
    1483             :                                              Depth),
    1484         274 :                         (SE->*GetExtendExpr)(PreStart, Ty, Depth));
    1485             : }
    1486             : 
    1487             : // Try to prove away overflow by looking at "nearby" add recurrences.  A
    1488             : // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
    1489             : // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
    1490             : //
    1491             : // Formally:
    1492             : //
    1493             : //     {S,+,X} == {S-T,+,X} + T
    1494             : //  => Ext({S,+,X}) == Ext({S-T,+,X} + T)
    1495             : //
    1496             : // If ({S-T,+,X} + T) does not overflow  ... (1)
    1497             : //
    1498             : //  RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
    1499             : //
    1500             : // If {S-T,+,X} does not overflow  ... (2)
    1501             : //
    1502             : //  RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
    1503             : //      == {Ext(S-T)+Ext(T),+,Ext(X)}
    1504             : //
    1505             : // If (S-T)+T does not overflow  ... (3)
    1506             : //
    1507             : //  RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
    1508             : //      == {Ext(S),+,Ext(X)} == LHS
    1509             : //
    1510             : // Thus, if (1), (2) and (3) are true for some T, then
    1511             : //   Ext({S,+,X}) == {Ext(S),+,Ext(X)}
    1512             : //
    1513             : // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
    1514             : // does not overflow" restricted to the 0th iteration.  Therefore we only need
    1515             : // to check for (1) and (2).
    1516             : //
    1517             : // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
    1518             : // is `Delta` (defined below).
    1519             : template <typename ExtendOpTy>
    1520       15031 : bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
    1521             :                                                 const SCEV *Step,
    1522             :                                                 const Loop *L) {
    1523             :   auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
    1524             : 
    1525             :   // We restrict `Start` to a constant to prevent SCEV from spending too much
    1526             :   // time here.  It is correct (but more expensive) to continue with a
    1527             :   // non-constant `Start` and do a general SCEV subtraction to compute
    1528             :   // `PreStart` below.
    1529             :   const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
    1530             :   if (!StartC)
    1531             :     return false;
    1532             : 
    1533             :   APInt StartAI = StartC->getAPInt();
    1534             : 
    1535       50952 :   for (unsigned Delta : {-2, -1, 1, 2}) {
    1536       90592 :     const SCEV *PreStart = getConstant(StartAI - Delta);
    1537             : 
    1538             :     FoldingSetNodeID ID;
    1539       22648 :     ID.AddInteger(scAddRecExpr);
    1540       22648 :     ID.AddPointer(PreStart);
    1541       22648 :     ID.AddPointer(Step);
    1542       22648 :     ID.AddPointer(L);
    1543       22648 :     void *IP = nullptr;
    1544             :     const auto *PreAR =
    1545             :       static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    1546             : 
    1547             :     // Give up if we don't already have the add recurrence we need because
    1548             :     // actually constructing an add recurrence is relatively expensive.
    1549       29659 :     if (PreAR && PreAR->getNoWrapFlags(WrapType)) {  // proves (2)
    1550         556 :       const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
    1551         278 :       ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
    1552         244 :       const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
    1553             :           DeltaS, &Pred, this);
    1554         278 :       if (Limit && isKnownPredicate(Pred, PreAR, Limit))  // proves (1)
    1555           3 :         return true;
    1556             :     }
    1557             :   }
    1558             : 
    1559             :   return false;
    1560             : }
    1561             : 
    1562             : const SCEV *
    1563      242864 : ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
    1564             :   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
    1565             :          "This is not an extending conversion!");
    1566             :   assert(isSCEVable(Ty) &&
    1567             :          "This is not a conversion to a SCEVable type!");
    1568      242864 :   Ty = getEffectiveSCEVType(Ty);
    1569             : 
    1570             :   // Fold if the operand is constant.
    1571             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    1572      121588 :     return getConstant(
    1573      243176 :       cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
    1574             : 
    1575             :   // zext(zext(x)) --> zext(x)
    1576             :   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
    1577        6790 :     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
    1578             : 
    1579             :   // Before doing any expensive analysis, check to see if we've already
    1580             :   // computed a SCEV for this Op and Ty.
    1581             :   FoldingSetNodeID ID;
    1582      114486 :   ID.AddInteger(scZeroExtend);
    1583      114486 :   ID.AddPointer(Op);
    1584      114486 :   ID.AddPointer(Ty);
    1585      114486 :   void *IP = nullptr;
    1586      114486 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1587       62267 :   if (Depth > MaxExtDepth) {
    1588          24 :     SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
    1589          12 :                                                      Op, Ty);
    1590          12 :     UniqueSCEVs.InsertNode(S, IP);
    1591          12 :     addToLoopUseLists(S);
    1592          12 :     return S;
    1593             :   }
    1594             : 
    1595             :   // zext(trunc(x)) --> zext(x) or x or trunc(x)
    1596             :   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
    1597             :     // It's possible the bits taken off by the truncate were all zero bits. If
    1598             :     // so, we should be able to simplify this further.
    1599        1498 :     const SCEV *X = ST->getOperand();
    1600        2792 :     ConstantRange CR = getUnsignedRange(X);
    1601        1498 :     unsigned TruncBits = getTypeSizeInBits(ST->getType());
    1602        1498 :     unsigned NewBits = getTypeSizeInBits(Ty);
    1603        4494 :     if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
    1604        2996 :             CR.zextOrTrunc(NewBits)))
    1605         204 :       return getTruncateOrZeroExtend(X, Ty);
    1606             :   }
    1607             : 
    1608             :   // If the input value is a chrec scev, and we can prove that the value
    1609             :   // did not overflow the old, smaller, value, we can zero extend all of the
    1610             :   // operands (often constants).  This allows analysis of something like
    1611             :   // this:  for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
    1612             :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
    1613       28736 :     if (AR->isAffine()) {
    1614       28666 :       const SCEV *Start = AR->getStart();
    1615       28666 :       const SCEV *Step = AR->getStepRecurrence(*this);
    1616       28666 :       unsigned BitWidth = getTypeSizeInBits(AR->getType());
    1617       28666 :       const Loop *L = AR->getLoop();
    1618             : 
    1619       28666 :       if (!AR->hasNoUnsignedWrap()) {
    1620       22009 :         auto NewFlags = proveNoWrapViaConstantRanges(AR);
    1621             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
    1622             :       }
    1623             : 
    1624             :       // If we have special knowledge that this addrec won't overflow,
    1625             :       // we don't need to do any further analysis.
    1626       28666 :       if (AR->hasNoUnsignedWrap())
    1627        8938 :         return getAddRecExpr(
    1628             :             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
    1629        8938 :             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    1630             : 
    1631             :       // Check whether the backedge-taken count is SCEVCouldNotCompute.
    1632             :       // Note that this serves two purposes: It filters out loops that are
    1633             :       // simply not analyzable, and it covers the case where this code is
    1634             :       // being called from within backedge-taken count analysis, such that
    1635             :       // attempting to ask for the backedge-taken count would likely result
    1636             :       // in infinite recursion. In the later case, the analysis code will
    1637             :       // cope with a conservative value, and it will take care to purge
    1638             :       // that value once it has finished.
    1639       19728 :       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
    1640       19728 :       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
    1641             :         // Manually compute the final value for AR, checking for
    1642             :         // overflow.
    1643             : 
    1644             :         // Check whether the backedge-taken count can be losslessly casted to
    1645             :         // the addrec's type. The count is always unsigned.
    1646             :         const SCEV *CastedMaxBECount =
    1647       17062 :           getTruncateOrZeroExtend(MaxBECount, Start->getType());
    1648             :         const SCEV *RecastedMaxBECount =
    1649       17062 :           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
    1650       17062 :         if (MaxBECount == RecastedMaxBECount) {
    1651       31508 :           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
    1652             :           // Check whether Start+Step*MaxBECount has no unsigned overflow.
    1653       15754 :           const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
    1654       15754 :                                         SCEV::FlagAnyWrap, Depth + 1);
    1655       15754 :           const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
    1656             :                                                           SCEV::FlagAnyWrap,
    1657             :                                                           Depth + 1),
    1658       15754 :                                                WideTy, Depth + 1);
    1659       15754 :           const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
    1660             :           const SCEV *WideMaxBECount =
    1661       15754 :             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
    1662             :           const SCEV *OperandExtendedAdd =
    1663       15754 :             getAddExpr(WideStart,
    1664             :                        getMulExpr(WideMaxBECount,
    1665             :                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
    1666             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1667       15754 :                        SCEV::FlagAnyWrap, Depth + 1);
    1668       15754 :           if (ZAdd == OperandExtendedAdd) {
    1669             :             // Cache knowledge of AR NUW, which is propagated to this AddRec.
    1670             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
    1671             :             // Return the expression with the addrec on the outside.
    1672         800 :             return getAddRecExpr(
    1673             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1674             :                                                          Depth + 1),
    1675             :                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
    1676         800 :                 AR->getNoWrapFlags());
    1677             :           }
    1678             :           // Similar to above, only this time treat the step value as signed.
    1679             :           // This covers loops that count down.
    1680       14954 :           OperandExtendedAdd =
    1681       14954 :             getAddExpr(WideStart,
    1682             :                        getMulExpr(WideMaxBECount,
    1683             :                                   getSignExtendExpr(Step, WideTy, Depth + 1),
    1684             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1685             :                        SCEV::FlagAnyWrap, Depth + 1);
    1686       14954 :           if (ZAdd == OperandExtendedAdd) {
    1687             :             // Cache knowledge of AR NW, which is propagated to this AddRec.
    1688             :             // Negative step causes unsigned wrap, but it still can't self-wrap.
    1689             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
    1690             :             // Return the expression with the addrec on the outside.
    1691         980 :             return getAddRecExpr(
    1692             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1693             :                                                          Depth + 1),
    1694             :                 getSignExtendExpr(Step, Ty, Depth + 1), L,
    1695         980 :                 AR->getNoWrapFlags());
    1696             :           }
    1697             :         }
    1698             :       }
    1699             : 
    1700             :       // Normally, in the cases we can prove no-overflow via a
    1701             :       // backedge guarding condition, we can also compute a backedge
    1702             :       // taken count for the loop.  The exceptions are assumptions and
    1703             :       // guards present in the loop -- SCEV is not great at exploiting
    1704             :       // these to compute max backedge taken counts, but can still use
    1705             :       // these to prove lack of overflow.  Use this fact to avoid
    1706             :       // doing extra work that may not pay off.
    1707       20605 :       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
    1708        2657 :           !AC.assumptions().empty()) {
    1709             :         // If the backedge is guarded by a comparison with the pre-inc
    1710             :         // value the addrec is safe. Also, if the entry is guarded by
    1711             :         // a comparison with the start value and the backedge is
    1712             :         // guarded by a comparison with the post-inc value, the addrec
    1713             :         // is safe.
    1714       15324 :         if (isKnownPositive(Step)) {
    1715        8694 :           const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
    1716        8694 :                                       getUnsignedRangeMax(Step));
    1717        5750 :           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
    1718        2852 :               isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
    1719             :             // Cache knowledge of AR NUW, which is propagated to this
    1720             :             // AddRec.
    1721             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
    1722             :             // Return the expression with the addrec on the outside.
    1723          79 :             return getAddRecExpr(
    1724             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1725             :                                                          Depth + 1),
    1726             :                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
    1727          79 :                 AR->getNoWrapFlags());
    1728             :           }
    1729       12426 :         } else if (isKnownNegative(Step)) {
    1730       36846 :           const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
    1731       36846 :                                       getSignedRangeMin(Step));
    1732       14249 :           if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
    1733        1967 :               isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
    1734             :             // Cache knowledge of AR NW, which is propagated to this
    1735             :             // AddRec.  Negative step causes unsigned wrap, but it
    1736             :             // still can't self-wrap.
    1737             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
    1738             :             // Return the expression with the addrec on the outside.
    1739       10469 :             return getAddRecExpr(
    1740             :                 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
    1741             :                                                          Depth + 1),
    1742             :                 getSignExtendExpr(Step, Ty, Depth + 1), L,
    1743       10469 :                 AR->getNoWrapFlags());
    1744             :           }
    1745             :         }
    1746             :       }
    1747             : 
    1748        7400 :       if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
    1749             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
    1750           3 :         return getAddRecExpr(
    1751             :             getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
    1752           3 :             getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    1753             :       }
    1754             :     }
    1755             : 
    1756             :   // zext(A % B) --> zext(A) % zext(B)
    1757             :   {
    1758             :     const SCEV *LHS;
    1759             :     const SCEV *RHS;
    1760       40782 :     if (matchURem(Op, LHS, RHS))
    1761          36 :       return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
    1762          36 :                          getZeroExtendExpr(RHS, Ty, Depth + 1));
    1763             :   }
    1764             : 
    1765             :   // zext(A / B) --> zext(A) / zext(B).
    1766             :   if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
    1767        5284 :     return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
    1768        5284 :                        getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
    1769             : 
    1770             :   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
    1771             :     // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
    1772        7896 :     if (SA->hasNoUnsignedWrap()) {
    1773             :       // If the addition does not unsign overflow then we can, by definition,
    1774             :       // commute the zero extension with the addition operation.
    1775             :       SmallVector<const SCEV *, 4> Ops;
    1776        1925 :       for (const auto *Op : SA->operands())
    1777         770 :         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
    1778         385 :       return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
    1779             :     }
    1780             :   }
    1781             : 
    1782             :   if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
    1783             :     // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
    1784        3641 :     if (SM->hasNoUnsignedWrap()) {
    1785             :       // If the multiply does not unsign overflow then we can, by definition,
    1786             :       // commute the zero extension with the multiply operation.
    1787             :       SmallVector<const SCEV *, 4> Ops;
    1788          15 :       for (const auto *Op : SM->operands())
    1789           6 :         Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
    1790           3 :       return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
    1791             :     }
    1792             : 
    1793             :     // zext(2^K * (trunc X to iN)) to iM ->
    1794             :     // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
    1795             :     //
    1796             :     // Proof:
    1797             :     //
    1798             :     //     zext(2^K * (trunc X to iN)) to iM
    1799             :     //   = zext((trunc X to iN) << K) to iM
    1800             :     //   = zext((trunc X to i{N-K}) << K)<nuw> to iM
    1801             :     //     (because shl removes the top K bits)
    1802             :     //   = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
    1803             :     //   = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
    1804             :     //
    1805        3638 :     if (SM->getNumOperands() == 2)
    1806        3611 :       if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
    1807        2563 :         if (MulLHS->getAPInt().isPowerOf2())
    1808             :           if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
    1809          22 :             int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
    1810             :                                MulLHS->getAPInt().logBase2();
    1811          22 :             Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
    1812          11 :             return getMulExpr(
    1813             :                 getZeroExtendExpr(MulLHS, Ty),
    1814             :                 getZeroExtendExpr(
    1815             :                     getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
    1816          11 :                 SCEV::FlagNUW, Depth + 1);
    1817             :           }
    1818             :   }
    1819             : 
    1820             :   // The cast wasn't folded; create an explicit cast node.
    1821             :   // Recompute the insert position, as it may have been invalidated.
    1822       35063 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1823       68124 :   SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
    1824       34062 :                                                    Op, Ty);
    1825       34062 :   UniqueSCEVs.InsertNode(S, IP);
    1826       34062 :   addToLoopUseLists(S);
    1827       34062 :   return S;
    1828             : }
    1829             : 
    1830             : const SCEV *
    1831      147939 : ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
    1832             :   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
    1833             :          "This is not an extending conversion!");
    1834             :   assert(isSCEVable(Ty) &&
    1835             :          "This is not a conversion to a SCEVable type!");
    1836      147939 :   Ty = getEffectiveSCEVType(Ty);
    1837             : 
    1838             :   // Fold if the operand is constant.
    1839             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    1840       95776 :     return getConstant(
    1841      191552 :       cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
    1842             : 
    1843             :   // sext(sext(x)) --> sext(x)
    1844             :   if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
    1845         275 :     return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
    1846             : 
    1847             :   // sext(zext(x)) --> zext(x)
    1848             :   if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
    1849         221 :     return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
    1850             : 
    1851             :   // Before doing any expensive analysis, check to see if we've already
    1852             :   // computed a SCEV for this Op and Ty.
    1853             :   FoldingSetNodeID ID;
    1854       51667 :   ID.AddInteger(scSignExtend);
    1855       51667 :   ID.AddPointer(Op);
    1856       51667 :   ID.AddPointer(Ty);
    1857       51667 :   void *IP = nullptr;
    1858       51667 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    1859             :   // Limit recursion depth.
    1860       39247 :   if (Depth > MaxExtDepth) {
    1861           8 :     SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
    1862           4 :                                                      Op, Ty);
    1863           4 :     UniqueSCEVs.InsertNode(S, IP);
    1864           4 :     addToLoopUseLists(S);
    1865           4 :     return S;
    1866             :   }
    1867             : 
    1868             :   // sext(trunc(x)) --> sext(x) or x or trunc(x)
    1869             :   if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
    1870             :     // It's possible the bits taken off by the truncate were all sign bits. If
    1871             :     // so, we should be able to simplify this further.
    1872         382 :     const SCEV *X = ST->getOperand();
    1873         759 :     ConstantRange CR = getSignedRange(X);
    1874         382 :     unsigned TruncBits = getTypeSizeInBits(ST->getType());
    1875         382 :     unsigned NewBits = getTypeSizeInBits(Ty);
    1876        1146 :     if (CR.truncate(TruncBits).signExtend(NewBits).contains(
    1877         764 :             CR.sextOrTrunc(NewBits)))
    1878           5 :       return getTruncateOrSignExtend(X, Ty);
    1879             :   }
    1880             : 
    1881             :   // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
    1882             :   if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
    1883        5675 :     if (SA->getNumOperands() == 2) {
    1884        5393 :       auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
    1885             :       auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
    1886        5393 :       if (SMul && SC1) {
    1887        1629 :         if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
    1888             :           const APInt &C1 = SC1->getAPInt();
    1889             :           const APInt &C2 = SC2->getAPInt();
    1890        3038 :           if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
    1891        1665 :               C2.ugt(C1) && C2.isPowerOf2())
    1892          21 :             return getAddExpr(getSignExtendExpr(SC1, Ty, Depth + 1),
    1893             :                               getSignExtendExpr(SMul, Ty, Depth + 1),
    1894          21 :                               SCEV::FlagAnyWrap, Depth + 1);
    1895             :         }
    1896             :       }
    1897             :     }
    1898             : 
    1899             :     // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
    1900        5654 :     if (SA->hasNoSignedWrap()) {
    1901             :       // If the addition does not sign overflow then we can, by definition,
    1902             :       // commute the sign extension with the addition operation.
    1903             :       SmallVector<const SCEV *, 4> Ops;
    1904        2625 :       for (const auto *Op : SA->operands())
    1905        1050 :         Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
    1906         525 :       return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
    1907             :     }
    1908             :   }
    1909             :   // If the input value is a chrec scev, and we can prove that the value
    1910             :   // did not overflow the old, smaller, value, we can sign extend all of the
    1911             :   // operands (often constants).  This allows analysis of something like
    1912             :   // this:  for (signed char X = 0; X < 100; ++X) { int Y = X; }
    1913             :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
    1914       19281 :     if (AR->isAffine()) {
    1915       19228 :       const SCEV *Start = AR->getStart();
    1916       19228 :       const SCEV *Step = AR->getStepRecurrence(*this);
    1917       19228 :       unsigned BitWidth = getTypeSizeInBits(AR->getType());
    1918       19228 :       const Loop *L = AR->getLoop();
    1919             : 
    1920       19228 :       if (!AR->hasNoSignedWrap()) {
    1921       11432 :         auto NewFlags = proveNoWrapViaConstantRanges(AR);
    1922             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
    1923             :       }
    1924             : 
    1925             :       // If we have special knowledge that this addrec won't overflow,
    1926             :       // we don't need to do any further analysis.
    1927       19228 :       if (AR->hasNoSignedWrap())
    1928       10310 :         return getAddRecExpr(
    1929             :             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
    1930       10310 :             getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
    1931             : 
    1932             :       // Check whether the backedge-taken count is SCEVCouldNotCompute.
    1933             :       // Note that this serves two purposes: It filters out loops that are
    1934             :       // simply not analyzable, and it covers the case where this code is
    1935             :       // being called from within backedge-taken count analysis, such that
    1936             :       // attempting to ask for the backedge-taken count would likely result
    1937             :       // in infinite recursion. In the later case, the analysis code will
    1938             :       // cope with a conservative value, and it will take care to purge
    1939             :       // that value once it has finished.
    1940        8918 :       const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
    1941        8918 :       if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
    1942             :         // Manually compute the final value for AR, checking for
    1943             :         // overflow.
    1944             : 
    1945             :         // Check whether the backedge-taken count can be losslessly casted to
    1946             :         // the addrec's type. The count is always unsigned.
    1947             :         const SCEV *CastedMaxBECount =
    1948        5363 :           getTruncateOrZeroExtend(MaxBECount, Start->getType());
    1949             :         const SCEV *RecastedMaxBECount =
    1950        5363 :           getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
    1951        5363 :         if (MaxBECount == RecastedMaxBECount) {
    1952       10150 :           Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
    1953             :           // Check whether Start+Step*MaxBECount has no signed overflow.
    1954        5075 :           const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
    1955        5075 :                                         SCEV::FlagAnyWrap, Depth + 1);
    1956        5075 :           const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
    1957             :                                                           SCEV::FlagAnyWrap,
    1958             :                                                           Depth + 1),
    1959        5075 :                                                WideTy, Depth + 1);
    1960        5075 :           const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
    1961             :           const SCEV *WideMaxBECount =
    1962        5075 :             getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
    1963             :           const SCEV *OperandExtendedAdd =
    1964        5075 :             getAddExpr(WideStart,
    1965             :                        getMulExpr(WideMaxBECount,
    1966             :                                   getSignExtendExpr(Step, WideTy, Depth + 1),
    1967             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1968        5075 :                        SCEV::FlagAnyWrap, Depth + 1);
    1969        5075 :           if (SAdd == OperandExtendedAdd) {
    1970             :             // Cache knowledge of AR NSW, which is propagated to this AddRec.
    1971             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
    1972             :             // Return the expression with the addrec on the outside.
    1973         313 :             return getAddRecExpr(
    1974             :                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
    1975             :                                                          Depth + 1),
    1976             :                 getSignExtendExpr(Step, Ty, Depth + 1), L,
    1977         313 :                 AR->getNoWrapFlags());
    1978             :           }
    1979             :           // Similar to above, only this time treat the step value as unsigned.
    1980             :           // This covers loops that count up with an unsigned step.
    1981        4762 :           OperandExtendedAdd =
    1982        4762 :             getAddExpr(WideStart,
    1983             :                        getMulExpr(WideMaxBECount,
    1984             :                                   getZeroExtendExpr(Step, WideTy, Depth + 1),
    1985             :                                   SCEV::FlagAnyWrap, Depth + 1),
    1986             :                        SCEV::FlagAnyWrap, Depth + 1);
    1987        4762 :           if (SAdd == OperandExtendedAdd) {
    1988             :             // If AR wraps around then
    1989             :             //
    1990             :             //    abs(Step) * MaxBECount > unsigned-max(AR->getType())
    1991             :             // => SAdd != OperandExtendedAdd
    1992             :             //
    1993             :             // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
    1994             :             // (SAdd == OperandExtendedAdd => AR is NW)
    1995             : 
    1996             :             const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
    1997             : 
    1998             :             // Return the expression with the addrec on the outside.
    1999           1 :             return getAddRecExpr(
    2000             :                 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
    2001             :                                                          Depth + 1),
    2002             :                 getZeroExtendExpr(Step, Ty, Depth + 1), L,
    2003           1 :                 AR->getNoWrapFlags());
    2004             :           }
    2005             :         }
    2006             :       }
    2007             : 
    2008             :       // Normally, in the cases we can prove no-overflow via a
    2009             :       // backedge guarding condition, we can also compute a backedge
    2010             :       // taken count for the loop.  The exceptions are assumptions and
    2011             :       // guards present in the loop -- SCEV is not great at exploiting
    2012             :       // these to compute max backedge taken counts, but can still use
    2013             :       // these to prove lack of overflow.  Use this fact to avoid
    2014             :       // doing extra work that may not pay off.
    2015             : 
    2016       12150 :       if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
    2017        3546 :           !AC.assumptions().empty()) {
    2018             :         // If the backedge is guarded by a comparison with the pre-inc
    2019             :         // value the addrec is safe. Also, if the entry is guarded by
    2020             :         // a comparison with the start value and the backedge is
    2021             :         // guarded by a comparison with the post-inc value, the addrec
    2022             :         // is safe.
    2023             :         ICmpInst::Predicate Pred;
    2024             :         const SCEV *OverflowLimit =
    2025        5067 :             getSignedOverflowLimitForStep(Step, &Pred, this);
    2026       10016 :         if (OverflowLimit &&
    2027        9772 :             (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
    2028        4823 :              isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
    2029             :           // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
    2030             :           const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
    2031         179 :           return getAddRecExpr(
    2032             :               getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
    2033         179 :               getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    2034             :         }
    2035             :       }
    2036             : 
    2037             :       // If Start and Step are constants, check if we can apply this
    2038             :       // transformation:
    2039             :       // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
    2040             :       auto *SC1 = dyn_cast<SCEVConstant>(Start);
    2041             :       auto *SC2 = dyn_cast<SCEVConstant>(Step);
    2042        8425 :       if (SC1 && SC2) {
    2043             :         const APInt &C1 = SC1->getAPInt();
    2044             :         const APInt &C2 = SC2->getAPInt();
    2045        5964 :         if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
    2046         826 :             C2.isPowerOf2()) {
    2047         794 :           Start = getSignExtendExpr(Start, Ty, Depth + 1);
    2048         794 :           const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
    2049         794 :                                             AR->getNoWrapFlags());
    2050         794 :           return getAddExpr(Start, getSignExtendExpr(NewAR, Ty, Depth + 1),
    2051         794 :                             SCEV::FlagAnyWrap, Depth + 1);
    2052             :         }
    2053             :       }
    2054             : 
    2055        7631 :       if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
    2056             :         const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
    2057           0 :         return getAddRecExpr(
    2058             :             getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
    2059           0 :             getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
    2060             :       }
    2061             :     }
    2062             : 
    2063             :   // If the input value is provably positive and we could not simplify
    2064             :   // away the sext build a zext instead.
    2065       27095 :   if (isKnownNonNegative(Op))
    2066        8291 :     return getZeroExtendExpr(Op, Ty, Depth + 1);
    2067             : 
    2068             :   // The cast wasn't folded; create an explicit cast node.
    2069             :   // Recompute the insert position, as it may have been invalidated.
    2070       18804 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    2071       37190 :   SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
    2072       18595 :                                                    Op, Ty);
    2073       18595 :   UniqueSCEVs.InsertNode(S, IP);
    2074       18595 :   addToLoopUseLists(S);
    2075       18595 :   return S;
    2076             : }
    2077             : 
    2078             : /// getAnyExtendExpr - Return a SCEV for the given operand extended with
    2079             : /// unspecified bits out to the given type.
    2080       10769 : const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
    2081             :                                               Type *Ty) {
    2082             :   assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
    2083             :          "This is not an extending conversion!");
    2084             :   assert(isSCEVable(Ty) &&
    2085             :          "This is not a conversion to a SCEVable type!");
    2086       10769 :   Ty = getEffectiveSCEVType(Ty);
    2087             : 
    2088             :   // Sign-extend negative constants.
    2089             :   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
    2090       15616 :     if (SC->getAPInt().isNegative())
    2091        5503 :       return getSignExtendExpr(Op, Ty);
    2092             : 
    2093             :   // Peel off a truncate cast.
    2094             :   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
    2095         112 :     const SCEV *NewOp = T->getOperand();
    2096         112 :     if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
    2097           0 :       return getAnyExtendExpr(NewOp, Ty);
    2098         112 :     return getTruncateOrNoop(NewOp, Ty);
    2099             :   }
    2100             : 
    2101             :   // Next try a zext cast. If the cast is folded, use it.
    2102        5154 :   const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
    2103        5154 :   if (!isa<SCEVZeroExtendExpr>(ZExt))
    2104             :     return ZExt;
    2105             : 
    2106             :   // Next try a sext cast. If the cast is folded, use it.
    2107        2127 :   const SCEV *SExt = getSignExtendExpr(Op, Ty);
    2108        2127 :   if (!isa<SCEVSignExtendExpr>(SExt))
    2109             :     return SExt;
    2110             : 
    2111             :   // Force the cast to be folded into the operands of an addrec.
    2112             :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
    2113             :     SmallVector<const SCEV *, 4> Ops;
    2114        3660 :     for (const SCEV *Op : AR->operands())
    2115        1464 :       Ops.push_back(getAnyExtendExpr(Op, Ty));
    2116         732 :     return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
    2117             :   }
    2118             : 
    2119             :   // If the expression is obviously signed, use the sext cast value.
    2120        1242 :   if (isa<SCEVSMaxExpr>(Op))
    2121             :     return SExt;
    2122             : 
    2123             :   // Absent any other information, use the zext cast value.
    2124        1242 :   return ZExt;
    2125             : }
    2126             : 
    2127             : /// Process the given Ops list, which is a list of operands to be added under
    2128             : /// the given scale, update the given map. This is a helper function for
    2129             : /// getAddRecExpr. As an example of what it does, given a sequence of operands
    2130             : /// that would form an add expression like this:
    2131             : ///
    2132             : ///    m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
    2133             : ///
    2134             : /// where A and B are constants, update the map with these values:
    2135             : ///
    2136             : ///    (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
    2137             : ///
    2138             : /// and add 13 + A*B*29 to AccumulatedConstant.
    2139             : /// This will allow getAddRecExpr to produce this:
    2140             : ///
    2141             : ///    13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
    2142             : ///
    2143             : /// This form often exposes folding opportunities that are hidden in
    2144             : /// the original operand list.
    2145             : ///
    2146             : /// Return true iff it appears that any interesting folding opportunities
    2147             : /// may be exposed. This helps getAddRecExpr short-circuit extra work in
    2148             : /// the common case where no interesting opportunities are present, and
    2149             : /// is also used as a check to avoid infinite recursion.
    2150             : static bool
    2151      463122 : CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
    2152             :                              SmallVectorImpl<const SCEV *> &NewOps,
    2153             :                              APInt &AccumulatedConstant,
    2154             :                              const SCEV *const *Ops, size_t NumOperands,
    2155             :                              const APInt &Scale,
    2156             :                              ScalarEvolution &SE) {
    2157             :   bool Interesting = false;
    2158             : 
    2159             :   // Iterate over the add operands. They are sorted, with constants first.
    2160             :   unsigned i = 0;
    2161      799462 :   while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
    2162      336340 :     ++i;
    2163             :     // Pull a buried constant out to the outside.
    2164     1008190 :     if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
    2165             :       Interesting = true;
    2166      672680 :     AccumulatedConstant += Scale * C->getAPInt();
    2167      336340 :   }
    2168             : 
    2169             :   // Next comes everything else. We're especially interested in multiplies
    2170             :   // here, but they're in the middle, so just visit the rest with one loop.
    2171     3338666 :   for (; i != NumOperands; ++i) {
    2172     1437772 :     const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
    2173     1561494 :     if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
    2174             :       APInt NewScale =
    2175      748979 :           Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
    2176     1475267 :       if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
    2177             :         // A multiplication of a constant with another add; recurse.
    2178             :         const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
    2179        4487 :         Interesting |=
    2180        4487 :           CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
    2181             :                                        Add->op_begin(), Add->getNumOperands(),
    2182             :                                        NewScale, SE);
    2183             :       } else {
    2184             :         // A multiplication of a constant with some other value. Update
    2185             :         // the map.
    2186     1488984 :         SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
    2187      744492 :         const SCEV *Key = SE.getMulExpr(MulOps);
    2188      744492 :         auto Pair = M.insert({Key, NewScale});
    2189      744492 :         if (Pair.second) {
    2190      741792 :           NewOps.push_back(Pair.first->first);
    2191             :         } else {
    2192        2700 :           Pair.first->second += NewScale;
    2193             :           // The map already had an entry for this value, which may indicate
    2194             :           // a folding opportunity.
    2195             :           Interesting = true;
    2196             :         }
    2197             :       }
    2198             :     } else {
    2199             :       // An ordinary operand. Update the map.
    2200             :       std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
    2201      688793 :           M.insert({Ops[i], Scale});
    2202      688793 :       if (Pair.second) {
    2203      473773 :         NewOps.push_back(Pair.first->first);
    2204             :       } else {
    2205      215020 :         Pair.first->second += Scale;
    2206             :         // The map already had an entry for this value, which may indicate
    2207             :         // a folding opportunity.
    2208             :         Interesting = true;
    2209             :       }
    2210             :     }
    2211             :   }
    2212             : 
    2213      463122 :   return Interesting;
    2214             : }
    2215             : 
    2216             : // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
    2217             : // `OldFlags' as can't-wrap behavior.  Infer a more aggressive set of
    2218             : // can't-overflow flags for the operation if possible.
    2219             : static SCEV::NoWrapFlags
    2220     4320280 : StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
    2221             :                       const SmallVectorImpl<const SCEV *> &Ops,
    2222             :                       SCEV::NoWrapFlags Flags) {
    2223             :   using namespace std::placeholders;
    2224             : 
    2225             :   using OBO = OverflowingBinaryOperator;
    2226             : 
    2227             :   bool CanAnalyze =
    2228     4320280 :       Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
    2229             :   (void)CanAnalyze;
    2230             :   assert(CanAnalyze && "don't call from other places!");
    2231             : 
    2232             :   int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
    2233             :   SCEV::NoWrapFlags SignOrUnsignWrap =
    2234             :       ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
    2235             : 
    2236             :   // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
    2237             :   auto IsKnownNonNegative = [&](const SCEV *S) {
    2238     1246207 :     return SE->isKnownNonNegative(S);
    2239     1246207 :   };
    2240             : 
    2241     5049633 :   if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
    2242             :     Flags =
    2243             :         ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
    2244             : 
    2245             :   SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
    2246             : 
    2247     6626999 :   if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
    2248     8289592 :       Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
    2249             : 
    2250             :     // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
    2251             :     // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
    2252             : 
    2253             :     const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
    2254     1610266 :     if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
    2255             :       auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    2256     3958302 :           Instruction::Add, C, OBO::NoSignedWrap);
    2257     3958302 :       if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
    2258             :         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
    2259             :     }
    2260     1610266 :     if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
    2261             :       auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    2262     4791303 :           Instruction::Add, C, OBO::NoUnsignedWrap);
    2263     4791303 :       if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
    2264             :         Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
    2265             :     }
    2266             :   }
    2267             : 
    2268     4320280 :   return Flags;
    2269             : }
    2270             : 
    2271      748053 : bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
    2272     1116054 :   return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
    2273             : }
    2274             : 
    2275             : /// Get a canonical add expression, or something simpler if possible.
    2276     2453147 : const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
    2277             :                                         SCEV::NoWrapFlags Flags,
    2278             :                                         unsigned Depth) {
    2279             :   assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
    2280             :          "only nuw or nsw allowed");
    2281             :   assert(!Ops.empty() && "Cannot get empty add!");
    2282     2453147 :   if (Ops.size() == 1) return Ops[0];
    2283             : #ifndef NDEBUG
    2284             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    2285             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    2286             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    2287             :            "SCEVAddExpr operand types don't match!");
    2288             : #endif
    2289             : 
    2290             :   // Sort by complexity, this groups all similar expression types together.
    2291     2351556 :   GroupByComplexity(Ops, &LI, DT);
    2292             : 
    2293     2351556 :   Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
    2294             : 
    2295             :   // If there are any constants, fold them together.
    2296     2351556 :   unsigned Idx = 0;
    2297     2351556 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    2298     1952100 :     ++Idx;
    2299             :     assert(Idx < Ops.size());
    2300     4065652 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    2301             :       // We found two constants, fold them together!
    2302     2719491 :       Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
    2303      906497 :       if (Ops.size() == 2) return Ops[0];
    2304       80726 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    2305       80726 :       LHSC = cast<SCEVConstant>(Ops[0]);
    2306       80726 :     }
    2307             : 
    2308             :     // If we are left with a constant zero being added, strip it off.
    2309     2252658 :     if (LHSC->getValue()->isZero()) {
    2310      250758 :       Ops.erase(Ops.begin());
    2311      250758 :       --Idx;
    2312             :     }
    2313             : 
    2314     1126329 :     if (Ops.size() == 1) return Ops[0];
    2315             :   }
    2316             : 
    2317             :   // Limit recursion calls depth.
    2318     1280737 :   if (Depth > MaxArithDepth)
    2319        3169 :     return getOrCreateAddExpr(Ops, Flags);
    2320             : 
    2321             :   // Okay, check to see if the same value occurs in the operand list more than
    2322             :   // once.  If so, merge them together into an multiply expression.  Since we
    2323             :   // sorted the list, these values are required to be adjacent.
    2324     1277568 :   Type *Ty = Ops[0]->getType();
    2325             :   bool FoundMatch = false;
    2326     3412898 :   for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
    2327     6407316 :     if (Ops[i] == Ops[i+1]) {      //  X + Y + Y  -->  X + Y*2
    2328             :       // Scan ahead to count how many equal operands there are.
    2329             :       unsigned Count = 2;
    2330        1729 :       while (i+Count != e && Ops[i+Count] == Ops[i])
    2331         126 :         ++Count;
    2332             :       // Merge the values into a multiply.
    2333         989 :       const SCEV *Scale = getConstant(Ty, Count);
    2334        1978 :       const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
    2335         989 :       if (Ops.size() == Count)
    2336             :         return Mul;
    2337         547 :       Ops[i] = Mul;
    2338         547 :       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
    2339         547 :       --i; e -= Count - 1;
    2340             :       FoundMatch = true;
    2341             :     }
    2342     1277126 :   if (FoundMatch)
    2343         513 :     return getAddExpr(Ops, Flags, Depth + 1);
    2344             : 
    2345             :   // Check for truncates. If all the operands are truncated from the same
    2346             :   // type, see if factoring out the truncate would permit the result to be
    2347             :   // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
    2348             :   // if the contents of the resulting outer trunc fold to something simple.
    2349     1276613 :   auto FindTruncSrcType = [&]() -> Type * {
    2350             :     // We're ultimately looking to fold an addrec of truncs and muls of only
    2351             :     // constants and truncs, so if we find any other types of SCEV
    2352             :     // as operands of the addrec then we bail and return nullptr here.
    2353             :     // Otherwise, we return the type of the operand of a trunc that we find.
    2354     2553226 :     if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
    2355        2333 :       return T->getOperand()->getType();
    2356             :     if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
    2357      453851 :       const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
    2358             :       if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
    2359        2631 :         return T->getOperand()->getType();
    2360             :     }
    2361             :     return nullptr;
    2362     1276613 :   };
    2363     1276613 :   if (auto *SrcType = FindTruncSrcType()) {
    2364             :     SmallVector<const SCEV *, 8> LargeOps;
    2365             :     bool Ok = true;
    2366             :     // Check all the operands to see if they can be represented in the
    2367             :     // source type of the truncate.
    2368       14871 :     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
    2369       23806 :       if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
    2370        2676 :         if (T->getOperand()->getType() != SrcType) {
    2371             :           Ok = false;
    2372             :           break;
    2373             :         }
    2374        2655 :         LargeOps.push_back(T->getOperand());
    2375             :       } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
    2376        2822 :         LargeOps.push_back(getAnyExtendExpr(C, SrcType));
    2377             :       } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
    2378             :         SmallVector<const SCEV *, 8> LargeMulOps;
    2379       11795 :         for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
    2380             :           if (const SCEVTruncateExpr *T =
    2381        8245 :                 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
    2382        3569 :             if (T->getOperand()->getType() != SrcType) {
    2383             :               Ok = false;
    2384             :               break;
    2385             :             }
    2386        3563 :             LargeMulOps.push_back(T->getOperand());
    2387             :           } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
    2388        3802 :             LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
    2389             :           } else {
    2390             :             Ok = false;
    2391             :             break;
    2392             :           }
    2393             :         }
    2394        4430 :         if (Ok)
    2395        3422 :           LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
    2396             :       } else {
    2397             :         Ok = false;
    2398             :         break;
    2399             :       }
    2400             :     }
    2401        4964 :     if (Ok) {
    2402             :       // Evaluate the expression in the larger type.
    2403        2131 :       const SCEV *Fold = getAddExpr(LargeOps, Flags, Depth + 1);
    2404             :       // If it folds to something simple, use it. Otherwise, don't.
    2405        2131 :       if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
    2406           7 :         return getTruncateExpr(Fold, Ty);
    2407             :     }
    2408             :   }
    2409             : 
    2410             :   // Skip past any other cast SCEVs.
    2411     4023515 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
    2412       60572 :     ++Idx;
    2413             : 
    2414             :   // If there are add operands they would be next.
    2415     1276606 :   if (Idx < Ops.size()) {
    2416             :     bool DeletedAdd = false;
    2417     3088806 :     while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
    2418      632777 :       if (Ops.size() > AddOpsInlineThreshold ||
    2419      316388 :           Add->getNumOperands() > AddOpsInlineThreshold)
    2420             :         break;
    2421             :       // If we have an add, expand the add operands onto the end of the operands
    2422             :       // list.
    2423      316388 :       Ops.erase(Ops.begin()+Idx);
    2424      632776 :       Ops.append(Add->op_begin(), Add->op_end());
    2425             :       DeletedAdd = true;
    2426      316388 :     }
    2427             : 
    2428             :     // If we deleted at least one add, we added operands to the end of the list,
    2429             :     // and they are not necessarily sorted.  Recurse to resort and resimplify
    2430             :     // any operands we just acquired.
    2431     1228015 :     if (DeletedAdd)
    2432      293110 :       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2433             :   }
    2434             : 
    2435             :   // Skip over the add expression until we get to a multiply.
    2436     2901901 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
    2437           1 :     ++Idx;
    2438             : 
    2439             :   // Check to see if there are any folding opportunities present with
    2440             :   // operands multiplied by constant values.
    2441     2853306 :   if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
    2442      458635 :     uint64_t BitWidth = getTypeSizeInBits(Ty);
    2443             :     DenseMap<const SCEV *, APInt> M;
    2444             :     SmallVector<const SCEV *, 8> NewOps;
    2445      458635 :     APInt AccumulatedConstant(BitWidth, 0);
    2446      917270 :     if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
    2447             :                                      Ops.data(), Ops.size(),
    2448      458635 :                                      APInt(BitWidth, 1), *this)) {
    2449             :       struct APIntCompare {
    2450             :         bool operator()(const APInt &LHS, const APInt &RHS) const {
    2451             :           return LHS.ult(RHS);
    2452             :         }
    2453             :       };
    2454             : 
    2455             :       // Some interesting folding opportunity is present, so its worthwhile to
    2456             :       // re-generate the operands list. Group the operands by constant scale,
    2457             :       // to avoid multiplying by the same constant scale multiple times.
    2458             :       std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
    2459      669448 :       for (const SCEV *NewOp : NewOps)
    2460      226495 :         MulOpLists[M.find(NewOp)->second].push_back(NewOp);
    2461             :       // Re-generate the operands list.
    2462             :       Ops.clear();
    2463      216458 :       if (AccumulatedConstant != 0)
    2464      197505 :         Ops.push_back(getConstant(AccumulatedConstant));
    2465      440870 :       for (auto &MulOp : MulOpLists)
    2466      448824 :         if (MulOp.first != 0)
    2467        9488 :           Ops.push_back(getMulExpr(
    2468             :               getConstant(MulOp.first),
    2469             :               getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
    2470             :               SCEV::FlagAnyWrap, Depth + 1));
    2471      216458 :       if (Ops.empty())
    2472       12719 :         return getZero(Ty);
    2473      203739 :       if (Ops.size() == 1)
    2474      201100 :         return Ops[0];
    2475        2639 :       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2476             :     }
    2477             :   }
    2478             : 
    2479             :   // If we are adding something to a multiply expression, make sure the
    2480             :   // something is not already an operand of the multiply.  If so, merge it into
    2481             :   // the multiply.
    2482     5430336 :   for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
    2483             :     const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
    2484     1651601 :     for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
    2485     1113377 :       const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
    2486     1113377 :       if (isa<SCEVConstant>(MulOpSCEV))
    2487             :         continue;
    2488    24815130 :       for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
    2489    48439114 :         if (MulOpSCEV == Ops[AddOp]) {
    2490             :           // Fold W + X + (X * Y * Z)  -->  W + (X * ((Y*Z)+1))
    2491         194 :           const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
    2492         194 :           if (Mul->getNumOperands() != 2) {
    2493             :             // If the multiply has more than two operands, we must get the
    2494             :             // Y*Z term.
    2495             :             SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
    2496             :                                                 Mul->op_begin()+MulOp);
    2497         200 :             MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
    2498         100 :             InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
    2499             :           }
    2500         388 :           SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
    2501         194 :           const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
    2502         194 :           const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
    2503         194 :                                             SCEV::FlagAnyWrap, Depth + 1);
    2504         194 :           if (Ops.size() == 2) return OuterMul;
    2505         112 :           if (AddOp < Idx) {
    2506           4 :             Ops.erase(Ops.begin()+AddOp);
    2507           4 :             Ops.erase(Ops.begin()+Idx-1);
    2508             :           } else {
    2509         108 :             Ops.erase(Ops.begin()+Idx);
    2510         108 :             Ops.erase(Ops.begin()+AddOp-1);
    2511             :           }
    2512         112 :           Ops.push_back(OuterMul);
    2513         112 :           return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2514             :         }
    2515             : 
    2516             :       // Check this multiply against other multiplies being added together.
    2517     6189455 :       for (unsigned OtherMulIdx = Idx+1;
    2518    18207667 :            OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
    2519             :            ++OtherMulIdx) {
    2520             :         const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
    2521             :         // If MulOp occurs in OtherMul, we can fold the two multiplies
    2522             :         // together.
    2523    16864853 :         for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
    2524    16864853 :              OMulOp != e; ++OMulOp)
    2525    22541942 :           if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
    2526             :             // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
    2527        4894 :             const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
    2528        4894 :             if (Mul->getNumOperands() != 2) {
    2529             :               SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
    2530             :                                                   Mul->op_begin()+MulOp);
    2531        5134 :               MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
    2532        2567 :               InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
    2533             :             }
    2534        4894 :             const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
    2535        4894 :             if (OtherMul->getNumOperands() != 2) {
    2536             :               SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
    2537        4343 :                                                   OtherMul->op_begin()+OMulOp);
    2538        8686 :               MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
    2539        4343 :               InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
    2540             :             }
    2541        9788 :             SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
    2542             :             const SCEV *InnerMulSum =
    2543        4894 :                 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
    2544        4894 :             const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
    2545        4894 :                                               SCEV::FlagAnyWrap, Depth + 1);
    2546        4894 :             if (Ops.size() == 2) return OuterMul;
    2547        2055 :             Ops.erase(Ops.begin()+Idx);
    2548        2055 :             Ops.erase(Ops.begin()+OtherMulIdx-1);
    2549        2055 :             Ops.push_back(OuterMul);
    2550        2055 :             return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2551             :           }
    2552             :       }
    2553             :     }
    2554             :   }
    2555             : 
    2556             :   // If there are any add recurrences in the operands list, see if any other
    2557             :   // added values are loop invariant.  If so, we can fold them into the
    2558             :   // recurrence.
    2559     1381156 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
    2560       10021 :     ++Idx;
    2561             : 
    2562             :   // Scan over all recurrences, trying to fold loop invariants into them.
    2563     2130945 :   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
    2564             :     // Scan all of the other operands to this add and add them to the vector if
    2565             :     // they are loop invariant w.r.t. the recurrence.
    2566             :     SmallVector<const SCEV *, 8> LIOps;
    2567      320885 :     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
    2568      320885 :     const Loop *AddRecLoop = AddRec->getLoop();
    2569      970900 :     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    2570     1300030 :       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
    2571      313501 :         LIOps.push_back(Ops[i]);
    2572      313501 :         Ops.erase(Ops.begin()+i);
    2573      313501 :         --i; --e;
    2574             :       }
    2575             : 
    2576             :     // If we found some loop invariants, fold them into the recurrence.
    2577      320885 :     if (!LIOps.empty()) {
    2578             :       //  NLI + LI + {Start,+,Step}  -->  NLI + {LI+Start,+,Step}
    2579      616132 :       LIOps.push_back(AddRec->getStart());
    2580             : 
    2581             :       SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
    2582      308066 :                                              AddRec->op_end());
    2583             :       // This follows from the fact that the no-wrap flags on the outer add
    2584             :       // expression are applicable on the 0th iteration, when the add recurrence
    2585             :       // will be equal to its start value.
    2586      616132 :       AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
    2587             : 
    2588             :       // Build the new addrec. Propagate the NUW and NSW flags if both the
    2589             :       // outer add and the inner addrec are guaranteed to have no overflow.
    2590             :       // Always propagate NW.
    2591      308066 :       Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
    2592      308066 :       const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
    2593             : 
    2594             :       // If all of the other operands were loop invariant, we are done.
    2595      308066 :       if (Ops.size() == 1) return NewRec;
    2596             : 
    2597             :       // Otherwise, add the folded AddRec by the non-invariant parts.
    2598         865 :       for (unsigned i = 0;; ++i)
    2599        4485 :         if (Ops[i] == AddRec) {
    2600         945 :           Ops[i] = NewRec;
    2601             :           break;
    2602             :         }
    2603         945 :       return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2604             :     }
    2605             : 
    2606             :     // Okay, if there weren't any loop invariants to be folded, check to see if
    2607             :     // there are multiple AddRec's with the same loop induction variable being
    2608             :     // added together.  If so, we can fold them.
    2609       12819 :     for (unsigned OtherIdx = Idx+1;
    2610       35991 :          OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
    2611             :          ++OtherIdx) {
    2612             :       // We expect the AddRecExpr's to be sorted in reverse dominance order,
    2613             :       // so that the 1st found AddRecExpr is dominated by all others.
    2614             :       assert(DT.dominates(
    2615             :            cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
    2616             :            AddRec->getLoop()->getHeader()) &&
    2617             :         "AddRecExprs are not sorted in reverse dominance order?");
    2618        7727 :       if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
    2619             :         // Other + {A,+,B}<L> + {C,+,D}<L>  -->  Other + {A+C,+,B+D}<L>
    2620             :         SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
    2621        7727 :                                                AddRec->op_end());
    2622       46393 :         for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
    2623             :              ++OtherIdx) {
    2624             :           const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
    2625        7732 :           if (OtherAddRec->getLoop() == AddRecLoop) {
    2626       24036 :             for (unsigned i = 0, e = OtherAddRec->getNumOperands();
    2627       24036 :                  i != e; ++i) {
    2628       33328 :               if (i >= AddRecOps.size()) {
    2629         720 :                 AddRecOps.append(OtherAddRec->op_begin()+i,
    2630             :                                  OtherAddRec->op_end());
    2631         360 :                 break;
    2632             :               }
    2633             :               SmallVector<const SCEV *, 2> TwoOps = {
    2634       48912 :                   AddRecOps[i], OtherAddRec->getOperand(i)};
    2635       32608 :               AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
    2636             :             }
    2637        7732 :             Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
    2638             :           }
    2639             :         }
    2640             :         // Step size has changed, so we cannot guarantee no self-wraparound.
    2641       15454 :         Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
    2642        7727 :         return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2643             :       }
    2644             :     }
    2645             : 
    2646             :     // Otherwise couldn't fold anything into this recurrence.  Move onto the
    2647             :     // next one.
    2648             :   }
    2649             : 
    2650             :   // Okay, it looks like we really DO need an add expr.  Check to see if we
    2651             :   // already have one, otherwise create a new one.
    2652      446157 :   return getOrCreateAddExpr(Ops, Flags);
    2653             : }
    2654             : 
    2655             : const SCEV *
    2656      449326 : ScalarEvolution::getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
    2657             :                                     SCEV::NoWrapFlags Flags) {
    2658             :   FoldingSetNodeID ID;
    2659      449326 :   ID.AddInteger(scAddExpr);
    2660     3522878 :   for (const SCEV *Op : Ops)
    2661     1536776 :     ID.AddPointer(Op);
    2662      449326 :   void *IP = nullptr;
    2663             :   SCEVAddExpr *S =
    2664             :       static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    2665      449326 :   if (!S) {
    2666      259466 :     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    2667             :     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    2668             :     S = new (SCEVAllocator)
    2669      518932 :         SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
    2670      259466 :     UniqueSCEVs.InsertNode(S, IP);
    2671      259466 :     addToLoopUseLists(S);
    2672             :   }
    2673             :   S->setNoWrapFlags(Flags);
    2674      449326 :   return S;
    2675             : }
    2676             : 
    2677             : const SCEV *
    2678      456434 : ScalarEvolution::getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
    2679             :                                     SCEV::NoWrapFlags Flags) {
    2680             :   FoldingSetNodeID ID;
    2681      456434 :   ID.AddInteger(scMulExpr);
    2682     1442162 :   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    2683     1971456 :     ID.AddPointer(Ops[i]);
    2684      456434 :   void *IP = nullptr;
    2685             :   SCEVMulExpr *S =
    2686             :     static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    2687      456434 :   if (!S) {
    2688      119181 :     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    2689             :     std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    2690      238362 :     S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
    2691             :                                         O, Ops.size());
    2692      119181 :     UniqueSCEVs.InsertNode(S, IP);
    2693      119181 :     addToLoopUseLists(S);
    2694             :   }
    2695             :   S->setNoWrapFlags(Flags);
    2696      456434 :   return S;
    2697             : }
    2698             : 
    2699             : static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
    2700        8964 :   uint64_t k = i*j;
    2701        8964 :   if (j > 1 && k / j != i) Overflow = true;
    2702             :   return k;
    2703             : }
    2704             : 
    2705             : /// Compute the result of "n choose k", the binomial coefficient.  If an
    2706             : /// intermediate computation overflows, Overflow will be set and the return will
    2707             : /// be garbage. Overflow is not cleared on absence of overflow.
    2708       13754 : static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
    2709             :   // We use the multiplicative formula:
    2710             :   //     n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
    2711             :   // At each iteration, we take the n-th term of the numeral and divide by the
    2712             :   // (k-n)th term of the denominator.  This division will always produce an
    2713             :   // integral result, and helps reduce the chance of overflow in the
    2714             :   // intermediate computations. However, we can still overflow even when the
    2715             :   // final result would fit.
    2716             : 
    2717       13754 :   if (n == 0 || n == k) return 1;
    2718        8931 :   if (k > n) return 0;
    2719             : 
    2720        8931 :   if (k > n/2)
    2721        1573 :     k = n-k;
    2722             : 
    2723             :   uint64_t r = 1;
    2724       26849 :   for (uint64_t i = 1; i <= k; ++i) {
    2725        8959 :     r = umul_ov(r, n-(i-1), Overflow);
    2726        8959 :     r /= i;
    2727             :   }
    2728             :   return r;
    2729             : }
    2730             : 
    2731             : /// Determine if any of the operands in this SCEV are a constant or if
    2732             : /// any of the add or multiply expressions in this SCEV contain a constant.
    2733       56740 : static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
    2734             :   struct FindConstantInAddMulChain {
    2735             :     bool FoundConstant = false;
    2736             : 
    2737             :     bool follow(const SCEV *S) {
    2738      195892 :       FoundConstant |= isa<SCEVConstant>(S);
    2739      195892 :       return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
    2740             :     }
    2741             : 
    2742             :     bool isDone() const {
    2743       81401 :       return FoundConstant;
    2744             :     }
    2745             :   };
    2746             : 
    2747       56740 :   FindConstantInAddMulChain F;
    2748       56740 :   SCEVTraversal<FindConstantInAddMulChain> ST(F);
    2749       56740 :   ST.visitAll(StartExpr);
    2750      113480 :   return F.FoundConstant;
    2751             : }
    2752             : 
    2753             : /// Get a canonical multiply expression, or something simpler if possible.
    2754     2040849 : const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
    2755             :                                         SCEV::NoWrapFlags Flags,
    2756             :                                         unsigned Depth) {
    2757             :   assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
    2758             :          "only nuw or nsw allowed");
    2759             :   assert(!Ops.empty() && "Cannot get empty mul!");
    2760     2040849 :   if (Ops.size() == 1) return Ops[0];
    2761             : #ifndef NDEBUG
    2762             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    2763             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    2764             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    2765             :            "SCEVMulExpr operand types don't match!");
    2766             : #endif
    2767             : 
    2768             :   // Sort by complexity, this groups all similar expression types together.
    2769     1289006 :   GroupByComplexity(Ops, &LI, DT);
    2770             : 
    2771     1289006 :   Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
    2772             : 
    2773             :   // Limit recursion calls depth.
    2774     1289006 :   if (Depth > MaxArithDepth)
    2775       17274 :     return getOrCreateMulExpr(Ops, Flags);
    2776             : 
    2777             :   // If there are any constants, fold them together.
    2778             :   unsigned Idx = 0;
    2779     1271732 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    2780             : 
    2781     1217809 :     if (Ops.size() == 2)
    2782             :       // C1*(C2+V) -> C1*C2 + C1*V
    2783     1151062 :       if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
    2784             :         // If any of Add's ops are Adds or Muls with a constant, apply this
    2785             :         // transformation as well.
    2786             :         //
    2787             :         // TODO: There are some cases where this transformation is not
    2788             :         // profitable; for example, Add = (C0 + X) * Y + Z.  Maybe the scope of
    2789             :         // this transformation should be narrowed down.
    2790       65318 :         if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
    2791      163869 :           return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
    2792             :                                        SCEV::FlagAnyWrap, Depth + 1),
    2793             :                             getMulExpr(LHSC, Add->getOperand(1),
    2794             :                                        SCEV::FlagAnyWrap, Depth + 1),
    2795       54623 :                             SCEV::FlagAnyWrap, Depth + 1);
    2796             : 
    2797             :     ++Idx;
    2798     1210089 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    2799             :       // We found two constants, fold them together!
    2800             :       ConstantInt *Fold =
    2801     1853832 :           ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
    2802      617944 :       Ops[0] = getConstant(Fold);
    2803      617944 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    2804      617944 :       if (Ops.size() == 1) return Ops[0];
    2805       46903 :       LHSC = cast<SCEVConstant>(Ops[0]);
    2806       46903 :     }
    2807             : 
    2808             :     // If we are left with a constant one being multiplied, strip it off.
    2809     1184290 :     if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
    2810       45136 :       Ops.erase(Ops.begin());
    2811             :       --Idx;
    2812      547009 :     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
    2813             :       // If we have a multiply of zero, it will always be zero.
    2814             :       return Ops[0];
    2815      540943 :     } else if (Ops[0]->isAllOnesValue()) {
    2816             :       // If we have a mul by -1 of an add, try distributing the -1 among the
    2817             :       // add operands.
    2818      419365 :       if (Ops.size() == 2) {
    2819      414773 :         if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
    2820             :           SmallVector<const SCEV *, 4> NewOps;
    2821             :           bool AnyFolded = false;
    2822       48973 :           for (const SCEV *AddOp : Add->operands()) {
    2823       41958 :             const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
    2824       20979 :                                          Depth + 1);
    2825       20979 :             if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
    2826       20979 :             NewOps.push_back(Mul);
    2827             :           }
    2828        7015 :           if (AnyFolded)
    2829        5886 :             return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
    2830             :         } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
    2831             :           // Negation preserves a recurrence's no self-wrap property.
    2832             :           SmallVector<const SCEV *, 4> Operands;
    2833      362154 :           for (const SCEV *AddRecOp : AddRec->operands())
    2834      291494 :             Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
    2835             :                                           Depth + 1));
    2836             : 
    2837      141320 :           return getAddRecExpr(Operands, AddRec->getLoop(),
    2838       70660 :                                AddRec->getNoWrapFlags(SCEV::FlagNW));
    2839             :         }
    2840             :       }
    2841             :     }
    2842             : 
    2843      509533 :     if (Ops.size() == 1)
    2844       38836 :       return Ops[0];
    2845             :   }
    2846             : 
    2847             :   // Skip over the add expression until we get to a multiply.
    2848     2115618 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
    2849      151339 :     ++Idx;
    2850             : 
    2851             :   // If there are mul operands inline them all into this expression.
    2852      524620 :   if (Idx < Ops.size()) {
    2853             :     bool DeletedMul = false;
    2854      518563 :     while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
    2855       57907 :       if (Ops.size() > MulOpsInlineThreshold)
    2856             :         break;
    2857             :       // If we have an mul, expand the mul operands onto the end of the
    2858             :       // operands list.
    2859       57541 :       Ops.erase(Ops.begin()+Idx);
    2860      115082 :       Ops.append(Mul->op_begin(), Mul->op_end());
    2861             :       DeletedMul = true;
    2862       57541 :     }
    2863             : 
    2864             :     // If we deleted at least one mul, we added operands to the end of the
    2865             :     // list, and they are not necessarily sorted.  Recurse to resort and
    2866             :     // resimplify any operands we just acquired.
    2867      461022 :     if (DeletedMul)
    2868       55950 :       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2869             :   }
    2870             : 
    2871             :   // If there are any add recurrences in the operands list, see if any other
    2872             :   // added values are loop invariant.  If so, we can fold them into the
    2873             :   // recurrence.
    2874     1472903 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
    2875       39912 :     ++Idx;
    2876             : 
    2877             :   // Scan over all recurrences, trying to fold loop invariants into them.
    2878     1323702 :   for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
    2879             :     // Scan all of the other operands to this mul and add them to the vector
    2880             :     // if they are loop invariant w.r.t. the recurrence.
    2881             :     SmallVector<const SCEV *, 8> LIOps;
    2882       32444 :     const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
    2883       32444 :     const Loop *AddRecLoop = AddRec->getLoop();
    2884      105869 :     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    2885      146850 :       if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
    2886       29199 :         LIOps.push_back(Ops[i]);
    2887       29199 :         Ops.erase(Ops.begin()+i);
    2888       29199 :         --i; --e;
    2889             :       }
    2890             : 
    2891             :     // If we found some loop invariants, fold them into the recurrence.
    2892       32444 :     if (!LIOps.empty()) {
    2893             :       //  NLI * LI * {Start,+,Step}  -->  NLI * {LI*Start,+,LI*Step}
    2894             :       SmallVector<const SCEV *, 4> NewOps;
    2895       28894 :       NewOps.reserve(AddRec->getNumOperands());
    2896       28894 :       const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
    2897       88810 :       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
    2898      119832 :         NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
    2899             :                                     SCEV::FlagAnyWrap, Depth + 1));
    2900             : 
    2901             :       // Build the new addrec. Propagate the NUW and NSW flags if both the
    2902             :       // outer mul and the inner addrec are guaranteed to have no overflow.
    2903             :       //
    2904             :       // No self-wrap cannot be guaranteed after changing the step size, but
    2905             :       // will be inferred if either NUW or NSW is true.
    2906       28894 :       Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
    2907       28894 :       const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
    2908             : 
    2909             :       // If all of the other operands were loop invariant, we are done.
    2910       28894 :       if (Ops.size() == 1) return NewRec;
    2911             : 
    2912             :       // Otherwise, multiply the folded AddRec by the non-invariant parts.
    2913          72 :       for (unsigned i = 0;; ++i)
    2914        2626 :         if (Ops[i] == AddRec) {
    2915        1205 :           Ops[i] = NewRec;
    2916             :           break;
    2917             :         }
    2918        1205 :       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2919             :     }
    2920             : 
    2921             :     // Okay, if there weren't any loop invariants to be folded, check to see
    2922             :     // if there are multiple AddRec's with the same loop induction variable
    2923             :     // being multiplied together.  If so, we can fold them.
    2924             : 
    2925             :     // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
    2926             :     // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
    2927             :     //       choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
    2928             :     //   ]]],+,...up to x=2n}.
    2929             :     // Note that the arguments to choose() are always integers with values
    2930             :     // known at compile time, never SCEV objects.
    2931             :     //
    2932             :     // The implementation avoids pointless extra computations when the two
    2933             :     // addrec's are of different length (mathematically, it's equivalent to
    2934             :     // an infinite stream of zeros on the right).
    2935             :     bool OpsModified = false;
    2936        5856 :     for (unsigned OtherIdx = Idx+1;
    2937       14759 :          OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
    2938             :          ++OtherIdx) {
    2939             :       const SCEVAddRecExpr *OtherAddRec =
    2940             :         dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
    2941        2802 :       if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
    2942        2144 :         continue;
    2943             : 
    2944             :       // Limit max number of arguments to avoid creation of unreasonably big
    2945             :       // SCEVAddRecs with very complex operands.
    2946        7748 :       if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
    2947        2802 :           MaxAddRecSize)
    2948        2144 :         continue;
    2949             : 
    2950         658 :       bool Overflow = false;
    2951             :       Type *Ty = AddRec->getType();
    2952         658 :       bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
    2953             :       SmallVector<const SCEV*, 7> AddRecOps;
    2954        3905 :       for (int x = 0, xe = AddRec->getNumOperands() +
    2955        1316 :              OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
    2956        2589 :         const SCEV *Term = getZero(Ty);
    2957       10214 :         for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
    2958        7625 :           uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
    2959       21379 :           for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
    2960       15250 :                  ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
    2961       13754 :                z < ze && !Overflow; ++z) {
    2962        6129 :             uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
    2963             :             uint64_t Coeff;
    2964        6129 :             if (LargerThan64Bits)
    2965             :               Coeff = umul_ov(Coeff1, Coeff2, Overflow);
    2966             :             else
    2967        6124 :               Coeff = Coeff1*Coeff2;
    2968        6129 :             const SCEV *CoeffTerm = getConstant(Ty, Coeff);
    2969        6129 :             const SCEV *Term1 = AddRec->getOperand(y-z);
    2970        6129 :             const SCEV *Term2 = OtherAddRec->getOperand(z);
    2971        6129 :             Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1, Term2,
    2972             :                                                SCEV::FlagAnyWrap, Depth + 1),
    2973             :                               SCEV::FlagAnyWrap, Depth + 1);
    2974             :           }
    2975             :         }
    2976        2589 :         AddRecOps.push_back(Term);
    2977             :       }
    2978         658 :       if (!Overflow) {
    2979         658 :         const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
    2980         658 :                                               SCEV::FlagAnyWrap);
    2981         658 :         if (Ops.size() == 2) return NewAddRec;
    2982         163 :         Ops[Idx] = NewAddRec;
    2983         163 :         Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
    2984             :         OpsModified = true;
    2985             :         AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
    2986             :         if (!AddRec)
    2987             :           break;
    2988             :       }
    2989             :     }
    2990        3054 :     if (OpsModified)
    2991         121 :       return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
    2992             : 
    2993             :     // Otherwise couldn't fold anything into this recurrence.  Move onto the
    2994             :     // next one.
    2995             :   }
    2996             : 
    2997             :   // Okay, it looks like we really DO need an mul expr.  Check to see if we
    2998             :   // already have one, otherwise create a new one.
    2999      439160 :   return getOrCreateMulExpr(Ops, Flags);
    3000             : }
    3001             : 
    3002             : /// Represents an unsigned remainder expression based on unsigned division.
    3003        4415 : const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
    3004             :                                          const SCEV *RHS) {
    3005             :   assert(getEffectiveSCEVType(LHS->getType()) ==
    3006             :          getEffectiveSCEVType(RHS->getType()) &&
    3007             :          "SCEVURemExpr operand types don't match!");
    3008             : 
    3009             :   // Short-circuit easy cases
    3010             :   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
    3011             :     // If constant is one, the result is trivial
    3012        4336 :     if (RHSC->getValue()->isOne())
    3013        1552 :       return getZero(LHS->getType()); // X urem 1 --> 0
    3014             : 
    3015             :     // If constant is a power of two, fold into a zext(trunc(LHS)).
    3016        1392 :     if (RHSC->getAPInt().isPowerOf2()) {
    3017         203 :       Type *FullTy = LHS->getType();
    3018             :       Type *TruncTy =
    3019         406 :           IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
    3020         203 :       return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
    3021             :     }
    3022             :   }
    3023             : 
    3024             :   // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
    3025        3436 :   const SCEV *UDiv = getUDivExpr(LHS, RHS);
    3026        3436 :   const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
    3027        3436 :   return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
    3028             : }
    3029             : 
    3030             : /// Get a canonical unsigned division expression, or something simpler if
    3031             : /// possible.
    3032       36491 : const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
    3033             :                                          const SCEV *RHS) {
    3034             :   assert(getEffectiveSCEVType(LHS->getType()) ==
    3035             :          getEffectiveSCEVType(RHS->getType()) &&
    3036             :          "SCEVUDivExpr operand types don't match!");
    3037             : 
    3038             :   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
    3039       67546 :     if (RHSC->getValue()->isOne())
    3040             :       return LHS;                               // X udiv 1 --> x
    3041             :     // If the denominator is zero, the result of the udiv is undefined. Don't
    3042             :     // try to analyze it, because the resolution chosen here may differ from
    3043             :     // the resolution chosen in other parts of the compiler.
    3044       23531 :     if (!RHSC->getValue()->isZero()) {
    3045             :       // Determine if the division can be folded into the operands of
    3046             :       // its operands.
    3047             :       // TODO: Generalize this to non-constants by using known-bits information.
    3048       23530 :       Type *Ty = LHS->getType();
    3049       23530 :       unsigned LZ = RHSC->getAPInt().countLeadingZeros();
    3050       23530 :       unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
    3051             :       // For non-power-of-two values, effectively round the value up to the
    3052             :       // nearest power of two.
    3053       23530 :       if (!RHSC->getAPInt().isPowerOf2())
    3054             :         ++MaxShiftAmt;
    3055             :       IntegerType *ExtTy =
    3056       47060 :         IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
    3057             :       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
    3058             :         if (const SCEVConstant *Step =
    3059         592 :             dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
    3060             :           // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
    3061             :           const APInt &StepInt = Step->getAPInt();
    3062             :           const APInt &DivInt = RHSC->getAPInt();
    3063        1700 :           if (!StepInt.urem(DivInt) &&
    3064          26 :               getZeroExtendExpr(AR, ExtTy) ==
    3065          52 :               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
    3066             :                             getZeroExtendExpr(Step, ExtTy),
    3067             :                             AR->getLoop(), SCEV::FlagAnyWrap)) {
    3068             :             SmallVector<const SCEV *, 4> Operands;
    3069          75 :             for (const SCEV *Op : AR->operands())
    3070          30 :               Operands.push_back(getUDivExpr(Op, RHS));
    3071          15 :             return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
    3072             :           }
    3073             :           /// Get a canonical UDivExpr for a recurrence.
    3074             :           /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
    3075             :           // We can currently only fold X%N if X is constant.
    3076         543 :           const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
    3077        1963 :           if (StartC && !DivInt.urem(StepInt) &&
    3078         416 :               getZeroExtendExpr(AR, ExtTy) ==
    3079         832 :               getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
    3080             :                             getZeroExtendExpr(Step, ExtTy),
    3081             :                             AR->getLoop(), SCEV::FlagAnyWrap)) {
    3082             :             const APInt &StartInt = StartC->getAPInt();
    3083         296 :             const APInt &StartRem = StartInt.urem(StepInt);
    3084         296 :             if (StartRem != 0)
    3085          48 :               LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
    3086             :                                   AR->getLoop(), SCEV::FlagNW);
    3087             :           }
    3088             :         }
    3089             :       // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
    3090             :       if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
    3091             :         SmallVector<const SCEV *, 4> Operands;
    3092       17648 :         for (const SCEV *Op : M->operands())
    3093        7134 :           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
    3094        3380 :         if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
    3095             :           // Find an operand that's safely divisible.
    3096           0 :           for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
    3097           0 :             const SCEV *Op = M->getOperand(i);
    3098           0 :             const SCEV *Div = getUDivExpr(Op, RHSC);
    3099           0 :             if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
    3100           0 :               Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
    3101             :                                                       M->op_end());
    3102           0 :               Operands[i] = Div;
    3103           0 :               return getMulExpr(Operands);
    3104             :             }
    3105             :           }
    3106             :       }
    3107             : 
    3108             :       // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
    3109             :       if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
    3110             :         if (auto *DivisorConstant =
    3111          22 :                 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
    3112          22 :           bool Overflow = false;
    3113             :           APInt NewRHS =
    3114          22 :               DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
    3115          22 :           if (Overflow) {
    3116           6 :             return getConstant(RHSC->getType(), 0, false);
    3117             :           }
    3118          19 :           return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
    3119             :         }
    3120             :       }
    3121             : 
    3122             :       // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
    3123             :       if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
    3124             :         SmallVector<const SCEV *, 4> Operands;
    3125       12172 :         for (const SCEV *Op : A->operands())
    3126        4982 :           Operands.push_back(getZeroExtendExpr(Op, ExtTy));
    3127        2208 :         if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
    3128             :           Operands.clear();
    3129          55 :           for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
    3130         110 :             const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
    3131         110 :             if (isa<SCEVUDivExpr>(Op) ||
    3132          55 :                 getMulExpr(Op, RHS) != A->getOperand(i))
    3133             :               break;
    3134           0 :             Operands.push_back(Op);
    3135             :           }
    3136          55 :           if (Operands.size() == A->getNumOperands())
    3137           0 :             return getAddExpr(Operands);
    3138             :         }
    3139             :       }
    3140             : 
    3141             :       // Fold if both operands are constant.
    3142             :       if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
    3143        9791 :         Constant *LHSCV = LHSC->getValue();
    3144        9791 :         Constant *RHSCV = RHSC->getValue();
    3145        9791 :         return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
    3146        9791 :                                                                    RHSCV)));
    3147             :       }
    3148             :     }
    3149             :   }
    3150             : 
    3151             :   FoldingSetNodeID ID;
    3152       16421 :   ID.AddInteger(scUDivExpr);
    3153       16421 :   ID.AddPointer(LHS);
    3154       16421 :   ID.AddPointer(RHS);
    3155       16421 :   void *IP = nullptr;
    3156       16421 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    3157       16762 :   SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
    3158             :                                              LHS, RHS);
    3159        8381 :   UniqueSCEVs.InsertNode(S, IP);
    3160        8381 :   addToLoopUseLists(S);
    3161        8381 :   return S;
    3162             : }
    3163             : 
    3164           0 : static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
    3165           0 :   APInt A = C1->getAPInt().abs();
    3166           0 :   APInt B = C2->getAPInt().abs();
    3167           0 :   uint32_t ABW = A.getBitWidth();
    3168           0 :   uint32_t BBW = B.getBitWidth();
    3169             : 
    3170           0 :   if (ABW > BBW)
    3171           0 :     B = B.zext(ABW);
    3172           0 :   else if (ABW < BBW)
    3173           0 :     A = A.zext(BBW);
    3174             : 
    3175           0 :   return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
    3176             : }
    3177             : 
    3178             : /// Get a canonical unsigned division expression, or something simpler if
    3179             : /// possible. There is no representation for an exact udiv in SCEV IR, but we
    3180             : /// can attempt to remove factors from the LHS and RHS.  We can't do this when
    3181             : /// it's not exact because the udiv may be clearing bits.
    3182         173 : const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
    3183             :                                               const SCEV *RHS) {
    3184             :   // TODO: we could try to find factors in all sorts of things, but for now we
    3185             :   // just deal with u/exact (multiply, constant). See SCEVDivision towards the
    3186             :   // end of this file for inspiration.
    3187             : 
    3188             :   const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
    3189           1 :   if (!Mul || !Mul->hasNoUnsignedWrap())
    3190         173 :     return getUDivExpr(LHS, RHS);
    3191             : 
    3192             :   if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
    3193             :     // If the mulexpr multiplies by a constant, then that constant must be the
    3194             :     // first element of the mulexpr.
    3195           0 :     if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
    3196           0 :       if (LHSCst == RHSCst) {
    3197             :         SmallVector<const SCEV *, 2> Operands;
    3198           0 :         Operands.append(Mul->op_begin() + 1, Mul->op_end());
    3199           0 :         return getMulExpr(Operands);
    3200             :       }
    3201             : 
    3202             :       // We can't just assume that LHSCst divides RHSCst cleanly, it could be
    3203             :       // that there's a factor provided by one of the other terms. We need to
    3204             :       // check.
    3205           0 :       APInt Factor = gcd(LHSCst, RHSCst);
    3206           0 :       if (!Factor.isIntN(1)) {
    3207             :         LHSCst =
    3208           0 :             cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
    3209             :         RHSCst =
    3210           0 :             cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
    3211             :         SmallVector<const SCEV *, 2> Operands;
    3212           0 :         Operands.push_back(LHSCst);
    3213           0 :         Operands.append(Mul->op_begin() + 1, Mul->op_end());
    3214           0 :         LHS = getMulExpr(Operands);
    3215             :         RHS = RHSCst;
    3216             :         Mul = dyn_cast<SCEVMulExpr>(LHS);
    3217             :         if (!Mul)
    3218           0 :           return getUDivExactExpr(LHS, RHS);
    3219             :       }
    3220             :     }
    3221             :   }
    3222             : 
    3223           0 :   for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
    3224           0 :     if (Mul->getOperand(i) == RHS) {
    3225             :       SmallVector<const SCEV *, 2> Operands;
    3226           0 :       Operands.append(Mul->op_begin(), Mul->op_begin() + i);
    3227           0 :       Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
    3228           0 :       return getMulExpr(Operands);
    3229             :     }
    3230             :   }
    3231             : 
    3232           0 :   return getUDivExpr(LHS, RHS);
    3233             : }
    3234             : 
    3235             : /// Get an add recurrence expression for the specified loop.  Simplify the
    3236             : /// expression as much as possible.
    3237      156848 : const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
    3238             :                                            const Loop *L,
    3239             :                                            SCEV::NoWrapFlags Flags) {
    3240             :   SmallVector<const SCEV *, 4> Operands;
    3241      156848 :   Operands.push_back(Start);
    3242      156848 :   if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
    3243         209 :     if (StepChrec->getLoop() == L) {
    3244         136 :       Operands.append(StepChrec->op_begin(), StepChrec->op_end());
    3245          68 :       return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
    3246             :     }
    3247             : 
    3248      156780 :   Operands.push_back(Step);
    3249      156780 :   return getAddRecExpr(Operands, L, Flags);
    3250             : }
    3251             : 
    3252             : /// Get an add recurrence expression for the specified loop.  Simplify the
    3253             : /// expression as much as possible.
    3254             : const SCEV *
    3255      716309 : ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
    3256             :                                const Loop *L, SCEV::NoWrapFlags Flags) {
    3257      716309 :   if (Operands.size() == 1) return Operands[0];
    3258             : #ifndef NDEBUG
    3259             :   Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
    3260             :   for (unsigned i = 1, e = Operands.size(); i != e; ++i)
    3261             :     assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
    3262             :            "SCEVAddRecExpr operand types don't match!");
    3263             :   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
    3264             :     assert(isLoopInvariant(Operands[i], L) &&
    3265             :            "SCEVAddRecExpr operand is not loop-invariant!");
    3266             : #endif
    3267             : 
    3268      699038 :   if (Operands.back()->isZero()) {
    3269             :     Operands.pop_back();
    3270       19320 :     return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0}  -->  X
    3271             :   }
    3272             : 
    3273             :   // It's tempting to want to call getMaxBackedgeTakenCount count here and
    3274             :   // use that information to infer NUW and NSW flags. However, computing a
    3275             :   // BE count requires calling getAddRecExpr, so we may not yet have a
    3276             :   // meaningful BE count at this point (and if we don't, we'd be stuck
    3277             :   // with a SCEVCouldNotCompute as the cached BE count).
    3278             : 
    3279      679718 :   Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
    3280             : 
    3281             :   // Canonicalize nested AddRecs in by nesting them in order of loop depth.
    3282      679718 :   if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
    3283      136977 :     const Loop *NestedLoop = NestedAR->getLoop();
    3284      136977 :     if (L->contains(NestedLoop)
    3285      136977 :             ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
    3286      392261 :             : (!NestedLoop->contains(L) &&
    3287      236614 :                DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
    3288             :       SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
    3289           0 :                                                   NestedAR->op_end());
    3290           0 :       Operands[0] = NestedAR->getStart();
    3291             :       // AddRecs require their operands be loop-invariant with respect to their
    3292             :       // loops. Don't perform this transformation if it would break this
    3293             :       // requirement.
    3294             :       bool AllInvariant = all_of(
    3295           0 :           Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
    3296             : 
    3297           0 :       if (AllInvariant) {
    3298             :         // Create a recurrence for the outer loop with the same step size.
    3299             :         //
    3300             :         // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
    3301             :         // inner recurrence has the same property.
    3302             :         SCEV::NoWrapFlags OuterFlags =
    3303           0 :           maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
    3304             : 
    3305           0 :         NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
    3306             :         AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
    3307           0 :           return isLoopInvariant(Op, NestedLoop);
    3308           0 :         });
    3309             : 
    3310           0 :         if (AllInvariant) {
    3311             :           // Ok, both add recurrences are valid after the transformation.
    3312             :           //
    3313             :           // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
    3314             :           // the outer recurrence has the same property.
    3315             :           SCEV::NoWrapFlags InnerFlags =
    3316           0 :             maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
    3317           0 :           return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
    3318             :         }
    3319             :       }
    3320             :       // Reset Operands to its original state.
    3321           0 :       Operands[0] = NestedAR;
    3322             :     }
    3323             :   }
    3324             : 
    3325             :   // Okay, it looks like we really DO need an addrec expr.  Check to see if we
    3326             :   // already have one, otherwise create a new one.
    3327             :   FoldingSetNodeID ID;
    3328      679718 :   ID.AddInteger(scAddRecExpr);
    3329     2053013 :   for (unsigned i = 0, e = Operands.size(); i != e; ++i)
    3330     2746590 :     ID.AddPointer(Operands[i]);
    3331      679718 :   ID.AddPointer(L);
    3332      679718 :   void *IP = nullptr;
    3333             :   SCEVAddRecExpr *S =
    3334             :     static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
    3335      679718 :   if (!S) {
    3336      163353 :     const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
    3337             :     std::uninitialized_copy(Operands.begin(), Operands.end(), O);
    3338      326706 :     S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
    3339      163353 :                                            O, Operands.size(), L);
    3340      163353 :     UniqueSCEVs.InsertNode(S, IP);
    3341      163353 :     addToLoopUseLists(S);
    3342             :   }
    3343             :   S->setNoWrapFlags(Flags);
    3344             :   return S;
    3345             : }
    3346             : 
    3347             : const SCEV *
    3348      187484 : ScalarEvolution::getGEPExpr(GEPOperator *GEP,
    3349             :                             const SmallVectorImpl<const SCEV *> &IndexExprs) {
    3350      187484 :   const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
    3351             :   // getSCEV(Base)->getType() has the same address space as Base->getType()
    3352             :   // because SCEV::getType() preserves the address space.
    3353      187484 :   Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
    3354             :   // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
    3355             :   // instruction to its SCEV, because the Instruction may be guarded by control
    3356             :   // flow and the no-overflow bits may not be valid for the expression in any
    3357             :   // context. This can be fixed similarly to how these flags are handled for
    3358             :   // adds.
    3359      187484 :   SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
    3360             :                                              : SCEV::FlagAnyWrap;
    3361             : 
    3362             :   const SCEV *TotalOffset = getZero(IntPtrTy);
    3363             :   // The array size is unimportant. The first thing we do on CurTy is getting
    3364             :   // its element type.
    3365      187484 :   Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
    3366      857206 :   for (const SCEV *IndexExpr : IndexExprs) {
    3367             :     // Compute the (potentially symbolic) offset in bytes for this index.
    3368             :     if (StructType *STy = dyn_cast<StructType>(CurTy)) {
    3369             :       // For a struct, add the member offset.
    3370       30590 :       ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
    3371       30590 :       unsigned FieldNo = Index->getZExtValue();
    3372       30590 :       const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
    3373             : 
    3374             :       // Add the field offset to the running total offset.
    3375       30590 :       TotalOffset = getAddExpr(TotalOffset, FieldOffset);
    3376             : 
    3377             :       // Update CurTy to the type of the field at Index.
    3378       30590 :       CurTy = STy->getTypeAtIndex(Index);
    3379             :     } else {
    3380             :       // Update CurTy to its element type.
    3381      304271 :       CurTy = cast<SequentialType>(CurTy)->getElementType();
    3382             :       // For an array, add the element offset, explicitly scaled.
    3383      304271 :       const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
    3384             :       // Getelementptr indices are signed.
    3385      304271 :       IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
    3386             : 
    3387             :       // Multiply the index by the element size to compute the element offset.
    3388      304271 :       const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
    3389             : 
    3390             :       // Add the element offset to the running total offset.
    3391      304271 :       TotalOffset = getAddExpr(TotalOffset, LocalOffset);
    3392             :     }
    3393             :   }
    3394             : 
    3395             :   // Add the total offset from all the GEP indices to the base.
    3396      187484 :   return getAddExpr(BaseExpr, TotalOffset, Wrap);
    3397             : }
    3398             : 
    3399        4662 : const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
    3400             :                                          const SCEV *RHS) {
    3401        9324 :   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
    3402        9324 :   return getSMaxExpr(Ops);
    3403             : }
    3404             : 
    3405             : const SCEV *
    3406       22065 : ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3407             :   assert(!Ops.empty() && "Cannot get empty smax!");
    3408       22065 :   if (Ops.size() == 1) return Ops[0];
    3409             : #ifndef NDEBUG
    3410             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    3411             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    3412             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    3413             :            "SCEVSMaxExpr operand types don't match!");
    3414             : #endif
    3415             : 
    3416             :   // Sort by complexity, this groups all similar expression types together.
    3417       22065 :   GroupByComplexity(Ops, &LI, DT);
    3418             : 
    3419             :   // If there are any constants, fold them together.
    3420             :   unsigned Idx = 0;
    3421       22065 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    3422             :     ++Idx;
    3423             :     assert(Idx < Ops.size());
    3424       21515 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    3425             :       // We found two constants, fold them together!
    3426       19206 :       ConstantInt *Fold = ConstantInt::get(
    3427       19206 :           getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
    3428       19206 :       Ops[0] = getConstant(Fold);
    3429       19206 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    3430       19206 :       if (Ops.size() == 1) return Ops[0];
    3431           2 :       LHSC = cast<SCEVConstant>(Ops[0]);
    3432           2 :     }
    3433             : 
    3434             :     // If we are left with a constant minimum-int, strip it off.
    3435        2309 :     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
    3436          11 :       Ops.erase(Ops.begin());
    3437             :       --Idx;
    3438        2298 :     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
    3439             :       // If we have an smax with a constant maximum-int, it will always be
    3440             :       // maximum-int.
    3441             :       return Ops[0];
    3442             :     }
    3443             : 
    3444        2305 :     if (Ops.size() == 1) return Ops[0];
    3445             :   }
    3446             : 
    3447             :   // Find the first SMax
    3448       15436 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
    3449        2140 :     ++Idx;
    3450             : 
    3451             :   // Check to see if one of the operands is an SMax. If so, expand its operands
    3452             :   // onto our operand list, and recurse to simplify.
    3453        2846 :   if (Idx < Ops.size()) {
    3454             :     bool DeletedSMax = false;
    3455        1262 :     while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
    3456          78 :       Ops.erase(Ops.begin()+Idx);
    3457         156 :       Ops.append(SMax->op_begin(), SMax->op_end());
    3458             :       DeletedSMax = true;
    3459          78 :     }
    3460             : 
    3461        1184 :     if (DeletedSMax)
    3462          78 :       return getSMaxExpr(Ops);
    3463             :   }
    3464             : 
    3465             :   // Okay, check to see if the same value occurs in the operand list twice.  If
    3466             :   // so, delete one.  Since we sorted the list, these values are required to
    3467             :   // be adjacent.
    3468        5954 :   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
    3469             :     //  X smax Y smax Y  -->  X smax Y
    3470             :     //  X smax Y         -->  X, if X is always greater than Y
    3471       12739 :     if (Ops[i] == Ops[i+1] ||
    3472        3181 :         isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
    3473         134 :       Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
    3474         134 :       --i; --e;
    3475        6104 :     } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
    3476          48 :       Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
    3477          48 :       --i; --e;
    3478             :     }
    3479             : 
    3480        2768 :   if (Ops.size() == 1) return Ops[0];
    3481             : 
    3482             :   assert(!Ops.empty() && "Reduced smax down to nothing!");
    3483             : 
    3484             :   // Okay, it looks like we really DO need an smax expr.  Check to see if we
    3485             :   // already have one, otherwise create a new one.
    3486             :   FoldingSetNodeID ID;
    3487        2586 :   ID.AddInteger(scSMaxExpr);
    3488        8176 :   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    3489       11180 :     ID.AddPointer(Ops[i]);
    3490        2586 :   void *IP = nullptr;
    3491        2586 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    3492        2233 :   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    3493             :   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    3494        4466 :   SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
    3495             :                                              O, Ops.size());
    3496        2233 :   UniqueSCEVs.InsertNode(S, IP);
    3497        2233 :   addToLoopUseLists(S);
    3498        2233 :   return S;
    3499             : }
    3500             : 
    3501         762 : const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
    3502             :                                          const SCEV *RHS) {
    3503        1524 :   SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
    3504        1524 :   return getUMaxExpr(Ops);
    3505             : }
    3506             : 
    3507             : const SCEV *
    3508        1804 : ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3509             :   assert(!Ops.empty() && "Cannot get empty umax!");
    3510        1804 :   if (Ops.size() == 1) return Ops[0];
    3511             : #ifndef NDEBUG
    3512             :   Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
    3513             :   for (unsigned i = 1, e = Ops.size(); i != e; ++i)
    3514             :     assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
    3515             :            "SCEVUMaxExpr operand types don't match!");
    3516             : #endif
    3517             : 
    3518             :   // Sort by complexity, this groups all similar expression types together.
    3519        1804 :   GroupByComplexity(Ops, &LI, DT);
    3520             : 
    3521             :   // If there are any constants, fold them together.
    3522             :   unsigned Idx = 0;
    3523        1804 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
    3524             :     ++Idx;
    3525             :     assert(Idx < Ops.size());
    3526        1237 :     while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
    3527             :       // We found two constants, fold them together!
    3528         534 :       ConstantInt *Fold = ConstantInt::get(
    3529         534 :           getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
    3530         534 :       Ops[0] = getConstant(Fold);
    3531         534 :       Ops.erase(Ops.begin()+1);  // Erase the folded element
    3532         534 :       if (Ops.size() == 1) return Ops[0];
    3533          25 :       LHSC = cast<SCEVConstant>(Ops[0]);
    3534          25 :     }
    3535             : 
    3536             :     // If we are left with a constant minimum-int, strip it off.
    3537         703 :     if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
    3538         176 :       Ops.erase(Ops.begin());
    3539             :       --Idx;
    3540         527 :     } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
    3541             :       // If we have an umax with a constant maximum-int, it will always be
    3542             :       // maximum-int.
    3543             :       return Ops[0];
    3544             :     }
    3545             : 
    3546         678 :     if (Ops.size() == 1) return Ops[0];
    3547             :   }
    3548             : 
    3549             :   // Find the first UMax
    3550        7625 :   while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
    3551        1263 :     ++Idx;
    3552             : 
    3553             :   // Check to see if one of the operands is a UMax. If so, expand its operands
    3554             :   // onto our operand list, and recurse to simplify.
    3555        1094 :   if (Idx < Ops.size()) {
    3556             :     bool DeletedUMax = false;
    3557         415 :     while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
    3558          30 :       Ops.erase(Ops.begin()+Idx);
    3559          60 :       Ops.append(UMax->op_begin(), UMax->op_end());
    3560             :       DeletedUMax = true;
    3561          30 :     }
    3562             : 
    3563         385 :     if (DeletedUMax)
    3564          30 :       return getUMaxExpr(Ops);
    3565             :   }
    3566             : 
    3567             :   // Okay, check to see if the same value occurs in the operand list twice.  If
    3568             :   // so, delete one.  Since we sorted the list, these values are required to
    3569             :   // be adjacent.
    3570        2182 :   for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
    3571             :     //  X umax Y umax Y  -->  X umax Y
    3572             :     //  X umax Y         -->  X, if X is always greater than Y
    3573        3354 :     if (Ops[i] == Ops[i + 1] || isKnownViaNonRecursiveReasoning(
    3574             :                                     ICmpInst::ICMP_UGE, Ops[i], Ops[i + 1])) {
    3575          24 :       Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
    3576          24 :       --i; --e;
    3577        2188 :     } else if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, Ops[i],
    3578             :                                                Ops[i + 1])) {
    3579          41 :       Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
    3580          41 :       --i; --e;
    3581             :     }
    3582             : 
    3583        1064 :   if (Ops.size() == 1) return Ops[0];
    3584             : 
    3585             :   assert(!Ops.empty() && "Reduced umax down to nothing!");
    3586             : 
    3587             :   // Okay, it looks like we really DO need a umax expr.  Check to see if we
    3588             :   // already have one, otherwise create a new one.
    3589             :   FoldingSetNodeID ID;
    3590        1001 :   ID.AddInteger(scUMaxExpr);
    3591        3055 :   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
    3592        4108 :     ID.AddPointer(Ops[i]);
    3593        1001 :   void *IP = nullptr;
    3594        1001 :   if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
    3595         702 :   const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
    3596             :   std::uninitialized_copy(Ops.begin(), Ops.end(), O);
    3597        1404 :   SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
    3598             :                                              O, Ops.size());
    3599         702 :   UniqueSCEVs.InsertNode(S, IP);
    3600         702 :   addToLoopUseLists(S);
    3601         702 :   return S;
    3602             : }
    3603             : 
    3604       17266 : const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
    3605             :                                          const SCEV *RHS) {
    3606       34532 :   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
    3607       34532 :   return getSMinExpr(Ops);
    3608             : }
    3609             : 
    3610       17266 : const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3611             :   // ~smax(~x, ~y, ~z) == smin(x, y, z).
    3612             :   SmallVector<const SCEV *, 2> NotOps;
    3613       86330 :   for (auto *S : Ops)
    3614       34532 :     NotOps.push_back(getNotSCEV(S));
    3615       34532 :   return getNotSCEV(getSMaxExpr(NotOps));
    3616             : }
    3617             : 
    3618         307 : const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
    3619             :                                          const SCEV *RHS) {
    3620         614 :   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
    3621         614 :   return getUMinExpr(Ops);
    3622             : }
    3623             : 
    3624        1003 : const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
    3625             :   assert(!Ops.empty() && "At least one operand must be!");
    3626             :   // Trivial case.
    3627        1003 :   if (Ops.size() == 1)
    3628           0 :     return Ops[0];
    3629             : 
    3630             :   // ~umax(~x, ~y, ~z) == umin(x, y, z).
    3631             :   SmallVector<const SCEV *, 2> NotOps;
    3632        5065 :   for (auto *S : Ops)
    3633        2031 :     NotOps.push_back(getNotSCEV(S));
    3634        1003 :   return getNotSCEV(getUMaxExpr(NotOps));
    3635             : }
    3636             : 
    3637      343786 : const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
    3638             :   // We can bypass creating a target-independent
    3639             :   // constant expression and then folding it back into a ConstantInt.
    3640             :   // This is just a compile-time optimization.
    3641      687572 :   return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
    3642             : }
    3643             : 
    3644       30590 : const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
    3645             :                                              StructType *STy,
    3646             :                                              unsigned FieldNo) {
    3647             :   // We can bypass creating a target-independent
    3648             :   // constant expression and then folding it back into a ConstantInt.
    3649             :   // This is just a compile-time optimization.
    3650       30590 :   return getConstant(
    3651       61180 :       IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
    3652             : }
    3653             : 
    3654      240412 : const SCEV *ScalarEvolution::getUnknown(Value *V) {
    3655             :   // Don't attempt to do anything other than create a SCEVUnknown object
    3656             :   // here.  createSCEV only calls getUnknown after checking for all other
    3657             :   // interesting possibilities, and any other code that calls getUnknown
    3658             :   // is doing so in order to hide a value from SCEV canonicalization.
    3659             : 
    3660             :   FoldingSetNodeID ID;
    3661      240412 :   ID.AddInteger(scUnknown);
    3662      240412 :   ID.AddPointer(V);
    3663      240412 :   void *IP = nullptr;
    3664      240412 :   if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
    3665             :     assert(cast<SCEVUnknown>(S)->getValue() == V &&
    3666             :            "Stale SCEVUnknown in uniquing map!");
    3667             :     return S;
    3668             :   }
    3669      401880 :   SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
    3670      200940 :                                             FirstUnknown);
    3671      200940 :   FirstUnknown = cast<SCEVUnknown>(S);
    3672      200940 :   UniqueSCEVs.InsertNode(S, IP);
    3673      200940 :   return S;
    3674             : }
    3675             : 
    3676             : //===----------------------------------------------------------------------===//
    3677             : //            Basic SCEV Analysis and PHI Idiom Recognition Code
    3678             : //
    3679             : 
    3680             : /// Test if values of the given type are analyzable within the SCEV
    3681             : /// framework. This primarily includes integer types, and it can optionally
    3682             : /// include pointer types if the ScalarEvolution class has access to
    3683             : /// target-specific information.
    3684     1388741 : bool ScalarEvolution::isSCEVable(Type *Ty) const {
    3685             :   // Integers and pointers are always SCEVable.
    3686     1388741 :   return Ty->isIntOrPtrTy();
    3687             : }
    3688             : 
    3689             : /// Return the size in bits of the specified type, for which isSCEVable must
    3690             : /// return true.
    3691     3221765 : uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
    3692             :   assert(isSCEVable(Ty) && "Type is not SCEVable!");
    3693     3221765 :   if (Ty->isPointerTy())
    3694      641622 :     return getDataLayout().getIndexTypeSizeInBits(Ty);
    3695     5801908 :   return getDataLayout().getTypeSizeInBits(Ty);
    3696             : }
    3697             : 
    3698             : /// Return a type with the same bitwidth as the given type and which represents
    3699             : /// how SCEV will treat the given type, for which isSCEVable must return
    3700             : /// true. For pointer types, this is the pointer-sized integer type.
    3701     2433395 : Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
    3702             :   assert(isSCEVable(Ty) && "Type is not SCEVable!");
    3703             : 
    3704     2433395 :   if (Ty->isIntegerTy())
    3705             :     return Ty;
    3706             : 
    3707             :   // The only other support type is pointer.
    3708             :   assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
    3709     1286406 :   return getDataLayout().getIntPtrType(Ty);
    3710             : }
    3711             : 
    3712         807 : Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
    3713         807 :   return  getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
    3714             : }
    3715             : 
    3716      491894 : const SCEV *ScalarEvolution::getCouldNotCompute() {
    3717      491894 :   return CouldNotCompute.get();
    3718             : }
    3719             : 
    3720     1674495 : bool ScalarEvolution::checkValidity(const SCEV *S) const {
    3721             :   bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
    3722             :     auto *SU = dyn_cast<SCEVUnknown>(S);
    3723     2197832 :     return SU && SU->getValue() == nullptr;
    3724             :   });
    3725             : 
    3726     1674495 :   return !ContainsNulls;
    3727             : }
    3728             : 
    3729       60882 : bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
    3730       60882 :   HasRecMapType::iterator I = HasRecMap.find(S);
    3731       60882 :   if (I != HasRecMap.end())
    3732       12992 :     return I->second;
    3733             : 
    3734             :   bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
    3735       47890 :   HasRecMap.insert({S, FoundAddRec});
    3736       47890 :   return FoundAddRec;
    3737             : }
    3738             : 
    3739             : /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
    3740             : /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
    3741             : /// offset I, then return {S', I}, else return {\p S, nullptr}.
    3742      641431 : static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
    3743             :   const auto *Add = dyn_cast<SCEVAddExpr>(S);
    3744             :   if (!Add)
    3745      507845 :     return {S, nullptr};
    3746             : 
    3747      133586 :   if (Add->getNumOperands() != 2)
    3748        6325 :     return {S, nullptr};
    3749             : 
    3750      127261 :   auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
    3751             :   if (!ConstOp)
    3752       33149 :     return {S, nullptr};
    3753             : 
    3754       94112 :   return {Add->getOperand(1), ConstOp->getValue()};
    3755             : }
    3756             : 
    3757             : /// Return the ValueOffsetPair set for \p S. \p S can be represented
    3758             : /// by the value and offset from any ValueOffsetPair in the set.
    3759             : SetVector<ScalarEvolution::ValueOffsetPair> *
    3760      186713 : ScalarEvolution::getSCEVValues(const SCEV *S) {
    3761      186713 :   ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
    3762      186713 :   if (SI == ExprValueMap.end())
    3763             :     return nullptr;
    3764             : #ifndef NDEBUG
    3765             :   if (VerifySCEVMap) {
    3766             :     // Check there is no dangling Value in the set returned.
    3767             :     for (const auto &VE : SI->second)
    3768             :       assert(ValueExprMap.count(VE.first));
    3769             :   }
    3770             : #endif
    3771       76914 :   return &SI->second;
    3772             : }
    3773             : 
    3774             : /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
    3775             : /// cannot be used separately. eraseValueFromMap should be used to remove
    3776             : /// V from ValueExprMap and ExprValueMap at the same time.
    3777      105399 : void ScalarEvolution::eraseValueFromMap(Value *V) {
    3778      105399 :   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
    3779      105399 :   if (I != ValueExprMap.end()) {
    3780       95546 :     const SCEV *S = I->second;
    3781             :     // Remove {V, 0} from the set of ExprValueMap[S]
    3782       95546 :     if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
    3783       53066 :       SV->remove({V, nullptr});
    3784             : 
    3785             :     // Remove {V, Offset} from the set of ExprValueMap[Stripped]
    3786             :     const SCEV *Stripped;
    3787             :     ConstantInt *Offset;
    3788      191092 :     std::tie(Stripped, Offset) = splitAddExpr(S);
    3789       95546 :     if (Offset != nullptr) {
    3790       11139 :       if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
    3791         821 :         SV->remove({V, Offset});
    3792             :     }
    3793      191092 :     ValueExprMap.erase(V);
    3794             :   }
    3795      105399 : }
    3796             : 
    3797             : /// Check whether value has nuw/nsw/exact set but SCEV does not.
    3798             : /// TODO: In reality it is better to check the poison recursevely
    3799             : /// but this is better than nothing.
    3800      564406 : static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
    3801             :   if (auto *I = dyn_cast<Instruction>(V)) {
    3802             :     if (isa<OverflowingBinaryOperator>(I)) {
    3803             :       if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
    3804       96065 :         if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
    3805             :           return true;
    3806       63073 :         if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
    3807             :           return true;
    3808             :       }
    3809        6257 :     } else if (isa<PossiblyExactOperator>(I) && I->isExact())
    3810             :       return true;
    3811             :   }
    3812             :   return false;
    3813             : }
    3814             : 
    3815             : /// Return an existing SCEV if it exists, otherwise analyze the expression and
    3816             : /// create a new one.
    3817     2285115 : const SCEV *ScalarEvolution::getSCEV(Value *V) {
    3818             :   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
    3819             : 
    3820     2285115 :   const SCEV *S = getExistingSCEV(V);
    3821     2285115 :   if (S == nullptr) {
    3822      616174 :     S = createSCEV(V);
    3823             :     // During PHI resolution, it is possible to create two SCEVs for the same
    3824             :     // V, so it is needed to double check whether V->S is inserted into
    3825             :     // ValueExprMap before insert S->{V, 0} into ExprValueMap.
    3826             :     std::pair<ValueExprMapType::iterator, bool> Pair =
    3827     1848522 :         ValueExprMap.insert({SCEVCallbackVH(V, this), S});
    3828      616174 :     if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
    3829     1091770 :       ExprValueMap[S].insert({V, nullptr});
    3830             : 
    3831             :       // If S == Stripped + Offset, add Stripped -> {V, Offset} into
    3832             :       // ExprValueMap.
    3833      545885 :       const SCEV *Stripped = S;
    3834             :       ConstantInt *Offset = nullptr;
    3835     1091770 :       std::tie(Stripped, Offset) = splitAddExpr(S);
    3836             :       // If stripped is SCEVUnknown, don't bother to save
    3837             :       // Stripped -> {V, offset}. It doesn't simplify and sometimes even
    3838             :       // increase the complexity of the expansion code.
    3839             :       // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
    3840             :       // because it may generate add/sub instead of GEP in SCEV expansion.
    3841      628858 :       if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
    3842             :           !isa<GetElementPtrInst>(V))
    3843        2625 :         ExprValueMap[Stripped].insert({V, Offset});
    3844             :     }
    3845             :   }
    3846     2285115 :   return S;
    3847             : }
    3848             : 
    3849     2360529 : const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
    3850             :   assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
    3851             : 
    3852     2360529 :   ValueExprMapType::iterator I = ValueExprMap.find_as(V);
    3853     2360529 :   if (I != ValueExprMap.end()) {
    3854     1674495 :     const SCEV *S = I->second;
    3855     1674495 :     if (checkValidity(S))
    3856             :       return S;
    3857           0 :     eraseValueFromMap(V);
    3858           0 :     forgetMemoizedResults(S);
    3859             :   }
    3860             :   return nullptr;
    3861             : }
    3862             : 
    3863             : /// Return a SCEV corresponding to -V = -1*V
    3864      712993 : const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
    3865             :                                              SCEV::NoWrapFlags Flags) {
    3866             :   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
    3867      387218 :     return getConstant(
    3868      774436 :                cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
    3869             : 
    3870      325775 :   Type *Ty = V->getType();
    3871      325775 :   Ty = getEffectiveSCEVType(Ty);
    3872      325775 :   return getMulExpr(
    3873      325775 :       V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
    3874             : }
    3875             : 
    3876             : /// Return a SCEV corresponding to ~V = -1-V
    3877      146973 : const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
    3878             :   if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
    3879       80871 :     return getConstant(
    3880      161742 :                 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
    3881             : 
    3882       66102 :   Type *Ty = V->getType();
    3883       66102 :   Ty = getEffectiveSCEVType(Ty);
    3884             :   const SCEV *AllOnes =
    3885       66102 :                    getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
    3886       66102 :   return getMinusSCEV(AllOnes, V);
    3887             : }
    3888             : 
    3889      839432 : const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
    3890             :                                           SCEV::NoWrapFlags Flags,
    3891             :                                           unsigned Depth) {
    3892             :   // Fast path: X - X --> 0.
    3893      839432 :   if (LHS == RHS)
    3894      283426 :     return getZero(LHS->getType());
    3895             : 
    3896             :   // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
    3897             :   // makes it so that we cannot make much use of NUW.
    3898             :   auto AddFlags = SCEV::FlagAnyWrap;
    3899             :   const bool RHSIsNotMinSigned =
    3900     1395438 :       !getSignedRangeMin(RHS).isMinSignedValue();
    3901      697719 :   if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
    3902             :     // Let M be the minimum representable signed value. Then (-1)*RHS
    3903             :     // signed-wraps if and only if RHS is M. That can happen even for
    3904             :     // a NSW subtraction because e.g. (-1)*M signed-wraps even though
    3905             :     // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
    3906             :     // (-1)*RHS, we need to prove that RHS != M.
    3907             :     //
    3908             :     // If LHS is non-negative and we know that LHS - RHS does not
    3909             :     // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
    3910             :     // either by proving that RHS > M or that LHS >= 0.
    3911         315 :     if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
    3912             :       AddFlags = SCEV::FlagNSW;
    3913             :     }
    3914             :   }
    3915             : 
    3916             :   // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
    3917             :   // RHS is NSW and LHS >= 0.
    3918             :   //
    3919             :   // The difficulty here is that the NSW flag may have been proven
    3920             :   // relative to a loop that is to be found in a recurrence in LHS and
    3921             :   // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
    3922             :   // larger scope than intended.
    3923      697719 :   auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
    3924             : 
    3925      697719 :   return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
    3926             : }
    3927             : 
    3928             : const SCEV *
    3929       84968 : ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
    3930       84968 :   Type *SrcTy = V->getType();
    3931             :   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
    3932             :          "Cannot truncate or zero extend with non-integer arguments!");
    3933       84968 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3934             :     return V;  // No conversion
    3935       16915 :   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
    3936        8256 :     return getTruncateExpr(V, Ty);
    3937        8659 :   return getZeroExtendExpr(V, Ty);
    3938             : }
    3939             : 
    3940             : const SCEV *
    3941      304521 : ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
    3942             :                                          Type *Ty) {
    3943      304521 :   Type *SrcTy = V->getType();
    3944             :   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
    3945             :          "Cannot truncate or zero extend with non-integer arguments!");
    3946      304521 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3947             :     return V;  // No conversion
    3948       23009 :   if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
    3949         689 :     return getTruncateExpr(V, Ty);
    3950       22320 :   return getSignExtendExpr(V, Ty);
    3951             : }
    3952             : 
    3953             : const SCEV *
    3954      157952 : ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
    3955      157952 :   Type *SrcTy = V->getType();
    3956             :   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
    3957             :          "Cannot noop or zero extend with non-integer arguments!");
    3958             :   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
    3959             :          "getNoopOrZeroExtend cannot truncate!");
    3960      157952 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3961             :     return V;  // No conversion
    3962       21220 :   return getZeroExtendExpr(V, Ty);
    3963             : }
    3964             : 
    3965             : const SCEV *
    3966        3208 : ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
    3967        3208 :   Type *SrcTy = V->getType();
    3968             :   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
    3969             :          "Cannot noop or sign extend with non-integer arguments!");
    3970             :   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
    3971             :          "getNoopOrSignExtend cannot truncate!");
    3972        3208 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3973             :     return V;  // No conversion
    3974         288 :   return getSignExtendExpr(V, Ty);
    3975             : }
    3976             : 
    3977             : const SCEV *
    3978          83 : ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
    3979          83 :   Type *SrcTy = V->getType();
    3980             :   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
    3981             :          "Cannot noop or any extend with non-integer arguments!");
    3982             :   assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
    3983             :          "getNoopOrAnyExtend cannot truncate!");
    3984          83 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3985             :     return V;  // No conversion
    3986           0 :   return getAnyExtendExpr(V, Ty);
    3987             : }
    3988             : 
    3989             : const SCEV *
    3990         276 : ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
    3991         276 :   Type *SrcTy = V->getType();
    3992             :   assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
    3993             :          "Cannot truncate or noop with non-integer arguments!");
    3994             :   assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
    3995             :          "getTruncateOrNoop cannot extend!");
    3996         276 :   if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
    3997             :     return V;  // No conversion
    3998          22 :   return getTruncateExpr(V, Ty);
    3999             : }
    4000             : 
    4001           0 : const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
    4002             :                                                         const SCEV *RHS) {
    4003             :   const SCEV *PromotedLHS = LHS;
    4004             :   const SCEV *PromotedRHS = RHS;
    4005             : 
    4006           0 :   if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
    4007           0 :     PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
    4008             :   else
    4009           0 :     PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
    4010             : 
    4011           0 :   return getUMaxExpr(PromotedLHS, PromotedRHS);
    4012             : }
    4013             : 
    4014         400 : const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
    4015             :                                                         const SCEV *RHS) {
    4016         800 :   SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
    4017         800 :   return getUMinFromMismatchedTypes(Ops);
    4018             : }
    4019             : 
    4020       31369 : const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
    4021             :     SmallVectorImpl<const SCEV *> &Ops) {
    4022             :   assert(!Ops.empty() && "At least one operand must be!");
    4023             :   // Trivial case.
    4024       31369 :   if (Ops.size() == 1)
    4025       30673 :     return Ops[0];
    4026             : 
    4027             :   // Find the max type first.
    4028             :   Type *MaxType = nullptr;
    4029        3530 :   for (auto *S : Ops)
    4030        1417 :     if (MaxType)
    4031         721 :       MaxType = getWiderType(MaxType, S->getType());
    4032             :     else
    4033         696 :       MaxType = S->getType();
    4034             : 
    4035             :   // Extend all ops to max type.
    4036             :   SmallVector<const SCEV *, 2> PromotedOps;
    4037        3530 :   for (auto *S : Ops)
    4038        1417 :     PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
    4039             : 
    4040             :   // Generate umin.
    4041         696 :   return getUMinExpr(PromotedOps);
    4042             : }
    4043             : 
    4044       56055 : const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
    4045             :   // A pointer operand may evaluate to a nonpointer expression, such as null.
    4046      219908 :   if (!V->getType()->isPointerTy())
    4047             :     return V;
    4048             : 
    4049             :   if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
    4050           0 :     return getPointerBase(Cast->getOperand());
    4051             :   } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
    4052             :     const SCEV *PtrOp = nullptr;
    4053      272319 :     for (const SCEV *NAryOp : NAry->operands()) {
    4054      218420 :       if (NAryOp->getType()->isPointerTy()) {
    4055             :         // Cannot find the base of an expression with multiple pointer operands.
    4056       53899 :         if (PtrOp)
    4057             :           return V;
    4058             :         PtrOp = NAryOp;
    4059             :       }
    4060             :     }
    4061       53899 :     if (!PtrOp)
    4062             :       return V;
    4063             :     return getPointerBase(PtrOp);
    4064             :   }
    4065             :   return V;
    4066             : }
    4067             : 
    4068             : /// Push users of the given Instruction onto the given Worklist.
    4069             : static void
    4070      385102 : PushDefUseChildren(Instruction *I,
    4071             :                    SmallVectorImpl<Instruction *> &Worklist) {
    4072             :   // Push the def-use children onto the Worklist stack.
    4073      812930 :   for (User *U : I->users())
    4074      427828 :     Worklist.push_back(cast<Instruction>(U));
    4075      385102 : }
    4076             : 
    4077        7463 : void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
    4078             :   SmallVector<Instruction *, 16> Worklist;
    4079        7463 :   PushDefUseChildren(PN, Worklist);
    4080             : 
    4081             :   SmallPtrSet<Instruction *, 8> Visited;
    4082        7463 :   Visited.insert(PN);
    4083      172254 :   while (!Worklist.empty()) {
    4084             :     Instruction *I = Worklist.pop_back_val();
    4085      164791 :     if (!Visited.insert(I).second)
    4086       48341 :       continue;
    4087             : 
    4088      142060 :     auto It = ValueExprMap.find_as(static_cast<Value *>(I));
    4089      142060 :     if (It != ValueExprMap.end()) {
    4090       13292 :       const SCEV *Old = It->second;
    4091             : 
    4092             :       // Short-circuit the def-use traversal if the symbolic name
    4093             :       // ceases to appear in expressions.
    4094       13292 :       if (Old != SymName && !hasOperand(Old, SymName))
    4095             :         continue;
    4096             : 
    4097             :       // SCEVUnknown for a PHI either means that it has an unrecognized
    4098             :       // structure, it's a PHI that's in the progress of being computed
    4099             :       // by createNodeForPHI, or it's a single-value PHI. In the first case,
    4100             :       // additional loop trip count information isn't going to change anything.
    4101             :       // In the second case, createNodeForPHI will perform the necessary
    4102             :       // updates on its own when it gets to that point. In the third, we do
    4103             :       // want to forget the SCEVUnknown.
    4104          18 :       if (!isa<PHINode>(I) ||
    4105       10418 :           !isa<SCEVUnknown>(Old) ||
    4106           5 :           (I != PN && Old == SymName)) {
    4107       10413 :         eraseValueFromMap(It->first);
    4108       10413 :         forgetMemoizedResults(Old);
    4109             :       }
    4110             :     }
    4111             : 
    4112      139181 :     PushDefUseChildren(I, Worklist);
    4113             :   }
    4114        7463 : }
    4115             : 
    4116             : namespace {
    4117             : 
    4118             : /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
    4119             : /// expression in case its Loop is L. If it is not L then
    4120             : /// if IgnoreOtherLoops is true then use AddRec itself
    4121             : /// otherwise rewrite cannot be done.
    4122             : /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
    4123             : class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
    4124             : public:
    4125       31148 :   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
    4126             :                              bool IgnoreOtherLoops = true) {
    4127             :     SCEVInitRewriter Rewriter(L, SE);
    4128       31148 :     const SCEV *Result = Rewriter.visit(S);
    4129       31148 :     if (Rewriter.hasSeenLoopVariantSCEVUnknown())
    4130        1051 :       return SE.getCouldNotCompute();
    4131       30347 :     return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
    4132       30097 :                ? SE.getCouldNotCompute()
    4133             :                : Result;
    4134             :   }
    4135             : 
    4136             :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4137        4621 :     if (!SE.isLoopInvariant(Expr, L))
    4138        1071 :       SeenLoopVariantSCEVUnknown = true;
    4139             :     return Expr;
    4140             :   }
    4141             : 
    4142             :   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
    4143             :     // Only re-write AddRecExprs for this loop.
    4144       13744 :     if (Expr->getLoop() == L)
    4145       13490 :       return Expr->getStart();
    4146         254 :     SeenOtherLoops = true;
    4147             :     return Expr;
    4148             :   }
    4149             : 
    4150             :   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
    4151             : 
    4152             :   bool hasSeenOtherLoops() { return SeenOtherLoops; }
    4153             : 
    4154             : private:
    4155             :   explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
    4156       62296 :       : SCEVRewriteVisitor(SE), L(L) {}
    4157             : 
    4158             :   const Loop *L;
    4159             :   bool SeenLoopVariantSCEVUnknown = false;
    4160             :   bool SeenOtherLoops = false;
    4161             : };
    4162             : 
    4163             : /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
    4164             : /// increment expression in case its Loop is L. If it is not L then
    4165             : /// use AddRec itself.
    4166             : /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
    4167             : class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
    4168             : public:
    4169       24969 :   static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
    4170             :     SCEVPostIncRewriter Rewriter(L, SE);
    4171       24969 :     const SCEV *Result = Rewriter.visit(S);
    4172       24969 :     return Rewriter.hasSeenLoopVariantSCEVUnknown()
    4173       24969 :         ? SE.getCouldNotCompute()
    4174       24969 :         : Result;
    4175             :   }
    4176             : 
    4177             :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4178        3409 :     if (!SE.isLoopInvariant(Expr, L))
    4179           0 :       SeenLoopVariantSCEVUnknown = true;
    4180             :     return Expr;
    4181             :   }
    4182             : 
    4183       13196 :   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
    4184             :     // Only re-write AddRecExprs for this loop.
    4185       13196 :     if (Expr->getLoop() == L)
    4186       12946 :       return Expr->getPostIncExpr(SE);
    4187         250 :     SeenOtherLoops = true;
    4188         250 :     return Expr;
    4189             :   }
    4190             : 
    4191             :   bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
    4192             : 
    4193             :   bool hasSeenOtherLoops() { return SeenOtherLoops; }
    4194             : 
    4195             : private:
    4196             :   explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
    4197       49938 :       : SCEVRewriteVisitor(SE), L(L) {}
    4198             : 
    4199             :   const Loop *L;
    4200             :   bool SeenLoopVariantSCEVUnknown = false;
    4201             :   bool SeenOtherLoops = false;
    4202             : };
    4203             : 
    4204             : /// This class evaluates the compare condition by matching it against the
    4205             : /// condition of loop latch. If there is a match we assume a true value
    4206             : /// for the condition while building SCEV nodes.
    4207             : class SCEVBackedgeConditionFolder
    4208             :     : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
    4209             : public:
    4210        8459 :   static const SCEV *rewrite(const SCEV *S, const Loop *L,
    4211             :                              ScalarEvolution &SE) {
    4212             :     bool IsPosBECond = false;
    4213             :     Value *BECond = nullptr;
    4214        8459 :     if (BasicBlock *Latch = L->getLoopLatch()) {
    4215             :       BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
    4216        8452 :       if (BI && BI->isConditional()) {
    4217             :         assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
    4218             :                "Both outgoing branches should not target same header!");
    4219             :         BECond = BI->getCondition();
    4220        7732 :         IsPosBECond = BI->getSuccessor(0) == L->getHeader();
    4221             :       } else {
    4222             :         return S;
    4223             :       }
    4224             :     }
    4225             :     SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
    4226        7737 :     return Rewriter.visit(S);
    4227             :   }
    4228             : 
    4229        1904 :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4230        1904 :     const SCEV *Result = Expr;
    4231        1904 :     bool InvariantF = SE.isLoopInvariant(Expr, L);
    4232             : 
    4233        1904 :     if (!InvariantF) {
    4234             :       Instruction *I = cast<Instruction>(Expr->getValue());
    4235        1609 :       switch (I->getOpcode()) {
    4236             :       case Instruction::Select: {
    4237             :         SelectInst *SI = cast<SelectInst>(I);
    4238             :         Optional<const SCEV *> Res =
    4239          96 :             compareWithBackedgeCondition(SI->getCondition());
    4240          96 :         if (Res.hasValue()) {
    4241           5 :           bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
    4242          10 :           Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
    4243             :         }
    4244             :         break;
    4245             :       }
    4246        1513 :       default: {
    4247        1513 :         Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
    4248        1513 :         if (Res.hasValue())
    4249           4 :           Result = Res.getValue();
    4250             :         break;
    4251             :       }
    4252             :       }
    4253             :     }
    4254        1904 :     return Result;
    4255             :   }
    4256             : 
    4257             : private:
    4258             :   explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
    4259             :                                        bool IsPosBECond, ScalarEvolution &SE)
    4260        7737 :       : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
    4261        7737 :         IsPositiveBECond(IsPosBECond) {}
    4262             : 
    4263             :   Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
    4264             : 
    4265             :   const Loop *L;
    4266             :   /// Loop back condition.
    4267             :   Value *BackedgeCond = nullptr;
    4268             :   /// Set to true if loop back is on positive branch condition.
    4269             :   bool IsPositiveBECond;
    4270             : };
    4271             : 
    4272             : Optional<const SCEV *>
    4273        1609 : SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
    4274             : 
    4275             :   // If value matches the backedge condition for loop latch,
    4276             :   // then return a constant evolution node based on loopback
    4277             :   // branch taken.
    4278        1609 :   if (BackedgeCond == IC)
    4279          17 :     return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
    4280           2 :                             : SE.getZero(Type::getInt1Ty(SE.getContext()));
    4281             :   return None;
    4282             : }
    4283             : 
    4284             : class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
    4285             : public:
    4286        5128 :   static const SCEV *rewrite(const SCEV *S, const Loop *L,
    4287             :                              ScalarEvolution &SE) {
    4288             :     SCEVShiftRewriter Rewriter(L, SE);
    4289        5128 :     const SCEV *Result = Rewriter.visit(S);
    4290       10256 :     return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
    4291             :   }
    4292             : 
    4293             :   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
    4294             :     // Only allow AddRecExprs for this loop.
    4295        4541 :     if (!SE.isLoopInvariant(Expr, L))
    4296        4421 :       Valid = false;
    4297             :     return Expr;
    4298             :   }
    4299             : 
    4300         660 :   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
    4301        1226 :     if (Expr->getLoop() == L && Expr->isAffine())
    4302         566 :       return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
    4303          94 :     Valid = false;
    4304          94 :     return Expr;
    4305             :   }
    4306             : 
    4307             :   bool isValid() { return Valid; }
    4308             : 
    4309             : private:
    4310             :   explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
    4311       10256 :       : SCEVRewriteVisitor(SE), L(L) {}
    4312             : 
    4313             :   const Loop *L;
    4314             :   bool Valid = true;
    4315             : };
    4316             : 
    4317             : } // end anonymous namespace
    4318             : 
    4319             : SCEV::NoWrapFlags
    4320       33441 : ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
    4321       33441 :   if (!AR->isAffine())
    4322             :     return SCEV::FlagAnyWrap;
    4323             : 
    4324             :   using OBO = OverflowingBinaryOperator;
    4325             : 
    4326             :   SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
    4327             : 
    4328       33441 :   if (!AR->hasNoSignedWrap()) {
    4329       22163 :     ConstantRange AddRecRange = getSignedRange(AR);
    4330       44326 :     ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
    4331             : 
    4332             :     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    4333       44326 :         Instruction::Add, IncRange, OBO::NoSignedWrap);
    4334       22163 :     if (NSWRegion.contains(AddRecRange))
    4335             :       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
    4336             :   }
    4337             : 
    4338       33441 :   if (!AR->hasNoUnsignedWrap()) {
    4339       32189 :     ConstantRange AddRecRange = getUnsignedRange(AR);
    4340       64378 :     ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
    4341             : 
    4342             :     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
    4343       64378 :         Instruction::Add, IncRange, OBO::NoUnsignedWrap);
    4344       32189 :     if (NUWRegion.contains(AddRecRange))
    4345             :       Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
    4346             :   }
    4347             : 
    4348             :   return Result;
    4349             : }
    4350             : 
    4351             : namespace {
    4352             : 
    4353             : /// Represents an abstract binary operation.  This may exist as a
    4354             : /// normal instruction or constant expression, or may have been
    4355             : /// derived from an expression tree.
    4356             : struct BinaryOp {
    4357             :   unsigned Opcode;
    4358             :   Value *LHS;
    4359             :   Value *RHS;
    4360             :   bool IsNSW = false;
    4361             :   bool IsNUW = false;
    4362             : 
    4363             :   /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
    4364             :   /// constant expression.
    4365             :   Operator *Op = nullptr;
    4366             : 
    4367      136930 :   explicit BinaryOp(Operator *Op)
    4368      273860 :       : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
    4369      410790 :         Op(Op) {
    4370             :     if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
    4371      129012 :       IsNSW = OBO->hasNoSignedWrap();
    4372      129012 :       IsNUW = OBO->hasNoUnsignedWrap();
    4373             :     }
    4374      136930 :   }
    4375             : 
    4376             :   explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
    4377             :                     bool IsNUW = false)
    4378             :       : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
    4379             : };
    4380             : 
    4381             : } // end anonymous namespace
    4382             : 
    4383             : /// Try to map \p V into a BinaryOp, and return \c None on failure.
    4384      546069 : static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
    4385             :   auto *Op = dyn_cast<Operator>(V);
    4386             :   if (!Op)
    4387             :     return None;
    4388             : 
    4389             :   // Implementation detail: all the cleverness here should happen without
    4390             :   // creating new SCEV expressions -- our caller knowns tricks to avoid creating
    4391             :   // SCEV expressions when possible, and we should not break that.
    4392             : 
    4393      542474 :   switch (Op->getOpcode()) {
    4394      135933 :   case Instruction::Add:
    4395             :   case Instruction::Sub:
    4396             :   case Instruction::Mul:
    4397             :   case Instruction::UDiv:
    4398             :   case Instruction::URem:
    4399             :   case Instruction::And:
    4400             :   case Instruction::Or:
    4401             :   case Instruction::AShr:
    4402             :   case Instruction::Shl:
    4403      271866 :     return BinaryOp(Op);
    4404             : 
    4405         697 :   case Instruction::Xor:
    4406         697 :     if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
    4407             :       // If the RHS of the xor is a signmask, then this is just an add.
    4408             :       // Instcombine turns add of signmask into xor as a strength reduction step.
    4409         162 :       if (RHSC->getValue().isSignMask())
    4410             :         return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
    4411        1340 :     return BinaryOp(Op);
    4412             : 
    4413        5441 :   case Instruction::LShr:
    4414             :     // Turn logical shift right of a constant into a unsigned divide.
    4415        5441 :     if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
    4416        5116 :       uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
    4417             : 
    4418             :       // If the shift count is not less than the bitwidth, the result of
    4419             :       // the shift is undefined. Don't try to analyze it, because the
    4420             :       // resolution chosen here may differ from the resolution chosen in
    4421             :       // other parts of the compiler.
    4422        5116 :       if (SA->getValue().ult(BitWidth)) {
    4423             :         Constant *X =
    4424        5114 :             ConstantInt::get(SA->getContext(),
    4425       15342 :                              APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
    4426             :         return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
    4427             :       }
    4428             :     }
    4429         654 :     return BinaryOp(Op);
    4430             : 
    4431             :   case Instruction::ExtractValue: {
    4432             :     auto *EVI = cast<ExtractValueInst>(Op);
    4433         902 :     if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
    4434             :       break;
    4435             : 
    4436             :     auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
    4437             :     if (!CI)
    4438             :       break;
    4439             : 
    4440             :     if (auto *F = CI->getCalledFunction())
    4441         187 :       switch (F->getIntrinsicID()) {
    4442             :       case Intrinsic::sadd_with_overflow:
    4443             :       case Intrinsic::uadd_with_overflow:
    4444          93 :         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
    4445          30 :           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
    4446             :                           CI->getArgOperand(1));
    4447             : 
    4448             :         // Now that we know that all uses of the arithmetic-result component of
    4449             :         // CI are guarded by the overflow check, we can go ahead and pretend
    4450             :         // that the arithmetic is non-overflowing.
    4451          63 :         if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
    4452          56 :           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
    4453             :                           CI->getArgOperand(1), /* IsNSW = */ true,
    4454             :                           /* IsNUW = */ false);
    4455             :         else
    4456           7 :           return BinaryOp(Instruction::Add, CI->getArgOperand(0),
    4457             :                           CI->getArgOperand(1), /* IsNSW = */ false,
    4458             :                           /* IsNUW*/ true);
    4459             :       case Intrinsic::ssub_with_overflow:
    4460             :       case Intrinsic::usub_with_overflow:
    4461          61 :         if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
    4462          22 :           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
    4463             :                           CI->getArgOperand(1));
    4464             : 
    4465             :         // The same reasoning as sadd/uadd above.
    4466          39 :         if (F->getIntrinsicID() == Intrinsic::ssub_with_overflow)
    4467          21 :           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
    4468             :                           CI->getArgOperand(1), /* IsNSW = */ true,
    4469             :                           /* IsNUW = */ false);
    4470             :         else
    4471          18 :           return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
    4472             :                           CI->getArgOperand(1), /* IsNSW = */ false,
    4473             :                           /* IsNUW = */ true);
    4474           7 :       case Intrinsic::smul_with_overflow:
    4475             :       case Intrinsic::umul_with_overflow:
    4476           7 :         return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
    4477             :                         CI->getArgOperand(1));
    4478             :       default:
    4479             :         break;
    4480             :       }
    4481             :     break;
    4482             :   }
    4483             : 
    4484             :   default:
    4485             :     break;
    4486             :   }
    4487             : 
    4488             :   return None;
    4489             : }
    4490             : 
    4491             : /// Helper function to createAddRecFromPHIWithCasts. We have a phi
    4492             : /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
    4493             : /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
    4494             : /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
    4495             : /// follows one of the following patterns:
    4496             : /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
    4497             : /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
    4498             : /// If the SCEV expression of \p Op conforms with one of the expected patterns
    4499             : /// we return the type of the truncation operation, and indicate whether the
    4500             : /// truncated type should be treated as signed/unsigned by setting
    4501             : /// \p Signed to true/false, respectively.
    4502          99 : static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
    4503             :                                bool &Signed, ScalarEvolution &SE) {
    4504             :   // The case where Op == SymbolicPHI (that is, with no type conversions on
    4505             :   // the way) is handled by the regular add recurrence creating logic and
    4506             :   // would have already been triggered in createAddRecForPHI. Reaching it here
    4507             :   // means that createAddRecFromPHI had failed for this PHI before (e.g.,
    4508             :   // because one of the other operands of the SCEVAddExpr updating this PHI is
    4509             :   // not invariant).
    4510             :   //
    4511             :   // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
    4512             :   // this case predicates that allow us to prove that Op == SymbolicPHI will
    4513             :   // be added.
    4514          99 :   if (Op == SymbolicPHI)
    4515             :     return nullptr;
    4516             : 
    4517          84 :   unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
    4518          84 :   unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
    4519          84 :   if (SourceBits != NewBits)
    4520             :     return nullptr;
    4521             : 
    4522             :   const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
    4523             :   const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
    4524          84 :   if (!SExt && !ZExt)
    4525             :     return nullptr;
    4526             :   const SCEVTruncateExpr *Trunc =
    4527          23 :       SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
    4528          12 :            : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
    4529          19 :   if (!Trunc)
    4530             :     return nullptr;
    4531          19 :   const SCEV *X = Trunc->getOperand();
    4532          19 :   if (X != SymbolicPHI)
    4533             :     return nullptr;
    4534          19 :   Signed = SExt != nullptr;
    4535          19 :   return Trunc->getType();
    4536             : }
    4537             : 
    4538        1337 : static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
    4539        2674 :   if (!PN->getType()->isIntegerTy())
    4540             :     return nullptr;
    4541         938 :   const Loop *L = LI.getLoopFor(PN->getParent());
    4542        1706 :   if (!L || L->getHeader() != PN->getParent())
    4543             :     return nullptr;
    4544             :   return L;
    4545             : }
    4546             : 
    4547             : // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
    4548             : // computation that updates the phi follows the following pattern:
    4549             : //   (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
    4550             : // which correspond to a phi->trunc->sext/zext->add->phi update chain.
    4551             : // If so, try to see if it can be rewritten as an AddRecExpr under some
    4552             : // Predicates. If successful, return them as a pair. Also cache the results
    4553             : // of the analysis.
    4554             : //
    4555             : // Example usage scenario:
    4556             : //    Say the Rewriter is called for the following SCEV:
    4557             : //         8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
    4558             : //    where:
    4559             : //         %X = phi i64 (%Start, %BEValue)
    4560             : //    It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
    4561             : //    and call this function with %SymbolicPHI = %X.
    4562             : //
    4563             : //    The analysis will find that the value coming around the backedge has
    4564             : //    the following SCEV:
    4565             : //         BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
    4566             : //    Upon concluding that this matches the desired pattern, the function
    4567             : //    will return the pair {NewAddRec, SmallPredsVec} where:
    4568             : //         NewAddRec = {%Start,+,%Step}
    4569             : //         SmallPredsVec = {P1, P2, P3} as follows:
    4570             : //           P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
    4571             : //           P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
    4572             : //           P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
    4573             : //    The returned pair means that SymbolicPHI can be rewritten into NewAddRec
    4574             : //    under the predicates {P1,P2,P3}.
    4575             : //    This predicated rewrite will be cached in PredicatedSCEVRewrites:
    4576             : //         PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
    4577             : //
    4578             : // TODO's:
    4579             : //
    4580             : // 1) Extend the Induction descriptor to also support inductions that involve
    4581             : //    casts: When needed (namely, when we are called in the context of the
    4582             : //    vectorizer induction analysis), a Set of cast instructions will be
    4583             : //    populated by this method, and provided back to isInductionPHI. This is
    4584             : //    needed to allow the vectorizer to properly record them to be ignored by
    4585             : //    the cost model and to avoid vectorizing them (otherwise these casts,
    4586             : //    which are redundant under the runtime overflow checks, will be
    4587             : //    vectorized, which can be costly).
    4588             : //
    4589             : // 2) Support additional induction/PHISCEV patterns: We also want to support
    4590             : //    inductions where the sext-trunc / zext-trunc operations (partly) occur
    4591             : //    after the induction update operation (the induction increment):
    4592             : //
    4593             : //      (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
    4594             : //    which correspond to a phi->add->trunc->sext/zext->phi update chain.
    4595             : //
    4596             : //      (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
    4597             : //    which correspond to a phi->trunc->add->sext/zext->phi update chain.
    4598             : //
    4599             : // 3) Outline common code with createAddRecFromPHI to avoid duplication.
    4600             : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
    4601         286 : ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
    4602             :   SmallVector<const SCEVPredicate *, 3> Predicates;
    4603             : 
    4604             :   // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
    4605             :   // return an AddRec expression under some predicate.
    4606             : 
    4607             :   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
    4608         286 :   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
    4609             :   assert(L && "Expecting an integer loop header phi");
    4610             : 
    4611             :   // The loop may have multiple entrances or multiple exits; we can analyze
    4612             :   // this phi as an addrec if it has a unique entry value and a unique
    4613             :   // backedge value.
    4614             :   Value *BEValueV = nullptr, *StartValueV = nullptr;
    4615        1430 :   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    4616             :     Value *V = PN->getIncomingValue(i);
    4617         573 :     if (L->contains(PN->getIncomingBlock(i))) {
    4618         286 :       if (!BEValueV) {
    4619             :         BEValueV = V;
    4620           0 :       } else if (BEValueV != V) {
    4621             :         BEValueV = nullptr;
    4622             :         break;
    4623             :       }
    4624         287 :     } else if (!StartValueV) {
    4625             :       StartValueV = V;
    4626           1 :     } else if (StartValueV != V) {
    4627             :       StartValueV = nullptr;
    4628             :       break;
    4629             :     }
    4630             :   }
    4631         286 :   if (!BEValueV || !StartValueV)
    4632             :     return None;
    4633             : 
    4634         285 :   const SCEV *BEValue = getSCEV(BEValueV);
    4635             : 
    4636             :   // If the value coming around the backedge is an add with the symbolic
    4637             :   // value we just inserted, possibly with casts that we can ignore under
    4638             :   // an appropriate runtime guard, then we found a simple induction variable!
    4639             :   const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
    4640             :   if (!Add)
    4641             :     return None;
    4642             : 
    4643             :   // If there is a single occurrence of the symbolic value, possibly
    4644             :   // casted, replace it with a recurrence.
    4645          49 :   unsigned FoundIndex = Add->getNumOperands();
    4646          49 :   Type *TruncTy = nullptr;
    4647             :   bool Signed;
    4648         209 :   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4649          99 :     if ((TruncTy =
    4650         198 :              isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
    4651             :       if (FoundIndex == e) {
    4652             :         FoundIndex = i;
    4653             :         break;
    4654             :       }
    4655             : 
    4656          49 :   if (FoundIndex == Add->getNumOperands())
    4657             :     return None;
    4658             : 
    4659             :   // Create an add with everything but the specified operand.
    4660             :   SmallVector<const SCEV *, 8> Ops;
    4661          57 :   for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4662          38 :     if (i != FoundIndex)
    4663          38 :       Ops.push_back(Add->getOperand(i));
    4664          19 :   const SCEV *Accum = getAddExpr(Ops);
    4665             : 
    4666             :   // The runtime checks will not be valid if the step amount is
    4667             :   // varying inside the loop.
    4668          19 :   if (!isLoopInvariant(Accum, L))
    4669             :     return None;
    4670             : 
    4671             :   // *** Part2: Create the predicates
    4672             : 
    4673             :   // Analysis was successful: we have a phi-with-cast pattern for which we
    4674             :   // can return an AddRec expression under the following predicates:
    4675             :   //
    4676             :   // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
    4677             :   //     fits within the truncated type (does not overflow) for i = 0 to n-1.
    4678             :   // P2: An Equal predicate that guarantees that
    4679             :   //     Start = (Ext ix (Trunc iy (Start) to ix) to iy)
    4680             :   // P3: An Equal predicate that guarantees that
    4681             :   //     Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
    4682             :   //
    4683             :   // As we next prove, the above predicates guarantee that:
    4684             :   //     Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
    4685             :   //
    4686             :   //
    4687             :   // More formally, we want to prove that:
    4688             :   //     Expr(i+1) = Start + (i+1) * Accum
    4689             :   //               = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
    4690             :   //
    4691             :   // Given that:
    4692             :   // 1) Expr(0) = Start
    4693             :   // 2) Expr(1) = Start + Accum
    4694             :   //            = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
    4695             :   // 3) Induction hypothesis (step i):
    4696             :   //    Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
    4697             :   //
    4698             :   // Proof:
    4699             :   //  Expr(i+1) =
    4700             :   //   = Start + (i+1)*Accum
    4701             :   //   = (Start + i*Accum) + Accum
    4702             :   //   = Expr(i) + Accum
    4703             :   //   = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
    4704             :   //                                                             :: from step i
    4705             :   //
    4706             :   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
    4707             :   //
    4708             :   //   = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
    4709             :   //     + (Ext ix (Trunc iy (Accum) to ix) to iy)
    4710             :   //     + Accum                                                     :: from P3
    4711             :   //
    4712             :   //   = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
    4713             :   //     + Accum                            :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
    4714             :   //
    4715             :   //   = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
    4716             :   //   = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
    4717             :   //
    4718             :   // By induction, the same applies to all iterations 1<=i<n:
    4719             :   //
    4720             : 
    4721             :   // Create a truncated addrec for which we will add a no overflow check (P1).
    4722          18 :   const SCEV *StartVal = getSCEV(StartValueV);
    4723             :   const SCEV *PHISCEV =
    4724          18 :       getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
    4725          18 :                     getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
    4726             : 
    4727             :   // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
    4728             :   // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
    4729             :   // will be constant.
    4730             :   //
    4731             :   //  If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
    4732             :   // add P1.
    4733             :   if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
    4734             :     SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
    4735          16 :         Signed ? SCEVWrapPredicate::IncrementNSSW
    4736             :                : SCEVWrapPredicate::IncrementNUSW;
    4737          16 :     const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
    4738          16 :     Predicates.push_back(AddRecPred);
    4739             :   }
    4740             : 
    4741             :   // Create the Equal Predicates P2,P3:
    4742             : 
    4743             :   // It is possible that the predicates P2 and/or P3 are computable at
    4744             :   // compile time due to StartVal and/or Accum being constants.
    4745             :   // If either one is, then we can check that now and escape if either P2
    4746             :   // or P3 is false.
    4747             : 
    4748             :   // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
    4749             :   // for each of StartVal and Accum
    4750             :   auto getExtendedExpr = [&](const SCEV *Expr, 
    4751          35 :                              bool CreateSignExtend) -> const SCEV * {
    4752             :     assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
    4753          70 :     const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
    4754             :     const SCEV *ExtendedExpr =
    4755          70 :         CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
    4756          10 :                          : getZeroExtendExpr(TruncatedExpr, Expr->getType());
    4757          35 :     return ExtendedExpr;
    4758          18 :   };
    4759             : 
    4760             :   // Given:
    4761             :   //  ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
    4762             :   //               = getExtendedExpr(Expr)
    4763             :   // Determine whether the predicate P: Expr == ExtendedExpr
    4764             :   // is known to be false at compile time
    4765             :   auto PredIsKnownFalse = [&](const SCEV *Expr,
    4766             :                               const SCEV *ExtendedExpr) -> bool {
    4767          53 :     return Expr != ExtendedExpr &&
    4768          18 :            isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
    4769             :   };
    4770             : 
    4771          18 :   const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
    4772             :   if (PredIsKnownFalse(StartVal, StartExtended)) {
    4773             :     LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
    4774             :     return None;
    4775             :   }
    4776             : 
    4777             :   // The Step is always Signed (because the overflow checks are either
    4778             :   // NSSW or NUSW)
    4779          17 :   const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
    4780             :   if (PredIsKnownFalse(Accum, AccumExtended)) {
    4781             :     LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
    4782             :     return None;
    4783             :   }
    4784             : 
    4785             :   auto AppendPredicate = [&](const SCEV *Expr,
    4786          26 :                              const SCEV *ExtendedExpr) -> void {
    4787          35 :     if (Expr != ExtendedExpr &&
    4788          18 :         !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
    4789           9 :       const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
    4790             :       LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
    4791           9 :       Predicates.push_back(Pred);
    4792             :     }
    4793          39 :   };
    4794             : 
    4795          13 :   AppendPredicate(StartVal, StartExtended);
    4796          13 :   AppendPredicate(Accum, AccumExtended);
    4797             : 
    4798             :   // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
    4799             :   // which the casts had been folded away. The caller can rewrite SymbolicPHI
    4800             :   // into NewAR if it will also add the runtime overflow checks specified in
    4801             :   // Predicates.
    4802          13 :   auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
    4803             : 
    4804             :   std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
    4805             :       std::make_pair(NewAR, Predicates);
    4806             :   // Remember the result of the analysis for this SCEV at this locayyytion.
    4807          26 :   PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
    4808             :   return PredRewrite;
    4809             : }
    4810             : 
    4811             : Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
    4812        1051 : ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
    4813             :   auto *PN = cast<PHINode>(SymbolicPHI->getValue());
    4814        1051 :   const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
    4815        1051 :   if (!L)
    4816             :     return None;
    4817             : 
    4818             :   // Check to see if we already analyzed this PHI.
    4819        1068 :   auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
    4820         534 :   if (I != PredicatedSCEVRewrites.end()) {
    4821             :     std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
    4822             :         I->second;
    4823             :     // Analysis was done before and failed to create an AddRec:
    4824         248 :     if (Rewrite.first == SymbolicPHI)
    4825             :       return None;
    4826             :     // Analysis was done before and succeeded to create an AddRec under
    4827             :     // a predicate:
    4828             :     assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
    4829             :     assert(!(Rewrite.second).empty() && "Expected to find Predicates");
    4830             :     return Rewrite;
    4831             :   }
    4832             : 
    4833             :   Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
    4834         286 :     Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
    4835             : 
    4836             :   // Record in the cache that the analysis failed
    4837         286 :   if (!Rewrite) {
    4838             :     SmallVector<const SCEVPredicate *, 3> Predicates;
    4839         546 :     PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
    4840             :     return None;
    4841             :   }
    4842             : 
    4843             :   return Rewrite;
    4844             : }
    4845             : 
    4846             : // FIXME: This utility is currently required because the Rewriter currently 
    4847             : // does not rewrite this expression: 
    4848             : // {0, +, (sext ix (trunc iy to ix) to iy)} 
    4849             : // into {0, +, %step},
    4850             : // even when the following Equal predicate exists: 
    4851             : // "%step == (sext ix (trunc iy to ix) to iy)".
    4852          28 : bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
    4853             :     const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
    4854          28 :   if (AR1 == AR2)
    4855             :     return true;
    4856             : 
    4857          39 :   auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
    4858          64 :     if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
    4859          25 :         !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
    4860             :       return false;
    4861             :     return true;
    4862          25 :   };
    4863             : 
    4864          89 :   if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
    4865          14 :       !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
    4866             :     return false;
    4867             :   return true;
    4868             : }
    4869             : 
    4870             : /// A helper function for createAddRecFromPHI to handle simple cases.
    4871             : ///
    4872             : /// This function tries to find an AddRec expression for the simplest (yet most
    4873             : /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
    4874             : /// If it fails, createAddRecFromPHI will use a more general, but slow,
    4875             : /// technique for finding the AddRec expression.
    4876       48933 : const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
    4877             :                                                       Value *BEValueV,
    4878             :                                                       Value *StartValueV) {
    4879       48933 :   const Loop *L = LI.getLoopFor(PN->getParent());
    4880             :   assert(L && L->getHeader() == PN->getParent());
    4881             :   assert(BEValueV && StartValueV);
    4882             : 
    4883       48933 :   auto BO = MatchBinaryOp(BEValueV, DT);
    4884       48933 :   if (!BO)
    4885             :     return nullptr;
    4886             : 
    4887       38686 :   if (BO->Opcode != Instruction::Add)
    4888             :     return nullptr;
    4889             : 
    4890             :   const SCEV *Accum = nullptr;
    4891       37794 :   if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
    4892       35588 :     Accum = getSCEV(BO->RHS);
    4893        2206 :   else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
    4894          57 :     Accum = getSCEV(BO->LHS);
    4895             : 
    4896       35645 :   if (!Accum)
    4897             :     return nullptr;
    4898             : 
    4899             :   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    4900       35645 :   if (BO->IsNUW)
    4901             :     Flags = setFlags(Flags, SCEV::FlagNUW);
    4902       35645 :   if (BO->IsNSW)
    4903             :     Flags = setFlags(Flags, SCEV::FlagNSW);
    4904             : 
    4905       35645 :   const SCEV *StartVal = getSCEV(StartValueV);
    4906       35645 :   const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
    4907             : 
    4908      106935 :   ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
    4909             : 
    4910             :   // We can add Flags to the post-inc expression only if we
    4911             :   // know that it is *undefined behavior* for BEValueV to
    4912             :   // overflow.
    4913             :   if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
    4914       35645 :     if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
    4915       14857 :       (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
    4916             : 
    4917             :   return PHISCEV;
    4918             : }
    4919             : 
    4920       55737 : const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
    4921       55737 :   const Loop *L = LI.getLoopFor(PN->getParent());
    4922      106858 :   if (!L || L->getHeader() != PN->getParent())
    4923             :     return nullptr;
    4924             : 
    4925             :   // The loop may have multiple entrances or multiple exits; we can analyze
    4926             :   // this phi as an addrec if it has a unique entry value and a unique
    4927             :   // backedge value.
    4928             :   Value *BEValueV = nullptr, *StartValueV = nullptr;
    4929      244944 :   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    4930             :     Value *V = PN->getIncomingValue(i);
    4931       98023 :     if (L->contains(PN->getIncomingBlock(i))) {
    4932       49038 :       if (!BEValueV) {
    4933             :         BEValueV = V;
    4934          70 :       } else if (BEValueV != V) {
    4935             :         BEValueV = nullptr;
    4936             :         break;
    4937             :       }
    4938       48985 :     } else if (!StartValueV) {
    4939             :       StartValueV = V;
    4940          24 :     } else if (StartValueV != V) {
    4941             :       StartValueV = nullptr;
    4942             :       break;
    4943             :     }
    4944             :   }
    4945       48968 :   if (!BEValueV || !StartValueV)
    4946             :     return nullptr;
    4947             : 
    4948             :   assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
    4949             :          "PHI node already processed?");
    4950             : 
    4951             :   // First, try to find AddRec expression without creating a fictituos symbolic
    4952             :   // value for PN.
    4953       48933 :   if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
    4954             :     return S;
    4955             : 
    4956             :   // Handle PHI node value symbolically.
    4957       13288 :   const SCEV *SymbolicName = getUnknown(PN);
    4958       53152 :   ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
    4959             : 
    4960             :   // Using this symbolic name for the PHI, analyze the value coming around
    4961             :   // the back-edge.
    4962       13288 :   const SCEV *BEValue = getSCEV(BEValueV);
    4963             : 
    4964             :   // NOTE: If BEValue is loop invariant, we know that the PHI node just
    4965             :   // has a special value for the first iteration of the loop.
    4966             : 
    4967             :   // If the value coming around the backedge is an add with the symbolic
    4968             :   // value we just inserted, then we found a simple induction variable!
    4969             :   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
    4970             :     // If there is a single occurrence of the symbolic value, replace it
    4971             :     // with a recurrence.
    4972        8160 :     unsigned FoundIndex = Add->getNumOperands();
    4973       26396 :     for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4974       33700 :       if (Add->getOperand(i) == SymbolicName)
    4975             :         if (FoundIndex == e) {
    4976             :           FoundIndex = i;
    4977             :           break;
    4978             :         }
    4979             : 
    4980        8160 :     if (FoundIndex != Add->getNumOperands()) {
    4981             :       // Create an add with everything but the specified operand.
    4982             :       SmallVector<const SCEV *, 8> Ops;
    4983       40114 :       for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
    4984       16191 :         if (i != FoundIndex)
    4985       16918 :           Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
    4986             :                                                              L, *this));
    4987        7732 :       const SCEV *Accum = getAddExpr(Ops);
    4988             : 
    4989             :       // This is not a valid addrec if the step amount is varying each
    4990             :       // loop iteration, but is not itself an addrec in this loop.
    4991        8608 :       if (isLoopInvariant(Accum, L) ||
    4992          68 :           (isa<SCEVAddRecExpr>(Accum) &&
    4993          68 :            cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
    4994             :         SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    4995             : 
    4996        6924 :         if (auto BO = MatchBinaryOp(BEValueV, DT)) {
    4997        1299 :           if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
    4998          49 :             if (BO->IsNUW)
    4999             :               Flags = setFlags(Flags, SCEV::FlagNUW);
    5000          49 :             if (BO->IsNSW)
    5001             :               Flags = setFlags(Flags, SCEV::FlagNSW);
    5002             :           }
    5003             :         } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
    5004             :           // If the increment is an inbounds GEP, then we know the address
    5005             :           // space cannot be wrapped around. We cannot make any guarantee
    5006             :           // about signed or unsigned overflow because pointers are
    5007             :           // unsigned but we may have a negative index from the base
    5008             :           // pointer. We can guarantee that no unsigned wrap occurs if the
    5009             :           // indices form a positive value.
    5010        9499 :           if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
    5011             :             Flags = setFlags(Flags, SCEV::FlagNW);
    5012             : 
    5013        4217 :             const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
    5014        4217 :             if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
    5015             :               Flags = setFlags(Flags, SCEV::FlagNUW);
    5016             :           }
    5017             : 
    5018             :           // We cannot transfer nuw and nsw flags from subtraction
    5019             :           // operations -- sub nuw X, Y is not the same as add nuw X, -Y
    5020             :           // for instance.
    5021             :         }
    5022             : 
    5023        6924 :         const SCEV *StartVal = getSCEV(StartValueV);
    5024        6924 :         const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
    5025             : 
    5026             :         // Okay, for the entire analysis of this edge we assumed the PHI
    5027             :         // to be symbolic.  We now need to go back and purge all of the
    5028             :         // entries for the scalars that use the symbolic expression.
    5029        6924 :         forgetSymbolicName(PN, SymbolicName);
    5030       20772 :         ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
    5031             : 
    5032             :         // We can add Flags to the post-inc expression only if we
    5033             :         // know that it is *undefined behavior* for BEValueV to
    5034             :         // overflow.
    5035             :         if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
    5036        6924 :           if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
    5037        1964 :             (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
    5038             : 
    5039             :         return PHISCEV;
    5040             :       }
    5041             :     }
    5042             :   } else {
    5043             :     // Otherwise, this could be a loop like this:
    5044             :     //     i = 0;  for (j = 1; ..; ++j) { ....  i = j; }
    5045             :     // In this case, j = {1,+,1}  and BEValue is j.
    5046             :     // Because the other in-value of i (0) fits the evolution of BEValue
    5047             :     // i really is an addrec evolution.
    5048             :     //
    5049             :     // We can generalize this saying that i is the shifted value of BEValue
    5050             :     // by one iteration:
    5051             :     //   PHI(f(0), f({1,+,1})) --> f({0,+,1})
    5052        5128 :     const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
    5053        5128 :     const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
    5054        5880 :     if (Shifted != getCouldNotCompute() &&
    5055         752 :         Start != getCouldNotCompute()) {
    5056         752 :       const SCEV *StartVal = getSCEV(StartValueV);
    5057         752 :       if (Start == StartVal) {
    5058             :         // Okay, for the entire analysis of this edge we assumed the PHI
    5059             :         // to be symbolic.  We now need to go back and purge all of the
    5060             :         // entries for the scalars that use the symbolic expression.
    5061         539 :         forgetSymbolicName(PN, SymbolicName);
    5062        1617 :         ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
    5063         539 :         return Shifted;
    5064             :       }
    5065             :     }
    5066             :   }
    5067             : 
    5068             :   // Remove the temporary PHI node SCEV that has been inserted while intending
    5069             :   // to create an AddRecExpr for this PHI node. We can not keep this temporary
    5070             :   // as it will prevent later (possibly simpler) SCEV expressions to be added
    5071             :   // to the ValueExprMap.
    5072        5825 :   eraseValueFromMap(PN);
    5073             : 
    5074        5825 :   return nullptr;
    5075             : }
    5076             : 
    5077             : // Checks if the SCEV S is available at BB.  S is considered available at BB
    5078             : // if S can be materialized at BB without introducing a fault.
    5079        8110 : static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
    5080             :                                BasicBlock *BB) {
    5081             :   struct CheckAvailable {
    5082             :     bool TraversalDone = false;
    5083             :     bool Available = true;
    5084             : 
    5085             :     const Loop *L = nullptr;  // The loop BB is in (can be nullptr)
    5086             :     BasicBlock *BB = nullptr;
    5087             :     DominatorTree &DT;
    5088             : 
    5089             :     CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
    5090        8110 :       : L(L), BB(BB), DT(DT) {}
    5091             : 
    5092             :     bool setUnavailable() {
    5093        2867 :       TraversalDone = true;
    5094        2867 :       Available = false;
    5095             :       return false;
    5096             :     }
    5097             : 
    5098       14628 :     bool follow(const SCEV *S) {
    5099       29256 :       switch (S->getSCEVType()) {
    5100             :       case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
    5101             :       case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
    5102             :         // These expressions are available if their operand(s) is/are.
    5103             :         return true;
    5104             : 
    5105             :       case scAddRecExpr: {
    5106             :         // We allow add recurrences that are on the loop BB is in, or some
    5107             :         // outer loop.  This guarantees availability because the value of the
    5108             :         // add recurrence at BB is simply the "current" value of the induction
    5109             :         // variable.  We can relax this in the future; for instance an add
    5110             :         // recurrence on a sibling dominating loop is also available at BB.
    5111         380 :         const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
    5112         409 :         if (L && (ARLoop == L || ARLoop->contains(L)))
    5113             :           return true;
    5114             : 
    5115         227 :         return setUnavailable();
    5116             :       }
    5117             : 
    5118             :       case scUnknown: {
    5119             :         // For SCEVUnknown, we check for simple dominance.
    5120             :         const auto *SU = cast<SCEVUnknown>(S);
    5121             :         Value *V = SU->getValue();
    5122             : 
    5123        6010 :         if (isa<Argument>(V))
    5124             :           return false;
    5125             : 
    5126        5641 :         if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
    5127             :           return false;
    5128             : 
    5129        1727 :         return setUnavailable();
    5130             :       }
    5131             : 
    5132         913 :       case scUDivExpr:
    5133             :       case scCouldNotCompute:
    5134             :         // We do not try to smart about these at all.
    5135         913 :         return setUnavailable();
    5136             :       }
    5137           0 :       llvm_unreachable("switch should be fully covered!");
    5138             :     }
    5139             : 
    5140             :     bool isDone() { return TraversalDone; }
    5141             :   };
    5142             : 
    5143             :   CheckAvailable CA(L, BB, DT);
    5144        8110 :   SCEVTraversal<CheckAvailable> ST(CA);
    5145             : 
    5146        8110 :   ST.visitAll(S);
    5147       16220 :   return CA.Available;
    5148             : }
    5149             : 
    5150             : // Try to match a control flow sequence that branches out at BI and merges back
    5151             : // at Merge into a "C ? LHS : RHS" select pattern.  Return true on a successful
    5152             : // match.
    5153        4776 : static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
    5154             :                           Value *&C, Value *&LHS, Value *&RHS) {
    5155        4776 :   C = BI->getCondition();
    5156             : 
    5157        4776 :   BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
    5158             :   BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
    5159             : 
    5160        4776 :   if (!LeftEdge.isSingleEdge())
    5161             :     return false;
    5162             : 
    5163             :   assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
    5164             : 
    5165        4776 :   Use &LeftUse = Merge->getOperandUse(0);
    5166             :   Use &RightUse = Merge->getOperandUse(1);
    5167             : 
    5168        4776 :   if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
    5169        3412 :     LHS = LeftUse;
    5170        3412 :     RHS = RightUse;
    5171        3412 :     return true;
    5172             :   }
    5173             : 
    5174        1364 :   if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
    5175        1271 :     LHS = RightUse;
    5176        1271 :     RHS = LeftUse;
    5177        1271 :     return true;
    5178             :   }
    5179             : 
    5180             :   return false;
    5181             : }
    5182             : 
    5183       12629 : const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
    5184             :   auto IsReachable =
    5185       21474 :       [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
    5186       23366 :   if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
    5187       10736 :     const Loop *L = LI.getLoopFor(PN->getParent());
    5188             : 
    5189             :     // We don't want to break LCSSA, even in a SCEV expression tree.
    5190       34936 :     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    5191       36068 :       if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
    5192        7752 :         return nullptr;
    5193             : 
    5194             :     // Try to match
    5195             :     //
    5196             :     //  br %cond, label %left, label %right
    5197             :     // left:
    5198             :     //  br label %merge
    5199             :     // right:
    5200             :     //  br label %merge
    5201             :     // merge:
    5202             :     //  V = phi [ %x, %left ], [ %y, %right ]
    5203             :     //
    5204             :     // as "select %cond, %x, %y"
    5205             : 
    5206        9604 :     BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
    5207             :     assert(IDom && "At least the entry block should dominate PN");
    5208             : 
    5209             :     auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
    5210        4802 :     Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
    5211             : 
    5212        9552 :     if (BI && BI->isConditional() &&
    5213        9459 :         BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
    5214       12912 :         IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
    5215        3427 :         IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
    5216        1818 :       return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
    5217             :   }
    5218             : 
    5219             :   return nullptr;
    5220             : }
    5221             : 
    5222       55737 : const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
    5223       55737 :   if (const SCEV *S = createAddRecFromPHI(PN))
    5224             :     return S;
    5225             : 
    5226       12629 :   if (const SCEV *S = createNodeFromSelectLikePHI(PN))
    5227             :     return S;
    5228             : 
    5229             :   // If the PHI has a single incoming value, follow that value, unless the
    5230             :   // PHI's incoming blocks are in a different loop, in which case doing so
    5231             :   // risks breaking LCSSA form. Instcombine would normally zap these, but
    5232             :   // it doesn't have DominatorTree information, so it may miss cases.
    5233       32433 :   if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
    5234         830 :     if (LI.replacementPreservesLCSSAForm(PN, V))
    5235         149 :       return getSCEV(V);
    5236             : 
    5237             :   // If it's not a loop phi, we can't handle it yet.
    5238       10662 :   return getUnknown(PN);
    5239             : }
    5240             : 
    5241       16329 : const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
    5242             :                                                       Value *Cond,
    5243             :                                                       Value *TrueVal,
    5244             :                                                       Value *FalseVal) {
    5245             :   // Handle "constant" branch or select. This can occur for instance when a
    5246             :   // loop pass transforms an inner loop and moves on to process the outer loop.
    5247             :   if (auto *CI = dyn_cast<ConstantInt>(Cond))
    5248          89 :     return getSCEV(CI->isOne() ? TrueVal : FalseVal);
    5249             : 
    5250             :   // Try to match some simple smax or umax patterns.
    5251             :   auto *ICI = dyn_cast<ICmpInst>(Cond);
    5252             :   if (!ICI)
    5253         682 :     return getUnknown(I);
    5254             : 
    5255             :   Value *LHS = ICI->getOperand(0);
    5256             :   Value *RHS = ICI->getOperand(1);
    5257             : 
    5258       15558 :   switch (ICI->getPredicate()) {
    5259             :   case ICmpInst::ICMP_SLT:
    5260             :   case ICmpInst::ICMP_SLE:
    5261             :     std::swap(LHS, RHS);
    5262             :     LLVM_FALLTHROUGH;
    5263         926 :   case ICmpInst::ICMP_SGT:
    5264             :   case ICmpInst::ICMP_SGE:
    5265             :     // a >s b ? a+x : b+x  ->  smax(a, b)+x
    5266             :     // a >s b ? b+x : a+x  ->  smin(a, b)+x
    5267         926 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
    5268         904 :       const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
    5269         904 :       const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
    5270         904 :       const SCEV *LA = getSCEV(TrueVal);
    5271         904 :       const SCEV *RA = getSCEV(FalseVal);
    5272         904 :       const SCEV *LDiff = getMinusSCEV(LA, LS);
    5273         904 :       const SCEV *RDiff = getMinusSCEV(RA, RS);
    5274         904 :       if (LDiff == RDiff)
    5275         410 :         return getAddExpr(getSMaxExpr(LS, RS), LDiff);
    5276         494 :       LDiff = getMinusSCEV(LA, RS);
    5277         494 :       RDiff = getMinusSCEV(RA, LS);
    5278         494 :       if (LDiff == RDiff)
    5279         102 :         return getAddExpr(getSMinExpr(LS, RS), LDiff);
    5280             :     }
    5281             :     break;
    5282             :   case ICmpInst::ICMP_ULT:
    5283             :   case ICmpInst::ICMP_ULE:
    5284             :     std::swap(LHS, RHS);
    5285             :     LLVM_FALLTHROUGH;
    5286        3278 :   case ICmpInst::ICMP_UGT:
    5287             :   case ICmpInst::ICMP_UGE:
    5288             :     // a >u b ? a+x : b+x  ->  umax(a, b)+x
    5289             :     // a >u b ? b+x : a+x  ->  umin(a, b)+x
    5290        3278 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
    5291        3253 :       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
    5292        3253 :       const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
    5293        3253 :       const SCEV *LA = getSCEV(TrueVal);
    5294        3253 :       const SCEV *RA = getSCEV(FalseVal);
    5295        3253 :       const SCEV *LDiff = getMinusSCEV(LA, LS);
    5296        3253 :       const SCEV *RDiff = getMinusSCEV(RA, RS);
    5297        3253 :       if (LDiff == RDiff)
    5298         201 :         return getAddExpr(getUMaxExpr(LS, RS), LDiff);
    5299        3052 :       LDiff = getMinusSCEV(LA, RS);
    5300        3052 :       RDiff = getMinusSCEV(RA, LS);
    5301        3052 :       if (LDiff == RDiff)
    5302         199 :         return getAddExpr(getUMinExpr(LS, RS), LDiff);
    5303             :     }
    5304             :     break;
    5305        7128 :   case ICmpInst::ICMP_NE:
    5306             :     // n != 0 ? n+x : 1+x  ->  umax(n, 1)+x
    5307       14119 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
    5308        8461 :         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
    5309        1241 :       const SCEV *One = getOne(I->getType());
    5310        1241 :       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
    5311        1241 :       const SCEV *LA = getSCEV(TrueVal);
    5312        1241 :       const SCEV *RA = getSCEV(FalseVal);
    5313        1241 :       const SCEV *LDiff = getMinusSCEV(LA, LS);
    5314        1241 :       const SCEV *RDiff = getMinusSCEV(RA, One);
    5315        1241 :       if (LDiff == RDiff)
    5316           1 :         return getAddExpr(getUMaxExpr(One, LS), LDiff);
    5317             :     }
    5318             :     break;
    5319        4226 :   case ICmpInst::ICMP_EQ:
    5320             :     // n == 0 ? 1+x : n+x  ->  umax(n, 1)+x
    5321        8311 :     if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
    5322        7074 :         isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
    5323        1901 :       const SCEV *One = getOne(I->getType());
    5324        1901 :       const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
    5325        1901 :       const SCEV *LA = getSCEV(TrueVal);
    5326        1901 :       const SCEV *RA = getSCEV(FalseVal);
    5327        1901 :       const SCEV *LDiff = getMinusSCEV(LA, One);
    5328        1901 :       const SCEV *RDiff = getMinusSCEV(RA, LS);
    5329        1901 :       if (LDiff == RDiff)
    5330          50 :         return getAddExpr(getUMaxExpr(One, LS), LDiff);
    5331             :     }
    5332             :     break;
    5333             :   default:
    5334             :     break;
    5335             :   }
    5336             : 
    5337       14595 :   return getUnknown(I);
    5338             : }
    5339             : 
    5340             : /// Expand GEP instructions into add and multiply operations. This allows them
    5341             : /// to be analyzed by regular SCEV code.
    5342      171025 : const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
    5343             :   // Don't attempt to analyze GEPs over unsized objects.
    5344      171025 :   if (!GEP->getSourceElementType()->isSized())
    5345           0 :     return getUnknown(GEP);
    5346             : 
    5347             :   SmallVector<const SCEV *, 4> IndexExprs;
    5348      799227 :   for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
    5349      314101 :     IndexExprs.push_back(getSCEV(*Index));
    5350      171025 :   return getGEPExpr(GEP, IndexExprs);
    5351             : }
    5352             : 
    5353      529068 : uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
    5354             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
    5355       97176 :     return C->getAPInt().countTrailingZeros();
    5356             : 
    5357             :   if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
    5358        5482 :     return std::min(GetMinTrailingZeros(T->getOperand()),
    5359        8223 :                     (uint32_t)getTypeSizeInBits(T->getType()));
    5360             : 
    5361             :   if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
    5362       15862 :     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
    5363       15862 :     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
    5364           0 :                ? getTypeSizeInBits(E->getType())
    5365       15862 :                : OpRes;
    5366             :   }
    5367             : 
    5368             :   if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
    5369        8113 :     uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
    5370        8113 :     return OpRes == getTypeSizeInBits(E->getOperand()->getType())
    5371           0 :                ? getTypeSizeInBits(E->getType())
    5372        8113 :                : OpRes;
    5373             :   }
    5374             : 
    5375             :   if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
    5376             :     // The result is the min of all operands results.
    5377      173924 :     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
    5378      142914 :     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
    5379      167856 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
    5380             :     return MinOpRes;
    5381             :   }
    5382             : 
    5383             :   if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
    5384             :     // The result is the sum of all operands results.
    5385      119530 :     uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
    5386       59765 :     uint32_t BitWidth = getTypeSizeInBits(M->getType());
    5387      127025 :     for (unsigned i = 1, e = M->getNumOperands();
    5388      127025 :          SumOpRes != BitWidth && i != e; ++i)
    5389       67260 :       SumOpRes =
    5390      201780 :           std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
    5391             :     return SumOpRes;
    5392             :   }
    5393             : 
    5394             :   if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
    5395             :     // The result is the min of all operands results.
    5396      228296 :     uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
    5397      183953 :     for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
    5398      209415 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
    5399             :     return MinOpRes;
    5400             :   }
    5401             : 
    5402             :   if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
    5403             :     // The result is the min of all operands results.
    5404        4366 :     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
    5405        3499 :     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
    5406        3948 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
    5407             :     return MinOpRes;
    5408             :   }
    5409             : 
    5410             :   if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
    5411             :     // The result is the min of all operands results.
    5412        1404 :     uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
    5413         767 :     for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
    5414         195 :       MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
    5415             :     return MinOpRes;
    5416             :   }
    5417             : 
    5418      134300 :   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
    5419             :     // For a SCEVUnknown, ask ValueTracking.
    5420      402900 :     KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
    5421             :     return Known.countMinTrailingZeros();
    5422             :   }
    5423             : 
    5424             :   // SCEVUDivExpr
    5425             :   return 0;
    5426             : }
    5427             : 
    5428     1275397 : uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
    5429     1275397 :   auto I = MinTrailingZerosCache.find(S);
    5430     1275397 :   if (I != MinTrailingZerosCache.end())
    5431      746329 :     return I->second;
    5432             : 
    5433      529068 :   uint32_t Result = GetMinTrailingZerosImpl(S);
    5434      529068 :   auto InsertPair = MinTrailingZerosCache.insert({S, Result});
    5435             :   assert(InsertPair.second && "Should insert a new key");
    5436      529068 :   return InsertPair.first->second;
    5437             : }
    5438             : 
    5439             : /// Helper method to assign a range to V from metadata present in the IR.
    5440      262676 : static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
    5441             :   if (Instruction *I = dyn_cast<Instruction>(V))
    5442       70409 :     if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
    5443       24770 :       return getConstantRangeFromMetadata(*MD);
    5444             : 
    5445             :   return None;
    5446             : }
    5447             : 
    5448             : /// Determine the range for a particular SCEV.  If SignHint is
    5449             : /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
    5450             : /// with a "cleaner" unsigned (resp. signed) representation.
    5451             : const ConstantRange &
    5452     7781789 : ScalarEvolution::getRangeRef(const SCEV *S,
    5453             :                              ScalarEvolution::RangeSignHint SignHint) {
    5454     7781789 :   DenseMap<const SCEV *, ConstantRange> &Cache =
    5455             :       SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
    5456             :                                                        : SignedRanges;
    5457             : 
    5458             :   // See if we've computed this range already.
    5459     7781789 :   DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
    5460     7781789 :   if (I != Cache.end())
    5461     6546043 :     return I->second;
    5462             : 
    5463             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
    5464      898734 :     return setRange(C, SignHint, ConstantRange(C->getAPInt()));
    5465             : 
    5466      786379 :   unsigned BitWidth = getTypeSizeInBits(S->getType());
    5467     1572758 :   ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
    5468             : 
    5469             :   // If the value has known zeros, the maximum value will have those known zeros
    5470             :   // as well.
    5471      786379 :   uint32_t TZ = GetMinTrailingZeros(S);
    5472      786379 :   if (TZ != 0) {
    5473      257292 :     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
    5474      122551 :       ConservativeResult =
    5475      367653 :           ConstantRange(APInt::getMinValue(BitWidth),
    5476      612755 :                         APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
    5477             :     else
    5478      134741 :       ConservativeResult = ConstantRange(
    5479      269482 :           APInt::getSignedMinValue(BitWidth),
    5480      673705 :           APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
    5481             :   }
    5482             : 
    5483             :   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
    5484      422460 :     ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
    5485      854407 :     for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
    5486     1427174 :       X = X.add(getRangeRef(Add->getOperand(i), SignHint));
    5487      140820 :     return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
    5488             :   }
    5489             : 
    5490             :   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
    5491      326604 :     ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
    5492      235257 :     for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
    5493      252778 :       X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
    5494      108868 :     return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
    5495             :   }
    5496             : 
    5497             :   if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
    5498       13092 :     ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
    5499        9560 :     for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
    5500       10392 :       X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
    5501        4364 :     return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
    5502             :   }
    5503             : 
    5504             :   if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
    5505        4212 :     ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
    5506        2864 :     for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
    5507        2920 :       X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
    5508        1404 :     return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
    5509             :   }
    5510             : 
    5511             :   if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
    5512       21538 :     ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
    5513       21538 :     ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
    5514             :     return setRange(UDiv, SignHint,
    5515       10769 :                     ConservativeResult.intersectWith(X.udiv(Y)));
    5516             :   }
    5517             : 
    5518             :   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
    5519       60048 :     ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
    5520             :     return setRange(ZExt, SignHint,
    5521       30024 :                     ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
    5522             :   }
    5523             : 
    5524             :   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
    5525       31634 :     ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
    5526             :     return setRange(SExt, SignHint,
    5527       15817 :                     ConservativeResult.intersectWith(X.signExtend(BitWidth)));
    5528             :   }
    5529             : 
    5530             :   if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
    5531        9198 :     ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
    5532             :     return setRange(Trunc, SignHint,
    5533        4599 :                     ConservativeResult.intersectWith(X.truncate(BitWidth)));
    5534             :   }
    5535             : 
    5536             :   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
    5537             :     // If there's no unsigned wrap, the value will never be less than its
    5538             :     // initial value.
    5539      207038 :     if (AddRec->hasNoUnsignedWrap())
    5540       71518 :       if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
    5541      125204 :         if (!C->getValue()->isZero())
    5542       18534 :           ConservativeResult = ConservativeResult.intersectWith(
    5543       74136 :               ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
    5544             : 
    5545             :     // If there's no signed wrap, and all the operands have the same sign or
    5546             :     // zero, the value won't ever change sign.
    5547      207038 :     if (AddRec->hasNoSignedWrap()) {
    5548             :       bool AllNonNeg = true;
    5549             :       bool AllNonPos = true;
    5550      202101 :       for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
    5551      269468 :         if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
    5552      269468 :         if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
    5553             :       }
    5554       67367 :       if (AllNonNeg)
    5555       54887 :         ConservativeResult = ConservativeResult.intersectWith(
    5556      164661 :           ConstantRange(APInt(BitWidth, 0),
    5557      109774 :                         APInt::getSignedMinValue(BitWidth)));
    5558       12480 :       else if (AllNonPos)
    5559         264 :         ConservativeResult = ConservativeResult.intersectWith(
    5560         792 :           ConstantRange(APInt::getSignedMinValue(BitWidth),
    5561         264 :                         APInt(BitWidth, 1)));
    5562             :     }
    5563             : 
    5564             :     // TODO: non-affine addrec
    5565      207038 :     if (AddRec->isAffine()) {
    5566      205484 :       const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
    5567      354740 :       if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
    5568      149256 :           getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
    5569             :         auto RangeFromAffine = getRangeForAffineAR(
    5570             :             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
    5571      437931 :             BitWidth);
    5572      145977 :         if (!RangeFromAffine.isFullSet())
    5573      104809 :           ConservativeResult =
    5574      209618 :               ConservativeResult.intersectWith(RangeFromAffine);
    5575             : 
    5576             :         auto RangeFromFactoring = getRangeViaFactoring(
    5577             :             AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
    5578      437931 :             BitWidth);
    5579      145977 :         if (!RangeFromFactoring.isFullSet())
    5580          62 :           ConservativeResult =
    5581         124 :               ConservativeResult.intersectWith(RangeFromFactoring);
    5582             :       }
    5583             :     }
    5584             : 
    5585      207038 :     return setRange(AddRec, SignHint, std::move(ConservativeResult));
    5586             :   }
    5587             : 
    5588      262676 :   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
    5589             :     // Check if the IR explicitly contains !range metadata.
    5590      262676 :     Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
    5591      262676 :     if (MDRange.hasValue())
    5592       12385 :       ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
    5593             : 
    5594             :     // Split here to avoid paying the compile-time cost of calling both
    5595             :     // computeKnownBits and ComputeNumSignBits.  This restriction can be lifted
    5596             :     // if needed.
    5597      262676 :     const DataLayout &DL = getDataLayout();
    5598      262676 :     if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
    5599             :       // For a SCEVUnknown, ask ValueTracking.
    5600      374658 :       KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
    5601      374658 :       if (Known.One != ~Known.Zero + 1)
    5602       62862 :         ConservativeResult =
    5603      188586 :             ConservativeResult.intersectWith(ConstantRange(Known.One,
    5604      188586 :                                                            ~Known.Zero + 1));
    5605             :     } else {
    5606             :       assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
    5607             :              "generalize as needed!");
    5608      275580 :       unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
    5609      137790 :       if (NS > 1)
    5610       21028 :         ConservativeResult = ConservativeResult.intersectWith(
    5611       84112 :             ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
    5612       84112 :                           APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
    5613             :     }
    5614             : 
    5615             :     // A range of Phi is a subset of union of all ranges of its input.
    5616             :     if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
    5617             :       // Make sure that we do not run over cycled Phis.
    5618       26735 :       if (PendingPhiRanges.insert(Phi).second) {
    5619       34768 :         ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
    5620       46820 :         for (auto &Op : Phi->operands()) {
    5621       27838 :           auto OpRange = getRangeRef(getSCEV(Op), SignHint);
    5622       21812 :           RangeFromOps = RangeFromOps.unionWith(OpRange);
    5623             :           // No point to continue if we already have a full set.
    5624       21812 :           if (RangeFromOps.isFullSet())
    5625             :             break;
    5626             :         }
    5627       17384 :         ConservativeResult = ConservativeResult.intersectWith(RangeFromOps);
    5628             :         bool Erased = PendingPhiRanges.erase(Phi);
    5629             :         assert(Erased && "Failed to erase Phi properly?");
    5630             :         (void) Erased;
    5631             :       }
    5632             :     }
    5633             : 
    5634      262676 :     return setRange(U, SignHint, std::move(ConservativeResult));
    5635             :   }
    5636             : 
    5637           0 :   return setRange(S, SignHint, std::move(ConservativeResult));
    5638             : }
    5639             : 
    5640             : // Given a StartRange, Step and MaxBECount for an expression compute a range of
    5641             : // values that the expression can take. Initially, the expression has a value
    5642             : // from StartRange and then is changed by Step up to MaxBECount times. Signed
    5643             : // argument defines if we treat Step as signed or unsigned.
    5644      438303 : static ConstantRange getRangeForAffineARHelper(APInt Step,
    5645             :                                                const ConstantRange &StartRange,
    5646             :                                                const APInt &MaxBECount,
    5647             :                                                unsigned BitWidth, bool Signed) {
    5648             :   // If either Step or MaxBECount is 0, then the expression won't change, and we
    5649             :   // just need to return the initial range.
    5650      438303 :   if (Step == 0 || MaxBECount == 0)
    5651       11245 :     return StartRange;
    5652             : 
    5653             :   // If we don't know anything about the initial value (i.e. StartRange is
    5654             :   // FullRange), then we don't know anything about the final range either.
    5655             :   // Return FullRange.
    5656      427058 :   if (StartRange.isFullSet())
    5657       67103 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5658             : 
    5659             :   // If Step is signed and negative, then we use its absolute value, but we also
    5660             :   // note that we're moving in the opposite direction.
    5661      600206 :   bool Descending = Signed && Step.isNegative();
    5662             : 
    5663      359955 :   if (Signed)
    5664             :     // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
    5665             :     // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
    5666             :     // This equations hold true due to the well-defined wrap-around behavior of
    5667             :     // APInt.
    5668      480502 :     Step = Step.abs();
    5669             : 
    5670             :   // Check if Offset is more than full span of BitWidth. If it is, the
    5671             :   // expression is guaranteed to overflow.
    5672     1079865 :   if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
    5673       60130 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5674             : 
    5675             :   // Offset is by how much the expression can change. Checks above guarantee no
    5676             :   // overflow here.
    5677      299825 :   APInt Offset = Step * MaxBECount;
    5678             : 
    5679             :   // Minimum value of the final range will match the minimal value of StartRange
    5680             :   // if the expression is increasing and will be decreased by Offset otherwise.
    5681             :   // Maximum value of the final range will match the maximal value of StartRange
    5682             :   // if the expression is decreasing and will be increased by Offset otherwise.
    5683             :   APInt StartLower = StartRange.getLower();
    5684      299825 :   APInt StartUpper = StartRange.getUpper() - 1;
    5685             :   APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
    5686      299825 :                                    : (StartUpper + std::move(Offset));
    5687             : 
    5688             :   // It's possible that the new minimum/maximum value will fall into the initial
    5689             :   // range (due to wrap around). This means that the expression can take any
    5690             :   // value in this bitwidth, and we have to return full range.
    5691      299825 :   if (StartRange.contains(MovedBoundary))
    5692       10207 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5693             : 
    5694             :   APInt NewLower =
    5695      289618 :       Descending ? std::move(MovedBoundary) : std::move(StartLower);
    5696             :   APInt NewUpper =
    5697      289618 :       Descending ? std::move(StartUpper) : std::move(MovedBoundary);
    5698      289618 :   NewUpper += 1;
    5699             : 
    5700             :   // If we end up with full range, return a proper full range.
    5701      289618 :   if (NewLower == NewUpper)
    5702       12378 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5703             : 
    5704             :   // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
    5705      831720 :   return ConstantRange(std::move(NewLower), std::move(NewUpper));
    5706             : }
    5707             : 
    5708      146101 : ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
    5709             :                                                    const SCEV *Step,
    5710             :                                                    const SCEV *MaxBECount,
    5711             :                                                    unsigned BitWidth) {
    5712             :   assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
    5713             :          getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
    5714             :          "Precondition!");
    5715             : 
    5716      146101 :   MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
    5717             :   APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
    5718             : 
    5719             :   // First, consider step signed.
    5720      146101 :   ConstantRange StartSRange = getSignedRange(Start);
    5721      146101 :   ConstantRange StepSRange = getSignedRange(Step);
    5722             : 
    5723             :   // If Step can be both positive and negative, we need to find ranges for the
    5724             :   // maximum absolute step values in both directions and union them.
    5725             :   ConstantRange SR =
    5726      292202 :       getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
    5727      292202 :                                 MaxBECountValue, BitWidth, /* Signed = */ true);
    5728      292202 :   SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
    5729             :                                               StartSRange, MaxBECountValue,
    5730             :                                               BitWidth, /* Signed = */ true));
    5731             : 
    5732             :   // Next, consider step unsigned.
    5733             :   ConstantRange UR = getRangeForAffineARHelper(
    5734      146101 :       getUnsignedRangeMax(Step), getUnsignedRange(Start),
    5735      292202 :       MaxBECountValue, BitWidth, /* Signed = */ false);
    5736             : 
    5737             :   // Finally, intersect signed and unsigned ranges.
    5738      292202 :   return SR.intersectWith(UR);
    5739             : }
    5740             : 
    5741      145977 : ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
    5742             :                                                     const SCEV *Step,
    5743             :                                                     const SCEV *MaxBECount,
    5744             :                                                     unsigned BitWidth) {
    5745             :   //    RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
    5746             :   // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
    5747             : 
    5748      292088 :   struct SelectPattern {
    5749             :     Value *Condition = nullptr;
    5750             :     APInt TrueValue;
    5751             :     APInt FalseValue;
    5752             : 
    5753      146044 :     explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
    5754      292088 :                            const SCEV *S) {
    5755             :       Optional<unsigned> CastOp;
    5756             :       APInt Offset(BitWidth, 0);
    5757             : 
    5758             :       assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
    5759             :              "Should be!");
    5760             : 
    5761             :       // Peel off a constant offset:
    5762             :       if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
    5763             :         // In the future we could consider being smarter here and handle
    5764             :         // {Start+Step,+,Step} too.
    5765       29941 :         if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
    5766             :           return;
    5767             : 
    5768       12564 :         Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
    5769       12564 :         S = SA->getOperand(1);
    5770             :       }
    5771             : 
    5772             :       // Peel off a cast operation
    5773             :       if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
    5774             :         CastOp = SCast->getSCEVType();
    5775        2026 :         S = SCast->getOperand();
    5776             :       }
    5777             : 
    5778             :       using namespace llvm::PatternMatch;
    5779             : 
    5780             :       auto *SU = dyn_cast<SCEVUnknown>(S);
    5781             :       const APInt *TrueVal, *FalseVal;
    5782       41188 :       if (!SU ||
    5783      163541 :           !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
    5784             :                                           m_APInt(FalseVal)))) {
    5785      142818 :         Condition = nullptr;
    5786             :         return;
    5787             :       }
    5788             : 
    5789         129 :       TrueValue = *TrueVal;
    5790         129 :       FalseValue = *FalseVal;
    5791             : 
    5792             :       // Re-apply the cast we peeled off earlier
    5793         129 :       if (CastOp.hasValue())
    5794          32 :         switch (*CastOp) {
    5795           0 :         default:
    5796           0 :           llvm_unreachable("Unknown SCEV cast type!");
    5797             : 
    5798          16 :         case scTruncate:
    5799          32 :           TrueValue = TrueValue.trunc(BitWidth);
    5800          32 :           FalseValue = FalseValue.trunc(BitWidth);
    5801             :           break;
    5802           4 :         case scZeroExtend:
    5803           8 :           TrueValue = TrueValue.zext(BitWidth);
    5804           8 :           FalseValue = FalseValue.zext(BitWidth);
    5805             :           break;
    5806          12 :         case scSignExtend:
    5807          24 :           TrueValue = TrueValue.sext(BitWidth);
    5808          24 :           FalseValue = FalseValue.sext(BitWidth);
    5809             :           break;
    5810             :         }
    5811             : 
    5812             :       // Re-apply the constant offset we peeled off earlier
    5813         129 :       TrueValue += Offset;
    5814         129 :       FalseValue += Offset;
    5815             :     }
    5816             : 
    5817             :     bool isRecognized() { return Condition != nullptr; }
    5818             :   };
    5819             : 
    5820      291954 :   SelectPattern StartPattern(*this, BitWidth, Start);
    5821      145977 :   if (!StartPattern.isRecognized())
    5822      145910 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5823             : 
    5824         134 :   SelectPattern StepPattern(*this, BitWidth, Step);
    5825          67 :   if (!StepPattern.isRecognized())
    5826           5 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5827             : 
    5828          62 :   if (StartPattern.Condition != StepPattern.Condition) {
    5829             :     // We don't handle this case today; but we could, by considering four
    5830             :     // possibilities below instead of two. I'm not sure if there are cases where
    5831             :     // that will help over what getRange already does, though.
    5832           0 :     return ConstantRange(BitWidth, /* isFullSet = */ true);
    5833             :   }
    5834             : 
    5835             :   // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
    5836             :   // construct arbitrary general SCEV expressions here.  This function is called
    5837             :   // from deep in the call stack, and calling getSCEV (on a sext instruction,
    5838             :   // say) can end up caching a suboptimal value.
    5839             : 
    5840             :   // FIXME: without the explicit `this` receiver below, MSVC errors out with
    5841             :   // C2352 and C2512 (otherwise it isn't needed).
    5842             : 
    5843          62 :   const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
    5844          62 :   const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
    5845          62 :   const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
    5846          62 :   const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
    5847             : 
    5848             :   ConstantRange TrueRange =
    5849         124 :       this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
    5850             :   ConstantRange FalseRange =
    5851         124 :       this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
    5852             : 
    5853          62 :   return TrueRange.unionWith(FalseRange);
    5854             : }
    5855             : 
    5856       79109 : SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
    5857       79109 :   if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
    5858             :   const BinaryOperator *BinOp = cast<BinaryOperator>(V);
    5859             : 
    5860             :   // Return early if there are no flags to propagate to the SCEV.
    5861             :   SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    5862       79103 :   if (BinOp->hasNoUnsignedWrap())
    5863             :     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
    5864       79103 :   if (BinOp->hasNoSignedWrap())
    5865             :     Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
    5866       79103 :   if (Flags == SCEV::FlagAnyWrap)
    5867             :     return SCEV::FlagAnyWrap;
    5868             : 
    5869       41823 :   return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
    5870             : }
    5871             : 
    5872       84324 : bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
    5873             :   // Here we check that I is in the header of the innermost loop containing I,
    5874             :   // since we only deal with instructions in the loop header. The actual loop we
    5875             :   // need to check later will come from an add recurrence, but getting that
    5876             :   // requires computing the SCEV of the operands, which can be expensive. This
    5877             :   // check we can do cheaply to rule out some cases early.
    5878       84324 :   Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
    5879      164658 :   if (InnermostContainingLoop == nullptr ||
    5880       82329 :       InnermostContainingLoop->getHeader() != I->getParent())
    5881             :     return false;
    5882             : 
    5883             :   // Only proceed if we can prove that I does not yield poison.
    5884       46472 :   if (!programUndefinedIfFullPoison(I))
    5885             :     return false;
    5886             : 
    5887             :   // At this point we know that if I is executed, then it does not wrap
    5888             :   // according to at least one of NSW or NUW. If I is not executed, then we do
    5889             :   // not know if the calculation that I represents would wrap. Multiple
    5890             :   // instructions can map to the same SCEV. If we apply NSW or NUW from I to
    5891             :   // the SCEV, we must guarantee no wrapping for that SCEV also when it is
    5892             :   // derived from other instructions that map to the same SCEV. We cannot make
    5893             :   // that guarantee for cases where I is not executed. So we need to find the
    5894             :   // loop that I is considered in relation to and prove that I is executed for
    5895             :   // every iteration of that loop. That implies that the value that I
    5896             :   // calculates does not wrap anywhere in the loop, so then we can apply the
    5897             :   // flags to the SCEV.
    5898             :   //
    5899             :   // We check isLoopInvariant to disambiguate in case we are adding recurrences
    5900             :   // from different loops, so that we know which loop to prove that I is
    5901             :   // executed in.
    5902       23585 :   for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
    5903             :     // I could be an extractvalue from a call to an overflow intrinsic.
    5904             :     // TODO: We can do better here in some cases.
    5905       24934 :     if (!isSCEVable(I->getOperand(OpIndex)->getType()))
    5906             :       return false;
    5907       12466 :     const SCEV *Op = getSCEV(I->getOperand(OpIndex));
    5908             :     if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
    5909             :       bool AllOtherOpsLoopInvariant = true;
    5910       27397 :       for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
    5911             :            ++OtherOpIndex) {
    5912       11156 :         if (OtherOpIndex != OpIndex) {
    5913        5613 :           const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
    5914        5613 :           if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
    5915             :             AllOtherOpsLoopInvariant = false;
    5916             :             break;
    5917             :           }
    5918             :         }
    5919             :       }
    5920       10962 :       if (AllOtherOpsLoopInvariant &&
    5921        5349 :           isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
    5922             :         return true;
    5923             :     }
    5924             :   }
    5925             :   return false;
    5926             : }
    5927             : 
    5928       42501 : bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
    5929             :   // If we know that \c I can never be poison period, then that's enough.
    5930       42501 :   if (isSCEVExprNeverPoison(I))
    5931             :     return true;
    5932             : 
    5933             :   // For an add recurrence specifically, we assume that infinite loops without
    5934             :   // side effects are undefined behavior, and then reason as follows:
    5935             :   //
    5936             :   // If the add recurrence is poison in any iteration, it is poison on all
    5937             :   // future iterations (since incrementing poison yields poison). If the result
    5938             :   // of the add recurrence is fed into the loop latch condition and the loop
    5939             :   // does not contain any throws or exiting blocks other than the latch, we now
    5940             :   // have the ability to "choose" whether the backedge is taken or not (by
    5941             :   // choosing a sufficiently evil value for the poison feeding into the branch)
    5942             :   // for every iteration including and after the one in which \p I first became
    5943             :   // poison.  There are two possibilities (let's call the iteration in which \p
    5944             :   // I first became poison as K):
    5945             :   //
    5946             :   //  1. In the set of iterations including and after K, the loop body executes
    5947             :   //     no side effects.  In this case executing the backege an infinte number
    5948             :   //     of times will yield undefined behavior.
    5949             :   //
    5950             :   //  2. In the set of iterations including and after K, the loop body executes
    5951             :   //     at least one side effect.  In this case, that specific instance of side
    5952             :   //     effect is control dependent on poison, which also yields undefined
    5953             :   //     behavior.
    5954             : 
    5955       41419 :   auto *ExitingBB = L->getExitingBlock();
    5956       41419 :   auto *LatchBB = L->getLoopLatch();
    5957       41419 :   if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
    5958             :     return false;
    5959             : 
    5960             :   SmallPtrSet<const Instruction *, 16> Pushed;
    5961             :   SmallVector<const Instruction *, 8> PoisonStack;
    5962             : 
    5963             :   // We start by assuming \c I, the post-inc add recurrence, is poison.  Only
    5964             :   // things that are known to be fully poison under that assumption go on the
    5965             :   // PoisonStack.
    5966       26888 :   Pushed.insert(I);
    5967       26888 :   PoisonStack.push_back(I);
    5968             : 
    5969             :   bool LatchControlDependentOnPoison = false;
    5970       77835 :   while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
    5971             :     const Instruction *Poison = PoisonStack.pop_back_val();
    5972             : 
    5973      107649 :     for (auto *PoisonUser : Poison->users()) {
    5974       76619 :       if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
    5975       24240 :         if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
    5976       24238 :           PoisonStack.push_back(cast<Instruction>(PoisonUser));
    5977             :       } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
    5978             :         assert(BI->isConditional() && "Only possibility!");
    5979       19981 :         if (BI->getParent() == LatchBB) {
    5980             :           LatchControlDependentOnPoison = true;
    5981             :           break;
    5982             :         }
    5983             :       }
    5984             :     }
    5985             :   }
    5986             : 
    5987       46805 :   return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
    5988             : }
    5989             : 
    5990             : ScalarEvolution::LoopProperties
    5991       21290 : ScalarEvolution::getLoopProperties(const Loop *L) {
    5992             :   using LoopProperties = ScalarEvolution::LoopProperties;
    5993             : 
    5994       21290 :   auto Itr = LoopPropertiesCache.find(L);
    5995       21290 :   if (Itr == LoopPropertiesCache.end()) {
    5996      234790 :     auto HasSideEffects = [](Instruction *I) {
    5997             :       if (auto *SI = dyn_cast<StoreInst>(I))
    5998       23609 :         return !SI->isSimple();
    5999             : 
    6000      211181 :       return I->mayHaveSideEffects();
    6001             :     };
    6002             : 
    6003             :     LoopProperties LP = {/* HasNoAbnormalExits */ true,
    6004             :                          /*HasNoSideEffects*/ true};
    6005             : 
    6006       56724 :     for (auto *BB : L->getBlocks())
    6007      252263 :       for (auto &I : *BB) {
    6008      234790 :         if (!isGuaranteedToTransferExecutionToSuccessor(&I))
    6009             :           LP.HasNoAbnormalExits = false;
    6010      234790 :         if (HasSideEffects(&I))
    6011             :           LP.HasNoSideEffects = false;
    6012      234790 :         if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
    6013             :           break; // We're already as pessimistic as we can get.
    6014             :       }
    6015             : 
    6016       10980 :     auto InsertPair = LoopPropertiesCache.insert({L, LP});
    6017             :     assert(InsertPair.second && "We just checked!");
    6018       10980 :     Itr = InsertPair.first;
    6019             :   }
    6020             : 
    6021       21290 :   return Itr->second;
    6022             : }
    6023             : 
    6024      616174 : const SCEV *ScalarEvolution::createSCEV(Value *V) {
    6025      616174 :   if (!isSCEVable(V->getType()))
    6026           0 :     return getUnknown(V);
    6027             : 
    6028             :   if (Instruction *I = dyn_cast<Instruction>(V)) {
    6029             :     // Don't attempt to analyze instructions in blocks that aren't
    6030             :     // reachable. Such instructions don't matter, and they aren't required
    6031             :     // to obey basic rules for definitions dominating uses which this
    6032             :     // analysis depends on.
    6033      325811 :     if (!DT.isReachableFromEntry(I->getParent()))
    6034         322 :       return getUnknown(V);
    6035             :   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
    6036      117652 :     return getConstant(CI);
    6037      172711 :   else if (isa<ConstantPointerNull>(V))
    6038        1526 :     return getZero(V->getType());
    6039             :   else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
    6040           0 :     return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
    6041      171948 :   else if (!isa<ConstantExpr>(V))
    6042       83453 :     return getUnknown(V);
    6043             : 
    6044             :   Operator *U = cast<Operator>(V);
    6045      413984 :   if (auto BO = MatchBinaryOp(U, DT)) {
    6046       80053 :     switch (BO->Opcode) {
    6047             :     case Instruction::Add: {
    6048             :       // The simple thing to do would be to just call getSCEV on both operands
    6049             :       // and call getAddExpr with the result. However if we're looking at a
    6050             :       // bunch of things all added together, this can be quite inefficient,
    6051             :       // because it leads to N-1 getAddExpr calls for N ultimate operands.
    6052             :       // Instead, gather up all the operands and make a single getAddExpr call.
    6053             :       // LLVM IR canonical form means we need only traverse the left operands.
    6054             :       SmallVector<const SCEV *, 4> AddOps;
    6055             :       do {
    6056       66803 :         if (BO->Op) {
    6057       66711 :           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
    6058        4703 :             AddOps.push_back(OpSCEV);
    6059        4703 :             break;
    6060             :           }
    6061             : 
    6062             :           // If a NUW or NSW flag can be applied to the SCEV for this
    6063             :           // addition, then compute the SCEV for this addition by itself
    6064             :           // with a separate call to getAddExpr. We need to do that
    6065             :           // instead of pushing the operands of the addition onto AddOps,
    6066             :           // since the flags are only known to apply to this particular
    6067             :           // addition - they may not apply to other additions that can be
    6068             :           // formed with operands from AddOps.
    6069       62008 :           const SCEV *RHS = getSCEV(BO->RHS);
    6070       62008 :           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
    6071       62008 :           if (Flags != SCEV::FlagAnyWrap) {
    6072        3577 :             const SCEV *LHS = getSCEV(BO->LHS);
    6073        3577 :             if (BO->Opcode == Instruction::Sub)
    6074           2 :               AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
    6075             :             else
    6076        3575 :               AddOps.push_back(getAddExpr(LHS, RHS, Flags));
    6077             :             break;
    6078             :           }
    6079             :         }
    6080             : 
    6081       58523 :         if (BO->Opcode == Instruction::Sub)
    6082         311 :           AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
    6083             :         else
    6084       58212 :           AddOps.push_back(getSCEV(BO->RHS));
    6085             : 
    6086       58523 :         auto NewBO = MatchBinaryOp(BO->LHS, DT);
    6087       58523 :         if (!NewBO || (NewBO->Opcode != Instruction::Add &&
    6088             :                        NewBO->Opcode != Instruction::Sub)) {
    6089       44075 :           AddOps.push_back(getSCEV(BO->LHS));
    6090             :           break;
    6091             :         }
    6092             :         BO = NewBO;
    6093             :       } while (true);
    6094             : 
    6095       52355 :       return getAddExpr(AddOps);
    6096             :     }
    6097             : 
    6098             :     case Instruction::Mul: {
    6099             :       SmallVector<const SCEV *, 4> MulOps;
    6100             :       do {
    6101        8260 :         if (BO->Op) {
    6102        8256 :           if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
    6103         404 :             MulOps.push_back(OpSCEV);
    6104         404 :             break;
    6105             :           }
    6106             : 
    6107        7852 :           SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
    6108        7852 :           if (Flags != SCEV::FlagAnyWrap) {
    6109         131 :             MulOps.push_back(
    6110         262 :                 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
    6111         131 :             break;
    6112             :           }
    6113             :         }
    6114             : 
    6115        7725 :         MulOps.push_back(getSCEV(BO->RHS));
    6116        7725 :         auto NewBO = MatchBinaryOp(BO->LHS, DT);
    6117        7725 :         if (!NewBO || NewBO->Opcode != Instruction::Mul) {
    6118        6923 :           MulOps.push_back(getSCEV(BO->LHS));
    6119             :           break;
    6120             :         }
    6121             :         BO = NewBO;
    6122             :       } while (true);
    6123             : 
    6124        7458 :       return getMulExpr(MulOps);
    6125             :     }
    6126             :     case Instruction::UDiv:
    6127        4241 :       return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
    6128             :     case Instruction::URem:
    6129         491 :       return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
    6130        6961 :     case Instruction::Sub: {
    6131             :       SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
    6132        6961 :       if (BO->Op)
    6133        6928 :         Flags = getNoWrapFlagsFromUB(BO->Op);
    6134        6961 :       return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
    6135             :     }
    6136             :     case Instruction::And:
    6137             :       // For an expression like x&255 that merely masks off the high bits,
    6138             :       // use zext(trunc(x)) as the SCEV expression.
    6139        2414 :       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
    6140        1958 :         if (CI->isZero())
    6141        1899 :           return getSCEV(BO->RHS);
    6142        1956 :         if (CI->isMinusOne())
    6143           0 :           return getSCEV(BO->LHS);
    6144             :         const APInt &A = CI->getValue();
    6145             : 
    6146             :         // Instcombine's ShrinkDemandedConstant may strip bits out of
    6147             :         // constants, obscuring what would otherwise be a low-bits mask.
    6148             :         // Use computeKnownBits to compute what ShrinkDemandedConstant
    6149             :         // knew about to reconstruct a low-bits mask value.
    6150        1956 :         unsigned LZ = A.countLeadingZeros();
    6151        1956 :         unsigned TZ = A.countTrailingZeros();
    6152             :         unsigned BitWidth = A.getBitWidth();
    6153        2017 :         KnownBits Known(BitWidth);
    6154        3912 :         computeKnownBits(BO->LHS, Known, getDataLayout(),
    6155        1956 :                          0, &AC, nullptr, &DT);
    6156             : 
    6157             :         APInt EffectiveMask =
    6158        3912 :             APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
    6159       15648 :         if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
    6160        3790 :           const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
    6161        1895 :           const SCEV *LHS = getSCEV(BO->LHS);
    6162             :           const SCEV *ShiftedLHS = nullptr;
    6163             :           if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
    6164          29 :             if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
    6165             :               // For an expression like (x * 8) & 8, simplify the multiply.
    6166          28 :               unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
    6167          28 :               unsigned GCD = std::min(MulZeros, TZ);
    6168          28 :               APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
    6169             :               SmallVector<const SCEV*, 4> MulOps;
    6170          56 :               MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
    6171          56 :               MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
    6172          56 :               auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
    6173          28 :               ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
    6174             :             }
    6175             :           }
    6176          28 :           if (!ShiftedLHS)
    6177        1867 :             ShiftedLHS = getUDivExpr(LHS, MulCount);
    6178        3790 :           return getMulExpr(
    6179             :               getZeroExtendExpr(
    6180             :                   getTruncateExpr(ShiftedLHS,
    6181        3790 :                       IntegerType::get(getContext(), BitWidth - LZ - TZ)),
    6182        1895 :                   BO->LHS->getType()),
    6183        1895 :               MulCount);
    6184             :         }
    6185             :       }
    6186             :       break;
    6187             : 
    6188             :     case Instruction::Or:
    6189             :       // If the RHS of the Or is a constant, we may have something like:
    6190             :       // X*4+1 which got turned into X*4|1.  Handle this as an Add so loop
    6191             :       // optimizations will transparently handle this case.
    6192             :       //
    6193             :       // In order for this transformation to be safe, the LHS must be of the
    6194             :       // form X*(2^n) and the Or constant must be less than 2^n.
    6195        1156 :       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
    6196         768 :         const SCEV *LHS = getSCEV(BO->LHS);
    6197             :         const APInt &CIVal = CI->getValue();
    6198        1536 :         if (GetMinTrailingZeros(LHS) >=
    6199         768 :             (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
    6200             :           // Build a plain add SCEV.
    6201         726 :           const SCEV *S = getAddExpr(LHS, getSCEV(CI));
    6202             :           // If the LHS of the add was an addrec and it has no-wrap flags,
    6203             :           // transfer the no-wrap flags, since an or won't introduce a wrap.
    6204             :           if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
    6205             :             const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
    6206         489 :             const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
    6207             :                 OldAR->getNoWrapFlags());
    6208             :           }
    6209             :           return S;
    6210             :         }
    6211             :       }
    6212             :       break;
    6213             : 
    6214             :     case Instruction::Xor:
    6215         554 :       if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
    6216             :         // If the RHS of xor is -1, then this is a not operation.
    6217         108 :         if (CI->isMinusOne())
    6218          60 :           return getNotSCEV(getSCEV(BO->LHS));
    6219             : 
    6220             :         // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
    6221             :         // This is a variant of the check for xor with -1, and it handles
    6222             :         // the case where instcombine has trimmed non-demanded bits out
    6223             :         // of an xor with -1.
    6224          48 :         if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
    6225             :           if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
    6226          10 :             if (LBO->getOpcode() == Instruction::And &&
    6227             :                 LCI->getValue() == CI->getValue())
    6228             :               if (const SCEVZeroExtendExpr *Z =
    6229           4 :                       dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
    6230           2 :                 Type *UTy = BO->LHS->getType();
    6231           2 :                 const SCEV *Z0 = Z->getOperand();
    6232           2 :                 Type *Z0Ty = Z0->getType();
    6233           2 :                 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
    6234             : 
    6235             :                 // If C is a low-bits mask, the zero extend is serving to
    6236             :                 // mask off the high bits. Complement the operand and
    6237             :                 // re-apply the zext.
    6238           2 :                 if (CI->getValue().isMask(Z0TySize))
    6239           4 :                   return getZeroExtendExpr(getNotSCEV(Z0), UTy);
    6240             : 
    6241             :                 // If C is a single bit, it may be in the sign-bit position
    6242             :                 // before the zero-extend. In this case, represent the xor
    6243             :                 // using an add, which is equivalent, and re-apply the zext.
    6244           0 :                 APInt Trunc = CI->getValue().trunc(Z0TySize);
    6245           0 :                 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
    6246             :                     Trunc.isSignMask())
    6247           0 :                   return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
    6248           0 :                                            UTy);
    6249             :               }
    6250             :       }
    6251             :       break;
    6252             : 
    6253             :     case Instruction::Shl:
    6254             :       // Turn shift left of a constant amount into a multiply.
    6255        2684 :       if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
    6256             :         uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
    6257             : 
    6258             :         // If the shift count is not less than the bitwidth, the result of
    6259             :         // the shift is undefined. Don't try to analyze it, because the
    6260             :         // resolution chosen here may differ from the resolution chosen in
    6261             :         // other parts of the compiler.
    6262        4652 :         if (SA->getValue().uge(BitWidth))
    6263             :           break;
    6264             : 
    6265             :         // It is currently not resolved how to interpret NSW for left
    6266             :         // shift by BitWidth - 1, so we avoid applying flags in that
    6267             :         // case. Remove this check (or this comment) once the situation
    6268             :         // is resolved. See
    6269             :         // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
    6270             :         // and http://reviews.llvm.org/D8890 .
    6271             :         auto Flags = SCEV::FlagAnyWrap;
    6272        2322 :         if (BO->Op && SA->getValue().ult(BitWidth - 1))
    6273        2321 :           Flags = getNoWrapFlagsFromUB(BO->Op);
    6274             : 
    6275        2322 :         Constant *X = ConstantInt::get(
    6276        6966 :             getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
    6277        2322 :         return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
    6278             :       }
    6279             :       break;
    6280             : 
    6281             :     case Instruction::AShr: {
    6282             :       // AShr X, C, where C is a constant.
    6283        1423 :       ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
    6284             :       if (!CI)
    6285             :         break;
    6286             : 
    6287        1419 :       Type *OuterTy = BO->LHS->getType();
    6288        1419 :       uint64_t BitWidth = getTypeSizeInBits(OuterTy);
    6289             :       // If the shift count is not less than the bitwidth, the result of
    6290             :       // the shift is undefined. Don't try to analyze it, because the
    6291             :       // resolution chosen here may differ from the resolution chosen in
    6292             :       // other parts of the compiler.
    6293        1419 :       if (CI->getValue().uge(BitWidth))
    6294             :         break;
    6295             : 
    6296        1415 :       if (CI->isZero())
    6297           1 :         return getSCEV(BO->LHS); // shift by zero --> noop
    6298             : 
    6299             :       uint64_t AShrAmt = CI->getZExtValue();
    6300        2828 :       Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
    6301             : 
    6302        1414 :       Operator *L = dyn_cast<Operator>(BO->LHS);
    6303        1342 :       if (L && L->getOpcode() == Instruction::Shl) {
    6304             :         // X = Shl A, n
    6305             :         // Y = AShr X, m
    6306             :         // Both n and m are constant.
    6307             : 
    6308         682 :         const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
    6309         341 :         if (L->getOperand(1) == BO->RHS)
    6310             :           // For a two-shift sext-inreg, i.e. n = m,
    6311             :           // use sext(trunc(x)) as the SCEV expression.
    6312         309 :           return getSignExtendExpr(
    6313         309 :               getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
    6314             : 
    6315             :         ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
    6316          32 :         if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
    6317             :           uint64_t ShlAmt = ShlAmtCI->getZExtValue();
    6318          32 :           if (ShlAmt > AShrAmt) {
    6319             :             // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
    6320             :             // expression. We already checked that ShlAmt < BitWidth, so
    6321             :             // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
    6322             :             // ShlAmt - AShrAmt < Amt.
    6323             :             APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
    6324           2 :                                             ShlAmt - AShrAmt);
    6325           2 :             return getSignExtendExpr(
    6326             :                 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
    6327           2 :                 getConstant(Mul)), OuterTy);
    6328             :           }
    6329             :         }
    6330             :       }
    6331             :       break;
    6332             :     }
    6333             :     }
    6334             :   }
    6335             : 
    6336      337159 :   switch (U->getOpcode()) {
    6337        4112 :   case Instruction::Trunc:
    6338        8224 :     return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
    6339             : 
    6340        4583 :   case Instruction::ZExt:
    6341        9166 :     return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
    6342             : 
    6343        9980 :   case Instruction::SExt:
    6344       19960 :     if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
    6345             :       // The NSW flag of a subtract does not always survive the conversion to
    6346             :       // A + (-1)*B.  By pushing sign extension onto its operands we are much
    6347             :       // more likely to preserve NSW and allow later AddRec optimisations.
    6348             :       //
    6349             :       // NOTE: This is effectively duplicating this logic from getSignExtend:
    6350             :       //   sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
    6351             :       // but by that point the NSW information has potentially been lost.
    6352         715 :       if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
    6353          11 :         Type *Ty = U->getType();
    6354          11 :         auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
    6355          11 :         auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
    6356          11 :         return getMinusSCEV(V1, V2, SCEV::FlagNSW);
    6357             :       }
    6358          11 :     }
    6359       19938 :     return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
    6360             : 
    6361       10929 :   case Instruction::BitCast:
    6362             :     // BitCasts are no-op casts so we just eliminate the cast.
    6363       21858 :     if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
    6364       10752 :       return getSCEV(U->getOperand(0));
    6365             :     break;
    6366             : 
    6367             :   // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
    6368             :   // lead to pointer expressions which cannot safely be expanded to GEPs,
    6369             :   // because ScalarEvolution doesn't respect the GEP aliasing rules when
    6370             :   // simplifying integer expressions.
    6371             : 
    6372      171025 :   case Instruction::GetElementPtr:
    6373      171025 :     return createNodeForGEP(cast<GEPOperator>(U));
    6374             : 
    6375       55737 :   case Instruction::PHI:
    6376       55737 :     return createNodeForPHI(cast<PHINode>(U));
    6377             : 
    6378       14513 :   case Instruction::Select:
    6379             :     // U can also be a select constant expr, which let fall through.  Since
    6380             :     // createNodeForSelect only works for a condition that is an `ICmpInst`, and
    6381             :     // constant expressions cannot have instructions as operands, we'd have
    6382             :     // returned getUnknown for a select constant expressions anyway.
    6383       14513 :     if (isa<Instruction>(U))
    6384       14511 :       return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
    6385       14511 :                                       U->getOperand(1), U->getOperand(2));
    6386             :     break;
    6387             : 
    6388       11192 :   case Instruction::Call:
    6389             :   case Instruction::Invoke:
    6390       11192 :     if (Value *RV = CallSite(U).getReturnedArgOperand())
    6391           7 :       return getSCEV(RV);
    6392             :     break;
    6393             :   }
    6394             : 
    6395       66452 :   return getUnknown(V);
    6396             : }
    6397             : 
    6398             : //===----------------------------------------------------------------------===//
    6399             : //                   Iteration Count Computation Code
    6400             : //
    6401             : 
    6402       12835 : static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
    6403       12835 :   if (!ExitCount)
    6404             :     return 0;
    6405             : 
    6406        5457 :   ConstantInt *ExitConst = ExitCount->getValue();
    6407             : 
    6408             :   // Guard against huge trip counts.
    6409        5457 :   if (ExitConst->getValue().getActiveBits() > 32)
    6410             :     return 0;
    6411             : 
    6412             :   // In case of integer overflow, this returns 0, which is correct.
    6413        4174 :   return ((unsigned)ExitConst->getZExtValue()) + 1;
    6414             : }
    6415             : 
    6416        2040 : unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
    6417        2040 :   if (BasicBlock *ExitingBB = L->getExitingBlock())
    6418        1976 :     return getSmallConstantTripCount(L, ExitingBB);
    6419             : 
    6420             :   // No trip count information for multiple exits.
    6421             :   return 0;
    6422             : }
    6423             : 
    6424        7939 : unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
    6425             :                                                     BasicBlock *ExitingBlock) {
    6426             :   assert(ExitingBlock && "Must pass a non-null exiting block!");
    6427             :   assert(L->isLoopExiting(ExitingBlock) &&
    6428             :          "Exiting block must actually branch out of the loop!");
    6429             :   const SCEVConstant *ExitCount =
    6430        7939 :       dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
    6431        7939 :   return getConstantTripCount(ExitCount);
    6432             : }
    6433             : 
    6434        4896 : unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
    6435             :   const auto *MaxExitCount =
    6436        4896 :       dyn_cast<SCEVConstant>(getMaxBackedgeTakenCount(L));
    6437        4896 :   return getConstantTripCount(MaxExitCount);
    6438             : }
    6439             : 
    6440         258 : unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
    6441         258 :   if (BasicBlock *ExitingBB = L->getExitingBlock())
    6442         248 :     return getSmallConstantTripMultiple(L, ExitingBB);
    6443             : 
    6444             :   // No trip multiple information for multiple exits.
    6445             :   return 0;
    6446             : }
    6447             : 
    6448             : /// Returns the largest constant divisor of the trip count of this loop as a
    6449             : /// normal unsigned value, if possible. This means that the actual trip count is
    6450             : /// always a multiple of the returned value (don't forget the trip count could
    6451             : /// very well be zero as well!).
    6452             : ///
    6453             : /// Returns 1 if the trip count is unknown or not guaranteed to be the
    6454             : /// multiple of a constant (which is also the case if the trip count is simply
    6455             : /// constant, use getSmallConstantTripCount for that case), Will also return 1
    6456             : /// if the trip count is very large (>= 2^32).
    6457             : ///
    6458             : /// As explained in the comments for getSmallConstantTripCount, this assumes
    6459             : /// that control exits the loop via ExitingBlock.
    6460             : unsigned
    6461        6177 : ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
    6462             :                                               BasicBlock *ExitingBlock) {
    6463             :   assert(ExitingBlock && "Must pass a non-null exiting block!");
    6464             :   assert(L->isLoopExiting(ExitingBlock) &&
    6465             :          "Exiting block must actually branch out of the loop!");
    6466        6177 :   const SCEV *ExitCount = getExitCount(L, ExitingBlock);
    6467        6177 :   if (ExitCount == getCouldNotCompute())
    6468             :     return 1;
    6469             : 
    6470             :   // Get the trip count from the BE count by adding 1.
    6471        7636 :   const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
    6472             : 
    6473             :   const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
    6474             :   if (!TC)
    6475             :     // Attempt to factor more general cases. Returns the greatest power of
    6476             :     // two divisor. If overflow happens, the trip count expression is still
    6477             :     // divisible by the greatest power of 2 divisor returned.
    6478        3356 :     return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
    6479             : 
    6480        2140 :   ConstantInt *Result = TC->getValue();
    6481             : 
    6482             :   // Guard against huge trip counts (this requires checking
    6483             :   // for zero to handle the case where the trip count == -1 and the
    6484             :   // addition wraps).
    6485        4280 :   if (!Result || Result->getValue().getActiveBits() > 32 ||
    6486             :       Result->getValue().getActiveBits() == 0)
    6487             :     return 1;
    6488             : 
    6489        2138 :   return (unsigned)Result->getZExtValue();
    6490             : }
    6491             : 
    6492             : /// Get the expression for the number of loop iterations for which this loop is
    6493             : /// guaranteed not to exit via ExitingBlock. Otherwise return
    6494             : /// SCEVCouldNotCompute.
    6495       15069 : const SCEV *ScalarEvolution::getExitCount(const Loop *L,
    6496             :                                           BasicBlock *ExitingBlock) {
    6497       15069 :   return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
    6498             : }
    6499             : 
    6500             : const SCEV *
    6501        4029 : ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
    6502             :                                                  SCEVUnionPredicate &Preds) {
    6503        4029 :   return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
    6504             : }
    6505             : 
    6506       39014 : const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
    6507       39014 :   return getBackedgeTakenInfo(L).getExact(L, this);
    6508             : }
    6509             : 
    6510             : /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
    6511             : /// known never to be less than the actual backedge taken count.
    6512      239891 : const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
    6513      239891 :   return getBackedgeTakenInfo(L).getMax(this);
    6514             : }
    6515             : 
    6516        4683 : bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
    6517        4683 :   return getBackedgeTakenInfo(L).isMaxOrZero(this);
    6518             : }
    6519             : 
    6520             : /// Push PHI nodes in the header of the given loop onto the given Worklist.
    6521             : static void
    6522       24764 : PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
    6523             :   BasicBlock *Header = L->getHeader();
    6524             : 
    6525             :   // Push all Loop-header PHIs onto the Worklist stack.
    6526       24764 :   for (PHINode &PN : Header->phis())
    6527       33692 :     Worklist.push_back(&PN);
    6528       24764 : }
    6529             : 
    6530             : const ScalarEvolution::BackedgeTakenInfo &
    6531        4029 : ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
    6532        4029 :   auto &BTI = getBackedgeTakenInfo(L);
    6533        4029 :   if (BTI.hasFullInfo())
    6534             :     return BTI;
    6535             : 
    6536        2655 :   auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
    6537             : 
    6538         885 :   if (!Pair.second)
    6539          12 :     return Pair.first->second;
    6540             : 
    6541             :   BackedgeTakenInfo Result =
    6542         873 :       computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
    6543             : 
    6544        1746 :   return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
    6545             : }
    6546             : 
    6547             : const ScalarEvolution::BackedgeTakenInfo &
    6548      319031 : ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
    6549             :   // Initially insert an invalid entry for this loop. If the insertion
    6550             :   // succeeds, proceed to actually compute a backedge-taken count and
    6551             :   // update the value. The temporary CouldNotCompute value tells SCEV
    6552             :   // code elsewhere that it shouldn't attempt to request a new
    6553             :   // backedge-taken count, which could result in infinite recursion.
    6554             :   std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
    6555      957093 :       BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
    6556      319031 :   if (!Pair.second)
    6557      297216 :     return Pair.first->second;
    6558             : 
    6559             :   // computeBackedgeTakenCount may allocate memory for its result. Inserting it
    6560             :   // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
    6561             :   // must be cleared in this scope.
    6562       21815 :   BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
    6563             : 
    6564             :   // In product build, there are no usage of statistic.
    6565             :   (void)NumTripCountsComputed;
    6566             :   (void)NumTripCountsNotComputed;
    6567             : #if LLVM_ENABLE_STATS || !defined(NDEBUG)
    6568             :   const SCEV *BEExact = Result.getExact(L, this);
    6569             :   if (BEExact != getCouldNotCompute()) {
    6570             :     assert(isLoopInvariant(BEExact, L) &&
    6571             :            isLoopInvariant(Result.getMax(this), L) &&
    6572             :            "Computed backedge-taken count isn't loop invariant for loop!");
    6573             :     ++NumTripCountsComputed;
    6574             :   }
    6575             :   else if (Result.getMax(this) == getCouldNotCompute() &&
    6576             :            isa<PHINode>(L->getHeader()->begin())) {
    6577             :     // Only count loops that have phi nodes as not being computable.
    6578             :     ++NumTripCountsNotComputed;
    6579             :   }
    6580             : #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
    6581             : 
    6582             :   // Now that we know more about the trip count for this loop, forget any
    6583             :   // existing SCEV values for PHI nodes in this loop since they are only
    6584             :   // conservative estimates made without the benefit of trip count
    6585             :   // information. This is similar to the code in forgetLoop, except that
    6586             :   // it handles SCEVUnknown PHI nodes specially.
    6587             :   if (Result.hasAnyInfo()) {
    6588             :     SmallVector<Instruction *, 16> Worklist;
    6589       16817 :     PushLoopPHIs(L, Worklist);
    6590             : 
    6591             :     SmallPtrSet<Instruction *, 8> Discovered;
    6592      629709 :     while (!Worklist.empty()) {
    6593             :       Instruction *I = Worklist.pop_back_val();
    6594             : 
    6595             :       ValueExprMapType::iterator It =
    6596      306446 :         ValueExprMap.find_as(static_cast<Value *>(I));
    6597      306446 :       if (It != ValueExprMap.end()) {
    6598       40931 :         const SCEV *Old = It->second;
    6599             : 
    6600             :         // SCEVUnknown for a PHI either means that it has an unrecognized
    6601             :         // structure, or it's a PHI that's in the progress of being computed
    6602             :         // by createNodeForPHI.  In the former case, additional loop trip
    6603             :         // count information isn't going to change anything. In the later
    6604             :         // case, createNodeForPHI will perform the necessary updates on its
    6605             :         // own when it gets to that point.
    6606       60365 :         if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
    6607       38923 :           eraseValueFromMap(It->first);
    6608       38923 :           forgetMemoizedResults(Old);
    6609             :         }
    6610       40931 :         if (PHINode *PN = dyn_cast<PHINode>(I))
    6611       19434 :           ConstantEvolutionLoopExitValue.erase(PN);
    6612             :       }
    6613             : 
    6614             :       // Since we don't need to invalidate anything for correctness and we're
    6615             :       // only invalidating to make SCEV's results more precise, we get to stop
    6616             :       // early to avoid invalidating too much.  This is especially important in
    6617             :       // cases like:
    6618             :       //
    6619             :       //   %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
    6620             :       // loop0:
    6621             :       //   %pn0 = phi
    6622             :       //   ...
    6623             :       // loop1:
    6624             :       //   %pn1 = phi
    6625             :       //   ...
    6626             :       //
    6627             :       // where both loop0 and loop1's backedge taken count uses the SCEV
    6628             :       // expression for %v.  If we don't have the early stop below then in cases
    6629             :       // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
    6630             :       // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
    6631             :       // count for loop1, effectively nullifying SCEV's trip count cache.
    6632      697998 :       for (auto *U : I->users())
    6633      391552 :         if (auto *I = dyn_cast<Instruction>(U)) {
    6634      391552 :           auto *LoopForUser = LI.getLoopFor(I->getParent());
    6635     1151621 :           if (LoopForUser && L->contains(LoopForUser) &&
    6636      491675 :               Discovered.insert(I).second)
    6637      282734 :             Worklist.push_back(I);
    6638             :         }
    6639             :     }
    6640             :   }
    6641             : 
    6642             :   // Re-lookup the insert position, since the call to
    6643             :   // computeBackedgeTakenCount above could result in a
    6644             :   // recusive call to getBackedgeTakenInfo (on a different
    6645             :   // loop), which would invalidate the iterator computed
    6646             :   // earlier.
    6647       43630 :   return BackedgeTakenCounts.find(L)->second = std::move(Result);
    6648             : }
    6649             : 
    6650        5402 : void ScalarEvolution::forgetLoop(const Loop *L) {
    6651             :   // Drop any stored trip count value.
    6652             :   auto RemoveLoopFromBackedgeMap =
    6653       15894 :       [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
    6654       15894 :         auto BTCPos = Map.find(L);
    6655       15894 :         if (BTCPos != Map.end()) {
    6656        1952 :           BTCPos->second.clear();
    6657             :           Map.erase(BTCPos);
    6658             :         }
    6659       15894 :       };
    6660             : 
    6661             :   SmallVector<const Loop *, 16> LoopWorklist(1, L);
    6662             :   SmallVector<Instruction *, 32> Worklist;
    6663             :   SmallPtrSet<Instruction *, 16> Visited;
    6664             : 
    6665             :   // Iterate over all the loops and sub-loops to drop SCEV information.
    6666       21296 :   while (!LoopWorklist.empty()) {
    6667        7947 :     auto *CurrL = LoopWorklist.pop_back_val();
    6668             : 
    6669        7947 :     RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
    6670        7947 :     RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
    6671             : 
    6672             :     // Drop information about predicated SCEV rewrites for this loop.
    6673        8023 :     for (auto I = PredicatedSCEVRewrites.begin();
    6674        8023 :          I != PredicatedSCEVRewrites.end();) {
    6675             :       std::pair<const SCEV *, const Loop *> Entry = I->first;
    6676          76 :       if (Entry.second == CurrL)
    6677             :         PredicatedSCEVRewrites.erase(I++);
    6678             :       else
    6679           7 :         ++I;
    6680             :     }
    6681             : 
    6682        7947 :     auto LoopUsersItr = LoopUsers.find(CurrL);
    6683        7947 :     if (LoopUsersItr != LoopUsers.end()) {
    6684       22769 :       for (auto *S : LoopUsersItr->second)
    6685       10492 :         forgetMemoizedResults(S);
    6686             :       LoopUsers.erase(LoopUsersItr);
    6687             :     }
    6688             : 
    6689             :     // Drop information about expressions based on loop-header PHIs.
    6690        7947 :     PushLoopPHIs(CurrL, Worklist);
    6691             : 
    6692      161572 :     while (!Worklist.empty()) {
    6693             :       Instruction *I = Worklist.pop_back_val();
    6694      153625 :       if (!Visited.insert(I).second)
    6695       28022 :         continue;
    6696             : 
    6697             :       ValueExprMapType::iterator It =
    6698      125603 :           ValueExprMap.find_as(static_cast<Value *>(I));
    6699      125603 :       if (It != ValueExprMap.end()) {
    6700        4750 :         eraseValueFromMap(It->first);
    6701        4750 :         forgetMemoizedResults(It->second);
    6702        4750 :         if (PHINode *PN = dyn_cast<PHINode>(I))
    6703        1648 :           ConstantEvolutionLoopExitValue.erase(PN);
    6704             :       }
    6705             : 
    6706      125603 :       PushDefUseChildren(I, Worklist);
    6707             :     }
    6708             : 
    6709        7947 :     LoopPropertiesCache.erase(CurrL);
    6710             :     // Forget all contained loops too, to avoid dangling entries in the
    6711             :     // ValuesAtScopes map.
    6712       15894 :     LoopWorklist.append(CurrL->begin(), CurrL->end());
    6713             :   }
    6714        5402 : }
    6715             : 
    6716        3834 : void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
    6717        4543 :   while (Loop *Parent = L->getParentLoop())
    6718             :     L = Parent;
    6719        3834 :   forgetLoop(L);
    6720        3834 : }
    6721             : 
    6722       11349 : void ScalarEvolution::forgetValue(Value *V) {
    6723       11349 :   Instruction *I = dyn_cast<Instruction>(V);
    6724       11349 :   if (!I) return;
    6725             : 
    6726             :   // Drop information about expressions based on loop-header PHIs.
    6727             :   SmallVector<Instruction *, 16> Worklist;
    6728       11349 :   Worklist.push_back(I);
    6729             : 
    6730             :   SmallPtrSet<Instruction *, 8> Visited;
    6731      142090 :   while (!Worklist.empty()) {
    6732      130741 :     I = Worklist.pop_back_val();
    6733      130741 :     if (!Visited.insert(I).second)
    6734       17886 :       continue;
    6735             : 
    6736             :     ValueExprMapType::iterator It =
    6737      112855 :       ValueExprMap.find_as(static_cast<Value *>(I));
    6738      112855 :     if (It != ValueExprMap.end()) {
    6739       15541 :       eraseValueFromMap(It->first);
    6740       15541 :       forgetMemoizedResults(It->second);
    6741       31082 :       if (PHINode *PN = dyn_cast<PHINode>(I))
    6742        3658 :         ConstantEvolutionLoopExitValue.erase(PN);
    6743             :     }
    6744             : 
    6745      112855 :     PushDefUseChildren(I, Worklist);
    6746             :   }
    6747             : }
    6748             : 
    6749             : /// Get the exact loop backedge taken count considering all loop exits. A
    6750             : /// computable result can only be returned for loops with all exiting blocks
    6751             : /// dominating the latch. howFarToZero assumes that the limit of each loop test
    6752             : /// is never skipped. This is a valid assumption as long as the loop exits via
    6753             : /// that test. For precise results, it is the caller's responsibility to specify
    6754             : /// the relevant loop exiting block using getExact(ExitingBlock, SE).
    6755             : const SCEV *
    6756       43043 : ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
    6757             :                                              SCEVUnionPredicate *Preds) const {
    6758             :   // If any exits were not computable, the loop is not computable.
    6759       43043 :   if (!isComplete() || ExitNotTaken.empty())
    6760       12074 :     return SE->getCouldNotCompute();
    6761             : 
    6762       30969 :   const BasicBlock *Latch = L->getLoopLatch();
    6763             :   // All exiting blocks we have collected must dominate the only backedge.
    6764       30969 :   if (!Latch)
    6765           0 :     return SE->getCouldNotCompute();
    6766             : 
    6767             :   // All exiting blocks we have gathered dominate loop's latch, so exact trip
    6768             :   // count is simply a minimum out of all these calculated exit counts.
    6769             :   SmallVector<const SCEV *, 2> Ops;
    6770       93549 :   for (auto &ENT : ExitNotTaken) {
    6771       31290 :     const SCEV *BECount = ENT.ExactNotTaken;
    6772             :     assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
    6773             :     assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
    6774             :            "We should only have known counts for exiting blocks that dominate "
    6775             :            "latch!");
    6776             : 
    6777       31290 :     Ops.push_back(BECount);
    6778             : 
    6779       31290 :     if (Preds && !ENT.hasAlwaysTruePredicate())
    6780          24 :       Preds->add(ENT.Predicate.get());
    6781             : 
    6782             :     assert((Preds || ENT.hasAlwaysTruePredicate()) &&
    6783             :            "Predicate should be always true!");
    6784             :   }
    6785             : 
    6786       30969 :   return SE->getUMinFromMismatchedTypes(Ops);
    6787             : }
    6788             : 
    6789             : /// Get the exact not taken count for this loop exit.
    6790             : const SCEV *
    6791       31414 : ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
    6792             :                                              ScalarEvolution *SE) const {
    6793       34822 :   for (auto &ENT : ExitNotTaken)
    6794       25742 :     if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
    6795       24038 :       return ENT.ExactNotTaken;
    6796             : 
    6797        7376 :   return SE->getCouldNotCompute();
    6798             : }
    6799             : 
    6800             : /// getMax - Get the max backedge taken count for the loop.
    6801             : const SCEV *
    6802      239891 : ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
    6803             :   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
    6804             :     return !ENT.hasAlwaysTruePredicate();
    6805             :   };
    6806             : 
    6807      479782 :   if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
    6808       34126 :     return SE->getCouldNotCompute();
    6809             : 
    6810             :   assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
    6811             :          "No point in having a non-constant max backedge taken count!");
    6812             :   return getMax();
    6813             : }
    6814             : 
    6815        4683 : bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
    6816             :   auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
    6817             :     return !ENT.hasAlwaysTruePredicate();
    6818             :   };
    6819        4701 :   return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
    6820             : }
    6821             : 
    6822      131027 : bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
    6823             :                                                     ScalarEvolution *SE) const {
    6824      197399 :   if (getMax() && getMax() != SE->getCouldNotCompute() &&
    6825       66372 :       SE->hasOperand(getMax(), S))
    6826             :     return true;
    6827             : 
    6828      258509 :   for (auto &ENT : ExitNotTaken)
    6829      127632 :     if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
    6830       63816 :         SE->hasOperand(ENT.ExactNotTaken, S))
    6831             :       return true;
    6832             : 
    6833             :   return false;
    6834             : }
    6835             : 
    6836       51533 : ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
    6837       51533 :     : ExactNotTaken(E), MaxNotTaken(E) {
    6838             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6839             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6840             :          "No point in having a non-constant max backedge taken count!");
    6841       51533 : }
    6842             : 
    6843       10265 : ScalarEvolution::ExitLimit::ExitLimit(
    6844             :     const SCEV *E, const SCEV *M, bool MaxOrZero,
    6845       10265 :     ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
    6846       10265 :     : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
    6847             :   assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
    6848             :           !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
    6849             :          "Exact is not allowed to be less precise than Max");
    6850             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6851             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6852             :          "No point in having a non-constant max backedge taken count!");
    6853       31241 :   for (auto *PredSet : PredSetList)
    6854       10488 :     for (auto *P : *PredSet)
    6855             :       addPredicate(P);
    6856       10265 : }
    6857             : 
    6858        9948 : ScalarEvolution::ExitLimit::ExitLimit(
    6859             :     const SCEV *E, const SCEV *M, bool MaxOrZero,
    6860        9948 :     const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
    6861       19896 :     : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
    6862             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6863             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6864             :          "No point in having a non-constant max backedge taken count!");
    6865        9948 : }
    6866             : 
    6867          47 : ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
    6868          47 :                                       bool MaxOrZero)
    6869          47 :     : ExitLimit(E, M, MaxOrZero, None) {
    6870             :   assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
    6871             :           isa<SCEVConstant>(MaxNotTaken)) &&
    6872             :          "No point in having a non-constant max backedge taken count!");
    6873          47 : }
    6874             : 
    6875             : /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
    6876             : /// computable exit into a persistent ExitNotTakenInfo array.
    6877       22688 : ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
    6878             :     SmallVectorImpl<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
    6879             :         &&ExitCounts,
    6880       22688 :     bool Complete, const SCEV *MaxCount, bool MaxOrZero)
    6881       45376 :     : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
    6882             :   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
    6883             : 
    6884             :   ExitNotTaken.reserve(ExitCounts.size());
    6885       22688 :   std::transform(
    6886             :       ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
    6887       16382 :       [&](const EdgeExitInfo &EEI) {
    6888       16382 :         BasicBlock *ExitBB = EEI.first;
    6889             :         const ExitLimit &EL = EEI.second;
    6890       16382 :         if (EL.Predicates.empty())
    6891       32738 :           return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
    6892             : 
    6893          26 :         std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
    6894          13 :         for (auto *Pred : EL.Predicates)
    6895          13 :           Predicate->add(Pred);
    6896             : 
    6897          26 :         return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
    6898             :       });
    6899             :   assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
    6900             :          "No point in having a non-constant max backedge taken count!");
    6901       22688 : }
    6902             : 
    6903             : /// Invalidate this result and free the ExitNotTakenInfo array.
    6904       22592 : void ScalarEvolution::BackedgeTakenInfo::clear() {
    6905             :   ExitNotTaken.clear();
    6906       22592 : }
    6907             : 
    6908             : /// Compute the number of times the backedge of the specified loop will execute.
    6909             : ScalarEvolution::BackedgeTakenInfo
    6910       22688 : ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
    6911             :                                            bool AllowPredicates) {
    6912             :   SmallVector<BasicBlock *, 8> ExitingBlocks;
    6913       22688 :   L->getExitingBlocks(ExitingBlocks);
    6914             : 
    6915             :   using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
    6916             : 
    6917       22688 :   SmallVector<EdgeExitInfo, 4> ExitCounts;
    6918             :   bool CouldComputeBECount = true;
    6919       22688 :   BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
    6920             :   const SCEV *MustExitMaxBECount = nullptr;
    6921             :   const SCEV *MayExitMaxBECount = nullptr;
    6922             :   bool MustExitMaxOrZero = false;
    6923             : 
    6924             :   // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
    6925             :   // and compute maxBECount.
    6926             :   // Do a union of all the predicates here.
    6927       73178 :   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
    6928      100980 :     BasicBlock *ExitBB = ExitingBlocks[i];
    6929       50490 :     ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
    6930             : 
    6931             :     assert((AllowPredicates || EL.Predicates.empty()) &&
    6932             :            "Predicated exit limit when predicates are not allowed!");
    6933             : 
    6934             :     // 1. For each exit that can be computed, add an entry to ExitCounts.
    6935             :     // CouldComputeBECount is true only if all exits can be computed.
    6936       50490 :     if (EL.ExactNotTaken == getCouldNotCompute())
    6937             :       // We couldn't compute an exact value for this exit, so
    6938             :       // we won't be able to compute an exact value for the loop.
    6939             :       CouldComputeBECount = false;
    6940             :     else
    6941       16382 :       ExitCounts.emplace_back(ExitBB, EL);
    6942             : 
    6943             :     // 2. Derive the loop's MaxBECount from each exit's max number of
    6944             :     // non-exiting iterations. Partition the loop exits into two kinds:
    6945             :     // LoopMustExits and LoopMayExits.
    6946             :     //
    6947             :     // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
    6948             :     // is a LoopMayExit.  If any computable LoopMustExit is found, then
    6949             :     // MaxBECount is the minimum EL.MaxNotTaken of computable
    6950             :     // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
    6951             :     // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
    6952             :     // computable EL.MaxNotTaken.
    6953       67764 :     if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
    6954       17274 :         DT.dominates(ExitBB, Latch)) {
    6955       17274 :       if (!MustExitMaxBECount) {
    6956       16906 :         MustExitMaxBECount = EL.MaxNotTaken;
    6957       16906 :         MustExitMaxOrZero = EL.MaxOrZero;
    6958             :       } else {
    6959         368 :         MustExitMaxBECount =
    6960         368 :             getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
    6961             :       }
    6962       33216 :     } else if (MayExitMaxBECount != getCouldNotCompute()) {
    6963        9114 :       if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
    6964        9114 :         MayExitMaxBECount = EL.MaxNotTaken;
    6965             :       else {
    6966           0 :         MayExitMaxBECount =
    6967           0 :             getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
    6968             :       }
    6969             :     }
    6970             :   }
    6971       22688 :   const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
    6972        5782 :     (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
    6973             :   // The loop backedge will be taken the maximum or zero times if there's
    6974             :   // a single exit that must be taken the maximum or zero times.
    6975       22709 :   bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
    6976             :   return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
    6977       45376 :                            MaxBECount, MaxOrZero);
    6978             : }
    6979             : 
    6980             : ScalarEvolution::ExitLimit
    6981       50490 : ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
    6982             :                                       bool AllowPredicates) {
    6983             :   assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
    6984             :   // If our exiting block does not dominate the latch, then its connection with
    6985             :   // loop's exit limit may be far from trivial.
    6986       50490 :   const BasicBlock *Latch = L->getLoopLatch();
    6987       50490 :   if (!Latch || !DT.dominates(ExitingBlock, Latch))
    6988       17972 :     return getCouldNotCompute();
    6989             : 
    6990       32518 :   bool IsOnlyExit = (L->getExitingBlock() != nullptr);
    6991             :   TerminatorInst *Term = ExitingBlock->getTerminator();
    6992             :   if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
    6993             :     assert(BI->isConditional() && "If unconditional, it can't be in loop!");
    6994       25805 :     bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
    6995             :     assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
    6996             :            "It should have one successor in loop and one exit block!");
    6997             :     // Proceed to the next level to examine the exit condition expression.
    6998             :     return computeExitLimitFromCond(
    6999             :         L, BI->getCondition(), ExitIfTrue,
    7000       51610 :         /*ControlsExit=*/IsOnlyExit, AllowPredicates);
    7001             :   }
    7002             : 
    7003             :   if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
    7004             :     // For switch, make sure that there is a single exit from the loop.
    7005             :     BasicBlock *Exit = nullptr;
    7006          61 :     for (auto *SBB : successors(ExitingBlock))
    7007         196 :       if (!L->contains(SBB)) {
    7008          86 :         if (Exit) // Multiple exit successors.
    7009          25 :           return getCouldNotCompute();
    7010             :         Exit = SBB;
    7011             :       }
    7012             :     assert(Exit && "Exiting block must have at least one exit");
    7013             :     return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
    7014          36 :                                                 /*ControlsExit=*/IsOnlyExit);
    7015             :   }
    7016             : 
    7017        6652 :   return getCouldNotCompute();
    7018             : }
    7019             : 
    7020       25805 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
    7021             :     const Loop *L, Value *ExitCond, bool ExitIfTrue,
    7022             :     bool ControlsExit, bool AllowPredicates) {
    7023       25805 :   ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
    7024             :   return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
    7025       51610 :                                         ControlsExit, AllowPredicates);
    7026             : }
    7027             : 
    7028             : Optional<ScalarEvolution::ExitLimit>
    7029       26345 : ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
    7030             :                                       bool ExitIfTrue, bool ControlsExit,
    7031             :                                       bool AllowPredicates) {
    7032             :   (void)this->L;
    7033             :   (void)this->ExitIfTrue;
    7034             :   (void)this->AllowPredicates;
    7035             : 
    7036             :   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
    7037             :          this->AllowPredicates == AllowPredicates &&
    7038             :          "Variance in assumed invariant key components!");
    7039       52690 :   auto Itr = TripCountMap.find({ExitCond, ControlsExit});
    7040       26345 :   if (Itr == TripCountMap.end())
    7041             :     return None;
    7042             :   return Itr->second;
    7043             : }
    7044             : 
    7045       26285 : void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
    7046             :                                              bool ExitIfTrue,
    7047             :                                              bool ControlsExit,
    7048             :                                              bool AllowPredicates,
    7049             :                                              const ExitLimit &EL) {
    7050             :   assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
    7051             :          this->AllowPredicates == AllowPredicates &&
    7052             :          "Variance in assumed invariant key components!");
    7053             : 
    7054       52570 :   auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
    7055             :   assert(InsertResult.second && "Expected successful insertion!");
    7056             :   (void)InsertResult;
    7057             :   (void)ExitIfTrue;
    7058       26285 : }
    7059             : 
    7060       26345 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
    7061             :     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
    7062             :     bool ControlsExit, bool AllowPredicates) {
    7063             : 
    7064       26345 :   if (auto MaybeEL =
    7065       26345 :           Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
    7066             :     return *MaybeEL;
    7067             : 
    7068             :   ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
    7069       26285 :                                               ControlsExit, AllowPredicates);
    7070       26285 :   Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
    7071             :   return EL;
    7072             : }
    7073             : 
    7074       26285 : ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
    7075             :     ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
    7076             :     bool ControlsExit, bool AllowPredicates) {
    7077             :   // Check if the controlling expression for this loop is an And or Or.
    7078             :   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
    7079         279 :     if (BO->getOpcode() == Instruction::And) {
    7080             :       // Recurse on the operands of the and.
    7081             :       bool EitherMayExit = !ExitIfTrue;
    7082             :       ExitLimit EL0 = computeExitLimitFromCondCached(
    7083             :           Cache, L, BO->getOperand(0), ExitIfTrue,
    7084         424 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7085             :       ExitLimit EL1 = computeExitLimitFromCondCached(
    7086             :           Cache, L, BO->getOperand(1), ExitIfTrue,
    7087         212 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7088         212 :       const SCEV *BECount = getCouldNotCompute();
    7089         212 :       const SCEV *MaxBECount = getCouldNotCompute();
    7090         212 :       if (EitherMayExit) {
    7091             :         // Both conditions must be true for the loop to continue executing.
    7092             :         // Choose the less conservative count.
    7093         197 :         if (EL0.ExactNotTaken == getCouldNotCompute() ||
    7094          55 :             EL1.ExactNotTaken == getCouldNotCompute())
    7095         129 :           BECount = getCouldNotCompute();
    7096             :         else
    7097             :           BECount =
    7098          13 :               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
    7099         142 :         if (EL0.MaxNotTaken == getCouldNotCompute())
    7100          87 :           MaxBECount = EL1.MaxNotTaken;
    7101          55 :         else if (EL1.MaxNotTaken == getCouldNotCompute())
    7102          42 :           MaxBECount = EL0.MaxNotTaken;
    7103             :         else
    7104             :           MaxBECount =
    7105          13 :               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
    7106             :       } else {
    7107             :         // Both conditions must be true at the same time for the loop to exit.
    7108             :         // For now, be conservative.
    7109          70 :         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
    7110             :           MaxBECount = EL0.MaxNotTaken;
    7111          70 :         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
    7112             :           BECount = EL0.ExactNotTaken;
    7113             :       }
    7114             : 
    7115             :       // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
    7116             :       // to be more aggressive when computing BECount than when computing
    7117             :       // MaxBECount.  In these cases it is possible for EL0.ExactNotTaken and
    7118             :       // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
    7119             :       // to not.
    7120         275 :       if (isa<SCEVCouldNotCompute>(MaxBECount) &&
    7121             :           !isa<SCEVCouldNotCompute>(BECount))
    7122           2 :         MaxBECount = getConstant(getUnsignedRangeMax(BECount));
    7123             : 
    7124             :       return ExitLimit(BECount, MaxBECount, false,
    7125         424 :                        {&EL0.Predicates, &EL1.Predicates});
    7126             :     }
    7127          67 :     if (BO->getOpcode() == Instruction::Or) {
    7128             :       // Recurse on the operands of the or.
    7129             :       bool EitherMayExit = ExitIfTrue;
    7130             :       ExitLimit EL0 = computeExitLimitFromCondCached(
    7131             :           Cache, L, BO->getOperand(0), ExitIfTrue,
    7132         116 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7133             :       ExitLimit EL1 = computeExitLimitFromCondCached(
    7134             :           Cache, L, BO->getOperand(1), ExitIfTrue,
    7135          58 :           ControlsExit && !EitherMayExit, AllowPredicates);
    7136          58 :       const SCEV *BECount = getCouldNotCompute();
    7137          58 :       const SCEV *MaxBECount = getCouldNotCompute();
    7138          58 :       if (EitherMayExit) {
    7139             :         // Both conditions must be false for the loop to continue executing.
    7140             :         // Choose the less conservative count.
    7141          27 :         if (EL0.ExactNotTaken == getCouldNotCompute() ||
    7142           7 :             EL1.ExactNotTaken == getCouldNotCompute())
    7143          17 :           BECount = getCouldNotCompute();
    7144             :         else
    7145           3 :           BECount =
    7146           3 :               getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
    7147          20 :         if (EL0.MaxNotTaken == getCouldNotCompute())
    7148          13 :           MaxBECount = EL1.MaxNotTaken;
    7149           7 :         else if (EL1.MaxNotTaken == getCouldNotCompute())
    7150           4 :           MaxBECount = EL0.MaxNotTaken;
    7151             :         else
    7152           3 :           MaxBECount =
    7153           3 :               getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
    7154             :       } else {
    7155             :         // Both conditions must be false at the same time for the loop to exit.
    7156             :         // For now, be conservative.
    7157          38 :         if (EL0.MaxNotTaken == EL1.MaxNotTaken)
    7158             :           MaxBECount = EL0.MaxNotTaken;
    7159          38 :         if (EL0.ExactNotTaken == EL1.ExactNotTaken)
    7160             :           BECount = EL0.ExactNotTaken;
    7161             :       }
    7162             : 
    7163             :       return ExitLimit(BECount, MaxBECount, false,
    7164         116 :                        {&EL0.Predicates, &EL1.Predicates});
    7165             :     }
    7166             :   }
    7167             : 
    7168             :   // With an icmp, it may be feasible to compute an exact backedge-taken count.
    7169             :   // Proceed to the next level to examine the icmp.
    7170             :   if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
    7171             :     ExitLimit EL =
    7172       24582 :         computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
    7173       24582 :     if (EL.hasFullInfo() || !AllowPredicates)
    7174             :       return EL;
    7175             : 
    7176             :     // Try again, but use SCEV predicates this time.
    7177             :     return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
    7178         807 :                                     /*AllowPredicates=*/true);
    7179             :   }
    7180             : 
    7181             :   // Check for a constant condition. These are normally stripped out by
    7182             :   // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
    7183             :   // preserve the CFG and is temporarily leaving constant conditions
    7184             :   // in place.
    7185             :   if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
    7186         662 :     if (ExitIfTrue == !CI->getZExtValue())
    7187             :       // The backedge is always taken.
    7188         136 :       return getCouldNotCompute();
    7189             :     else
    7190             :       // The backedge is never taken.
    7191         526 :       return getZero(CI->getType());
    7192             :   }
    7193             : 
    7194             :   // If it's not an integer or pointer comparison then compute it the hard way.
    7195         771 :   return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
    7196             : }
    7197             : 
    7198             : ScalarEvolution::ExitLimit
    7199       25389 : ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
    7200             :                                           ICmpInst *ExitCond,
    7201             :                                           bool ExitIfTrue,
    7202             :                                           bool ControlsExit,
    7203             :                                           bool AllowPredicates) {
    7204             :   // If the condition was exit on true, convert the condition to exit on false
    7205             :   ICmpInst::Predicate Pred;
    7206       25389 :   if (!ExitIfTrue)
    7207       15106 :     Pred = ExitCond->getPredicate();
    7208             :   else
    7209       10283 :     Pred = ExitCond->getInversePredicate();
    7210       25389 :   const ICmpInst::Predicate OriginalPred = Pred;
    7211             : 
    7212             :   // Handle common loops like: for (X = "string"; *X; ++X)
    7213             :   if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
    7214             :     if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
    7215             :       ExitLimit ItCnt =
    7216        1853 :         computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
    7217        1853 :       if (ItCnt.hasAnyInfo())
    7218             :         return ItCnt;
    7219             :     }
    7220             : 
    7221       25389 :   const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
    7222       25389 :   const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
    7223             : 
    7224             :   // Try to evaluate any dependencies out of the loop.
    7225       25389 :   LHS = getSCEVAtScope(LHS, L);
    7226       25389 :   RHS = getSCEVAtScope(RHS, L);
    7227             : 
    7228             :   // At this point, we would like to compute how many iterations of the
    7229             :   // loop the predicate will return true for these inputs.
    7230       25389 :   if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
    7231             :     // If there is a loop-invariant, force it into the RHS.
    7232             :     std::swap(LHS, RHS);
    7233         231 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    7234             :   }
    7235             : 
    7236             :   // Simplify the operands before analyzing them.
    7237       25389 :   (void)SimplifyICmpOperands(Pred, LHS, RHS);
    7238             : 
    7239             :   // If we have a comparison of a chrec against a constant, try to use value
    7240             :   // ranges to answer this query.
    7241       25389 :   if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
    7242       14713 :     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
    7243       10371 :       if (AddRec->getLoop() == L) {
    7244             :         // Form the constant range.
    7245             :         ConstantRange CompRange =
    7246       12437 :             ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
    7247             : 
    7248       10357 :         const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
    7249       10357 :         if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
    7250             :       }
    7251             : 
    7252       17112 :   switch (Pred) {
    7253        9146 :   case ICmpInst::ICMP_NE: {                     // while (X != Y)
    7254             :     // Convert to: while (X-Y != 0)
    7255             :     ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
    7256        9146 :                                 AllowPredicates);
    7257        9146 :     if (EL.hasAnyInfo()) return EL;
    7258             :     break;
    7259             :   }
    7260        1204 :   case ICmpInst::ICMP_EQ: {                     // while (X == Y)
    7261             :     // Convert to: while (X-Y == 0)
    7262        1204 :     ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
    7263        1204 :     if (EL.hasAnyInfo()) return EL;
    7264             :     break;
    7265             :   }
    7266        4941 :   case ICmpInst::ICMP_SLT:
    7267             :   case ICmpInst::ICMP_ULT: {                    // while (X < Y)
    7268        4941 :     bool IsSigned = Pred == ICmpInst::ICMP_SLT;
    7269             :     ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
    7270        4941 :                                     AllowPredicates);
    7271        4941 :     if (EL.hasAnyInfo()) return EL;
    7272             :     break;
    7273             :   }
    7274        1308 :   case ICmpInst::ICMP_SGT:
    7275             :   case ICmpInst::ICMP_UGT: {                    // while (X > Y)
    7276        1308 :     bool IsSigned = Pred == ICmpInst::ICMP_SGT;
    7277             :     ExitLimit EL =
    7278             :         howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
    7279        1308 :                             AllowPredicates);
    7280        1308 :     if (EL.hasAnyInfo()) return EL;
    7281             :     break;
    7282             :   }
    7283             :   default:
    7284             :     break;
    7285             :   }
    7286             : 
    7287             :   auto *ExhaustiveCount =
    7288        8676 :       computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
    7289             : 
    7290        8676 :   if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
    7291          41 :     return ExhaustiveCount;
    7292             : 
    7293             :   return computeShiftCompareExitLimit(ExitCond->getOperand(0),
    7294        8635 :                                       ExitCond->getOperand(1), L, OriginalPred);
    7295             : }
    7296             : 
    7297             : ScalarEvolution::ExitLimit
    7298          36 : ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
    7299             :                                                       SwitchInst *Switch,
    7300             :                                                       BasicBlock *ExitingBlock,
    7301             :                                                       bool ControlsExit) {
    7302             :   assert(!L->contains(ExitingBlock) && "Not an exiting block!");
    7303             : 
    7304             :   // Give up if the exit is the default dest of a switch.
    7305          36 :   if (Switch->getDefaultDest() == ExitingBlock)
    7306          30 :     return getCouldNotCompute();
    7307             : 
    7308             :   assert(L->contains(Switch->getDefaultDest()) &&
    7309             :          "Default case must not exit the loop!");
    7310           6 :   const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
    7311           6 :   const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
    7312             : 
    7313             :   // while (X != Y) --> while (X-Y != 0)
    7314           6 :   ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
    7315           6 :   if (EL.hasAnyInfo())
    7316             :     return EL;
    7317             : 
    7318           5 :   return getCouldNotCompute();
    7319             : }
    7320             : 
    7321             : static ConstantInt *
    7322        8502 : EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
    7323             :                                 ScalarEvolution &SE) {
    7324        8502 :   const SCEV *InVal = SE.getConstant(C);
    7325        8502 :   const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
    7326             :   assert(isa<SCEVConstant>(Val) &&
    7327             :          "Evaluation of SCEV at constant didn't fold correctly?");
    7328        8502 :   return cast<SCEVConstant>(Val)->getValue();
    7329             : }
    7330             : 
    7331             : /// Given an exit condition of 'icmp op load X, cst', try to see if we can
    7332             : /// compute the backedge execution count.
    7333             : ScalarEvolution::ExitLimit
    7334        1853 : ScalarEvolution::computeLoadConstantCompareExitLimit(
    7335             :   LoadInst *LI,
    7336             :   Constant *RHS,
    7337             :   const Loop *L,
    7338             :   ICmpInst::Predicate predicate) {
    7339        1853 :   if (LI->isVolatile()) return getCouldNotCompute();
    7340             : 
    7341             :   // Check to see if the loaded pointer is a getelementptr of a global.
    7342             :   // TODO: Use SCEV instead of manually grubbing with GEPs.
    7343             :   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
    7344         702 :   if (!GEP) return getCouldNotCompute();
    7345             : 
    7346             :   // Make sure that it is really a constant global we are gepping, with an
    7347             :   // initializer, and make sure the first IDX is really 0.
    7348             :   GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
    7349          18 :   if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
    7350           0 :       GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
    7351           0 :       !cast<Constant>(GEP->getOperand(1))->isNullValue())
    7352        1101 :     return getCouldNotCompute();
    7353             : 
    7354             :   // Okay, we allow one non-constant index into the GEP instruction.
    7355             :   Value *VarIdx = nullptr;
    7356             :   std::vector<Constant*> Indexes;
    7357             :   unsigned VarIdxNum = 0;
    7358           0 :   for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
    7359             :     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
    7360           0 :       Indexes.push_back(CI);
    7361           0 :     } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
    7362           0 :       if (VarIdx) return getCouldNotCompute();  // Multiple non-constant idx's.
    7363             :       VarIdx = GEP->getOperand(i);
    7364           0 :       VarIdxNum = i-2;
    7365           0 :       Indexes.push_back(nullptr);
    7366             :     }
    7367             : 
    7368             :   // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
    7369           0 :   if (!VarIdx)
    7370           0 :     return getCouldNotCompute();
    7371             : 
    7372             :   // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
    7373             :   // Check to see if X is a loop variant variable value now.
    7374           0 :   const SCEV *Idx = getSCEV(VarIdx);
    7375           0 :   Idx = getSCEVAtScope(Idx, L);
    7376             : 
    7377             :   // We can only recognize very limited forms of loop index expressions, in
    7378             :   // particular, only affine AddRec's like {C1,+,C2}.
    7379             :   const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
    7380           0 :   if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
    7381           0 :       !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
    7382             :       !isa<SCEVConstant>(IdxExpr->getOperand(1)))
    7383           0 :     return getCouldNotCompute();
    7384             : 
    7385             :   unsigned MaxSteps = MaxBruteForceIterations;
    7386           0 :   for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
    7387           0 :     ConstantInt *ItCst = ConstantInt::get(
    7388           0 :                            cast<IntegerType>(IdxExpr->getType()), IterationNum);
    7389           0 :     ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
    7390             : 
    7391             :     // Form the GEP offset.
    7392           0 :     Indexes[VarIdxNum] = Val;
    7393             : 
    7394           0 :     Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
    7395             :                                                          Indexes);
    7396           0 :     if (!Result) break;  // Cannot compute!
    7397             : 
    7398             :     // Evaluate the condition for this iteration.
    7399           0 :     Result = ConstantExpr::getICmp(predicate, Result, RHS);
    7400           0 :     if (!isa<ConstantInt>(Result)) break;  // Couldn't decide for sure
    7401           0 :     if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
    7402             :       ++NumArrayLenItCounts;
    7403           0 :       return getConstant(ItCst);   // Found terminating iteration!
    7404             :     }
    7405             :   }
    7406           0 :   return getCouldNotCompute();
    7407             : }
    7408             : 
    7409        8635 : ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
    7410             :     Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
    7411             :   ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
    7412             :   if (!RHS)
    7413        4637 :     return getCouldNotCompute();
    7414             : 
    7415        3998 :   const BasicBlock *Latch = L->getLoopLatch();
    7416        3998 :   if (!Latch)
    7417           0 :     return getCouldNotCompute();
    7418             : 
    7419        3998 :   const BasicBlock *Predecessor = L->getLoopPredecessor();
    7420        3998 :   if (!Predecessor)
    7421           3 :     return getCouldNotCompute();
    7422             : 
    7423             :   // Return true if V is of the form "LHS `shift_op` <positive constant>".
    7424             :   // Return LHS in OutLHS and shift_opt in OutOpCode.
    7425             :   auto MatchPositiveShift =
    7426        4202 :       [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
    7427             : 
    7428             :     using namespace PatternMatch;
    7429             : 
    7430             :     ConstantInt *ShiftAmt;
    7431        8404 :     if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
    7432          50 :       OutOpCode = Instruction::LShr;
    7433        8304 :     else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
    7434          62 :       OutOpCode = Instruction::AShr;
    7435        8180 :     else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
    7436           3 :       OutOpCode = Instruction::Shl;
    7437             :     else
    7438             :       return false;
    7439             : 
    7440         230 :     return ShiftAmt->getValue().isStrictlyPositive();
    7441             :   };
    7442             : 
    7443             :   // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
    7444             :   //
    7445             :   // loop:
    7446             :   //   %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
    7447             :   //   %iv.shifted = lshr i32 %iv, <positive constant>
    7448             :   //
    7449             :   // Return true on a successful match.  Return the corresponding PHI node (%iv
    7450             :   // above) in PNOut and the opcode of the shift operation in OpCodeOut.
    7451             :   auto MatchShiftRecurrence =
    7452        3995 :       [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
    7453             :     Optional<Instruction::BinaryOps> PostShiftOpCode;
    7454             : 
    7455             :     {
    7456             :       Instruction::BinaryOps OpC;
    7457             :       Value *V;
    7458             : 
    7459             :       // If we encounter a shift instruction, "peel off" the shift operation,
    7460             :       // and remember that we did so.  Later when we inspect %iv's backedge
    7461             :       // value, we will make sure that the backedge value uses the same
    7462             :       // operation.
    7463             :       //
    7464             :       // Note: the peeled shift operation does not have to be the same
    7465             :       // instruction as the one feeding into the PHI's backedge value.  We only
    7466             :       // really care about it being the same *kind* of shift instruction --
    7467             :       // that's all that is required for our later inferences to hold.
    7468        8044 :       if (MatchPositiveShift(LHS, V, OpC)) {
    7469          54 :         PostShiftOpCode = OpC;
    7470          54 :         LHS = V;
    7471             :       }
    7472             :     }
    7473             : 
    7474        7990 :     PNOut = dyn_cast<PHINode>(LHS);
    7475        4425 :     if (!PNOut || PNOut->getParent() != L->getHeader())
    7476             :       return false;
    7477             : 
    7478         207 :     Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
    7479             :     Value *OpLHS;
    7480             : 
    7481             :     return
    7482             :         // The backedge value for the PHI node must be a shift by a positive
    7483             :         // amount
    7484         268 :         MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
    7485             : 
    7486             :         // of the PHI node itself
    7487         268 :         OpLHS == PNOut &&
    7488             : 
    7489             :         // and the kind of shift should be match the kind of shift we peeled
    7490             :         // off, if any.
    7491         100 :         (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
    7492        3995 :   };
    7493             : 
    7494             :   PHINode *PN;
    7495             :   Instruction::BinaryOps OpCode;
    7496        3995 :   if (!MatchShiftRecurrence(LHS, PN, OpCode))
    7497        3937 :     return getCouldNotCompute();
    7498             : 
    7499          58 :   const DataLayout &DL = getDataLayout();
    7500             : 
    7501             :   // The key rationale for this optimization is that for some kinds of shift
    7502             :   // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
    7503             :   // within a finite number of iterations.  If the condition guarding the
    7504             :   // backedge (in the sense that the backedge is taken if the condition is true)
    7505             :   // is false for the value the shift recurrence stabilizes to, then we know
    7506             :   // that the backedge is taken only a finite number of times.
    7507             : 
    7508             :   ConstantInt *StableValue = nullptr;
    7509          58 :   switch (OpCode) {
    7510           0 :   default:
    7511           0 :     llvm_unreachable("Impossible case!");
    7512             : 
    7513          37 :   case Instruction::AShr: {
    7514             :     // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
    7515             :     // bitwidth(K) iterations.
    7516          37 :     Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
    7517             :     KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
    7518          37 :                                        Predecessor->getTerminator(), &DT);
    7519             :     auto *Ty = cast<IntegerType>(RHS->getType());
    7520          37 :     if (Known.isNonNegative())
    7521          23 :       StableValue = ConstantInt::get(Ty, 0);
    7522          14 :     else if (Known.isNegative())
    7523           9 :       StableValue = ConstantInt::get(Ty, -1, true);
    7524             :     else
    7525           5 :       return getCouldNotCompute();
    7526             : 
    7527          32 :     break;
    7528             :   }
    7529             :   case Instruction::LShr:
    7530             :   case Instruction::Shl:
    7531             :     // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
    7532             :     // stabilize to 0 in at most bitwidth(K) iterations.
    7533          21 :     StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
    7534          21 :     break;
    7535             :   }
    7536             : 
    7537             :   auto *Result =
    7538          53 :       ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
    7539             :   assert(Result->getType()->isIntegerTy(1) &&
    7540             :          "Otherwise cannot be an operand to a branch instruction");
    7541             : 
    7542          53 :   if (Result->isZeroValue()) {
    7543          47 :     unsigned BitWidth = getTypeSizeInBits(RHS->getType());
    7544             :     const SCEV *UpperBound =
    7545          47 :         getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
    7546          47 :     return ExitLimit(getCouldNotCompute(), UpperBound, false);
    7547             :   }
    7548             : 
    7549           6 :   return getCouldNotCompute();
    7550             : }
    7551             : 
    7552             : /// Return true if we can constant fold an instruction of the specified type,
    7553             : /// assuming that all operands were constants.
    7554       81747 : static bool CanConstantFold(const Instruction *I) {
    7555       37365 :   if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
    7556      118522 :       isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
    7557             :       isa<LoadInst>(I))
    7558             :     return true;
    7559             : 
    7560             :   if (const CallInst *CI = dyn_cast<CallInst>(I))
    7561             :     if (const Function *F = CI->getCalledFunction())
    7562        3289 :       return canConstantFoldCallTo(CI, F);
    7563             :   return false;
    7564             : }
    7565             : 
    7566             : /// Determine whether this instruction can constant evolve within this loop
    7567             : /// assuming its operands can all constant evolve.
    7568       57691 : static bool canConstantEvolve(Instruction *I, const Loop *L) {
    7569             :   // An instruction outside of the loop can't be derived from a loop PHI.
    7570       57691 :   if (!L->contains(I)) return false;
    7571             : 
    7572       54344 :   if (isa<PHINode>(I)) {
    7573             :     // We don't currently keep track of the control flow needed to evaluate
    7574             :     // PHIs, so we cannot handle PHIs inside of loops.
    7575        4953 :     return L->getHeader() == I->getParent();
    7576             :   }
    7577             : 
    7578             :   // If we won't be able to constant fold this expression even if the operands
    7579             :   // are constants, bail early.
    7580       49391 :   return CanConstantFold(I);
    7581             : }
    7582             : 
    7583             : /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
    7584             : /// recursing through each instruction operand until reaching a loop header phi.
    7585             : static PHINode *
    7586       20741 : getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
    7587             :                                DenseMap<Instruction *, PHINode *> &PHIMap,
    7588             :                                unsigned Depth) {
    7589       20741 :   if (Depth > MaxConstantEvolvingDepth)
    7590             :     return nullptr;
    7591             : 
    7592             :   // Otherwise, we can evaluate this instruction if all of its operands are
    7593             :   // constant or derived from a PHI node themselves.
    7594             :   PHINode *PHI = nullptr;
    7595       73502 :   for (Value *Op : UseInst->operands()) {
    7596       29765 :     if (isa<Constant>(Op)) continue;
    7597             : 
    7598       23765 :     Instruction *OpInst = dyn_cast<Instruction>(Op);
    7599       37512 :     if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
    7600             : 
    7601       16319 :     PHINode *P = dyn_cast<PHINode>(OpInst);
    7602             :     if (!P)
    7603             :       // If this operand is already visited, reuse the prior result.
    7604             :       // We may have P != PHI if this is the deepest point at which the
    7605             :       // inconsistent paths meet.
    7606             :       P = PHIMap.lookup(OpInst);
    7607        4298 :     if (!P) {
    7608             :       // Recurse and memoize the results, whether a phi is found or not.
    7609             :       // This recursive call invalidates pointers into PHIMap.
    7610       12021 :       P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
    7611       12021 :       PHIMap[OpInst] = P;
    7612             :     }
    7613       16319 :     if (!P)
    7614             :       return nullptr;  // Not evolving from PHI
    7615       10095 :     if (PHI && PHI != P)
    7616             :       return nullptr;  // Evolving from multiple different PHIs.
    7617             :     PHI = P;
    7618             :   }
    7619             :   // This is a expression evolving from a constant PHI!
    7620             :   return PHI;
    7621             : }
    7622             : 
    7623             : /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
    7624             : /// in the loop that V is derived from.  We allow arbitrary operations along the
    7625             : /// way, but the operands of an operation must either be constants or a value
    7626             : /// derived from a constant PHI.  If this expression does not fit with these
    7627             : /// constraints, return null.
    7628        9447 : static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
    7629             :   Instruction *I = dyn_cast<Instruction>(V);
    7630        9197 :   if (!I || !canConstantEvolve(I, L)) return nullptr;
    7631             : 
    7632             :   if (PHINode *PN = dyn_cast<PHINode>(I))
    7633             :     return PN;
    7634             : 
    7635             :   // Record non-constant instructions contained by the loop.
    7636             :   DenseMap<Instruction *, PHINode *> PHIMap;
    7637        8720 :   return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
    7638             : }
    7639             : 
    7640             : /// EvaluateExpression - Given an expression that passes the
    7641             : /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
    7642             : /// in the loop has the value PHIVal.  If we can't fold this expression for some
    7643             : /// reason, return null.
    7644       50030 : static Constant *EvaluateExpression(Value *V, const Loop *L,
    7645             :                                     DenseMap<Instruction *, Constant *> &Vals,
    7646             :                                     const DataLayout &DL,
    7647             :                                     const TargetLibraryInfo *TLI) {
    7648             :   // Convenient constant check, but redundant for recursive calls.
    7649             :   if (Constant *C = dyn_cast<Constant>(V)) return C;
    7650             :   Instruction *I = dyn_cast<Instruction>(V);
    7651             :   if (!I) return nullptr;
    7652             : 
    7653       23854 :   if (Constant *C = Vals.lookup(I)) return C;
    7654             : 
    7655             :   // An instruction inside the loop depends on a value outside the loop that we
    7656             :   // weren't given a mapping for, or a value such as a call inside the loop.
    7657       26107 :   if (!canConstantEvolve(I, L)) return nullptr;
    7658             : 
    7659             :   // An unmapped PHI can be due to a branch or another loop inside this loop,
    7660             :   // or due to this not being the initial iteration through a loop where we
    7661             :   // couldn't compute the evolution of this particular PHI last time.
    7662       26078 :   if (isa<PHINode>(I)) return nullptr;
    7663             : 
    7664       26038 :   std::vector<Constant*> Operands(I->getNumOperands());
    7665             : 
    7666      127956 :   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
    7667      102228 :     Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
    7668       66165 :     if (!Operand) {
    7669       30112 :       Operands[i] = dyn_cast<Constant>(I->getOperand(i));
    7670       15211 :       if (!Operands[i]) return nullptr;
    7671       15051 :       continue;
    7672             :     }
    7673       36058 :     Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
    7674       36058 :     Vals[Operand] = C;
    7675       36058 :     if (!C) return nullptr;
    7676       71816 :     Operands[i] = C;
    7677             :   }
    7678             : 
    7679             :   if (CmpInst *CI = dyn_cast<CmpInst>(I))
    7680        6077 :     return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
    7681       12154 :                                            Operands[1], DL, TLI);
    7682             :   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
    7683         176 :     if (!LI->isVolatile())
    7684         176 :       return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
    7685             :   }
    7686       19630 :   return ConstantFoldInstOperands(I, Operands, DL, TLI);
    7687             : }
    7688             : 
    7689             : 
    7690             : // If every incoming value to PN except the one for BB is a specific Constant,
    7691             : // return that, else return nullptr.
    7692        2327 : static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
    7693             :   Constant *IncomingVal = nullptr;
    7694             : 
    7695        6917 :   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
    7696        3904 :     if (PN->getIncomingBlock(i) == BB)
    7697        1575 :       continue;
    7698             : 
    7699             :     auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
    7700             :     if (!CurrentVal)
    7701             :       return nullptr;
    7702             : 
    7703         720 :     if (IncomingVal != CurrentVal) {
    7704         718 :       if (IncomingVal)
    7705             :         return nullptr;
    7706             :       IncomingVal = CurrentVal;
    7707             :     }
    7708             :   }
    7709             : 
    7710             :   return IncomingVal;
    7711             : }
    7712             : 
    7713             : /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
    7714             : /// in the header of its containing loop, we know the loop executes a
    7715             : /// constant number of times, and the PHI node is just a recurrence
    7716             : /// involving constants, fold it.
    7717             : Constant *
    7718         117 : ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
    7719             :                                                    const APInt &BEs,
    7720             :                                                    const Loop *L) {
    7721         117 :   auto I = ConstantEvolutionLoopExitValue.find(PN);
    7722         117 :   if (I != ConstantEvolutionLoopExitValue.end())
    7723           0 :     return I->second;
    7724             : 
    7725         117 :   if (BEs.ugt(MaxBruteForceIterations))
    7726           7 :     return ConstantEvolutionLoopExitValue[PN] = nullptr;  // Not going to evaluate it.
    7727             : 
    7728             :   Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
    7729             : 
    7730             :   DenseMap<Instruction *, Constant *> CurrentIterVals;
    7731             :   BasicBlock *Header = L->getHeader();
    7732             :   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
    7733             : 
    7734         110 :   BasicBlock *Latch = L->getLoopLatch();
    7735         110 :   if (!Latch)
    7736             :     return nullptr;
    7737             : 
    7738         110 :   for (PHINode &PHI : Header->phis()) {
    7739         346 :     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
    7740         426 :       CurrentIterVals[&PHI] = StartCST;
    7741             :   }
    7742         110 :   if (!CurrentIterVals.count(PN))
    7743          19 :     return RetVal = nullptr;
    7744             : 
    7745          91 :   Value *BEValue = PN->getIncomingValueForBlock(Latch);
    7746             : 
    7747             :   // Execute the loop symbolically to determine the exit value.
    7748             :   assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
    7749             :          "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
    7750             : 
    7751          91 :   unsigned NumIterations = BEs.getZExtValue(); // must be in range
    7752             :   unsigned IterationNum = 0;
    7753          91 :   const DataLayout &DL = getDataLayout();
    7754         443 :   for (; ; ++IterationNum) {
    7755         534 :     if (IterationNum == NumIterations)
    7756         130 :       return RetVal = CurrentIterVals[PN];  // Got exit value!
    7757             : 
    7758             :     // Compute the value of the PHIs for the next iteration.
    7759             :     // EvaluateExpression adds non-phi values to the CurrentIterVals map.
    7760             :     DenseMap<Instruction *, Constant *> NextIterVals;
    7761             :     Constant *NextPHI =
    7762         469 :         EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
    7763         469 :     if (!NextPHI)
    7764             :       return nullptr;        // Couldn't evaluate!
    7765         886 :     NextIterVals[PN] = NextPHI;
    7766             : 
    7767         886 :     bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
    7768             : 
    7769             :     // Also evaluate the other PHI nodes.  However, we don't get to stop if we
    7770             :     // cease to be able to evaluate one of them or if they stop evolving,
    7771             :     // because that doesn't necessarily prevent us from computing PN.
    7772             :     SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
    7773        2552 :     for (const auto &I : CurrentIterVals) {
    7774        3332 :       PHINode *PHI = dyn_cast<PHINode>(I.first);
    7775        2949 :       if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
    7776         383 :       PHIsToCompute.emplace_back(PHI, I.second);
    7777             :     }
    7778             :     // We use two distinct loops because EvaluateExpression may invalidate any
    7779             :     // iterators into CurrentIterVals.
    7780        1209 :     for (const auto &I : PHIsToCompute) {
    7781         383 :       PHINode *PHI = I.first;
    7782         766 :       Constant *&NextPHI = NextIterVals[PHI];
    7783         383 :       if (!NextPHI) {   // Not already computed.
    7784         383 :         Value *BEValue = PHI->getIncomingValueForBlock(Latch);
    7785         383 :         NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
    7786             :       }
    7787         383 :       if (NextPHI != I.second)
    7788             :         StoppedEvolving = false;
    7789             :     }
    7790             : 
    7791             :     // If all entries in CurrentIterVals == NextIterVals then we can stop
    7792             :     // iterating, the loop can't continue to change.
    7793         443 :     if (StoppedEvolving)
    7794           0 :       return RetVal = CurrentIterVals[PN];
    7795             : 
    7796             :     CurrentIterVals.swap(NextIterVals);
    7797         443 :   }
    7798             : }
    7799             : 
    7800        9447 : const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
    7801             :                                                           Value *Cond,
    7802             :                                                           bool ExitWhen) {
    7803        9447 :   PHINode *PN = getConstantEvolvingPHI(Cond, L);
    7804        9447 :   if (!PN) return getCouldNotCompute();
    7805             : 
    7806             :   // If the loop is canonicalized, the PHI will have exactly two entries.
    7807             :   // That's the only form we support here.
    7808        1111 :   if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
    7809             : 
    7810             :   DenseMap<Instruction *, Constant *> CurrentIterVals;
    7811             :   BasicBlock *Header = L->getHeader();
    7812             :   assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
    7813             : 
    7814        1108 :   BasicBlock *Latch = L->getLoopLatch();
    7815             :   assert(Latch && "Should follow from NumIncomingValues == 2!");
    7816             : 
    7817        1108 :   for (PHINode &PHI : Header->phis()) {
    7818        1981 :     if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
    7819        1010 :       CurrentIterVals[&PHI] = StartCST;
    7820             :   }
    7821             :   if (!CurrentIterVals.count(PN))
    7822         954 :     return getCouldNotCompute();
    7823             : 
    7824             :   // Okay, we find a PHI node that defines the trip count of this loop.  Execute
    7825             :   // the loop symbolically to determine when the condition gets a value of
    7826             :   // "ExitWhen".
    7827             :   unsigned MaxIterations = MaxBruteForceIterations;   // Limit analysis.
    7828         154 :   const DataLayout &DL = getDataLayout();
    7829       11746 :   for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
    7830        5895 :     auto *CondVal = dyn_cast_or_null<ConstantInt>(
    7831        5895 :         EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
    7832             : 
    7833             :     // Couldn't symbolically evaluate.
    7834         154 :     if (!CondVal) return getCouldNotCompute();
    7835             : 
    7836       11680 :     if (CondVal->getValue() == uint64_t(ExitWhen)) {
    7837             :       ++NumBruteForceTripCountsComputed;
    7838          88 :       return getConstant(Type::getInt32Ty(getContext()), IterationNum);
    7839             :     }
    7840             : 
    7841             :     // Update all the PHI nodes for the next iteration.
    7842             :     DenseMap<Instruction *, Constant *> NextIterVals;
    7843             : 
    7844             :     // Create a list of which PHIs we need to compute. We want to do this before
    7845             :     // calling EvaluateExpression on them because that may invalidate iterators
    7846             :     // into CurrentIterVals.
    7847             :     SmallVector<PHINode *, 8> PHIsToCompute;
    7848       32572 :     for (const auto &I : CurrentIterVals) {
    7849       41960 :       PHINode *PHI = dyn_cast<PHINode>(I.first);
    7850       34735 :       if (!PHI || PHI->getParent() != Header) continue;
    7851        7225 :       PHIsToCompute.push_back(PHI);
    7852             :     }
    7853       20246 :     for (PHINode *PHI : PHIsToCompute) {
    7854       14450 :       Constant *&NextPHI = NextIterVals[PHI];
    7855        7225 :       if (NextPHI) continue;    // Already computed!
    7856             : 
    7857        7225 :       Value *BEValue = PHI->getIncomingValueForBlock(Latch);
    7858        7225 :       NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
    7859             :     }
    7860             :     CurrentIterVals.swap(NextIterVals);
    7861             :   }
    7862             : 
    7863             :   // Too many iterations were needed to evaluate.
    7864          55 :   return getCouldNotCompute();
    7865             : }
    7866             : 
    7867      533124 : const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
    7868             :   SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
    7869      533124 :       ValuesAtScopes[V];
    7870             :   // Check to see if we've folded this expression at this loop before.
    7871     1622280 :   for (auto &LS : Values)
    7872      846626 :     if (LS.first == L)
    7873      302048 :       return LS.second ? LS.second : V;
    7874             : 
    7875      231076 :   Values.emplace_back(L, nullptr);
    7876             : 
    7877             :   // Otherwise compute it.
    7878      231076 :   const SCEV *C = computeSCEVAtScope(V, L);
    7879      231114 :   for (auto &LS : reverse(ValuesAtScopes[V]))
    7880      230410 :     if (LS.first == L) {
    7881      230372 :       LS.second = C;
    7882      230372 :       break;
    7883             :     }
    7884             :   return C;
    7885             : }
    7886             : 
    7887             : /// This builds up a Constant using the ConstantExpr interface.  That way, we
    7888             : /// will return Constants for objects which aren't represented by a
    7889             : /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
    7890             : /// Returns NULL if the SCEV isn't representable as a Constant.
    7891       40814 : static Constant *BuildConstantFromSCEV(const SCEV *V) {
    7892       40814 :   switch (static_cast<SCEVTypes>(V->getSCEVType())) {
    7893             :     case scCouldNotCompute:
    7894             :     case scAddRecExpr:
    7895             :       break;
    7896             :     case scConstant:
    7897        7852 :       return cast<SCEVConstant>(V)->getValue();
    7898             :     case scUnknown:
    7899             :       return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
    7900             :     case scSignExtend: {
    7901             :       const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
    7902         333 :       if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
    7903           0 :         return ConstantExpr::getSExt(CastOp, SS->getType());
    7904             :       break;
    7905             :     }
    7906             :     case scZeroExtend: {
    7907             :       const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
    7908         315 :       if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
    7909           5 :         return ConstantExpr::getZExt(CastOp, SZ->getType());
    7910             :       break;
    7911             :     }
    7912             :     case scTruncate: {
    7913             :       const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
    7914         115 :       if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
    7915           2 :         return ConstantExpr::getTrunc(CastOp, ST->getType());
    7916             :       break;
    7917             :     }
    7918             :     case scAddExpr: {
    7919             :       const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
    7920       15684 :       if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
    7921        5996 :         if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
    7922             :           unsigned AS = PTy->getAddressSpace();
    7923           0 :           Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
    7924           0 :           C = ConstantExpr::getBitCast(C, DestPtrTy);
    7925             :         }
    7926        6012 :         for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
    7927       11994 :           Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
    7928        5997 :           if (!C2) return nullptr;
    7929             : 
    7930             :           // First pointer!
    7931          48 :           if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
    7932             :             unsigned AS = C2->getType()->getPointerAddressSpace();
    7933             :             std::swap(C, C2);
    7934          13 :             Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
    7935             :             // The offsets have been converted to bytes.  We can add bytes to an
    7936             :             // i8* by GEP with the byte count in the first index.
    7937          13 :             C = ConstantExpr::getBitCast(C, DestPtrTy);
    7938             :           }
    7939             : 
    7940             :           // Don't bother trying to sum two pointers. We probably can't
    7941             :           // statically compute a load that results from it anyway.
    7942          32 :           if (C2->getType()->isPointerTy())
    7943             :             return nullptr;
    7944             : 
    7945          16 :           if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
    7946          26 :             if (PTy->getElementType()->isStructTy())
    7947           0 :               C2 = ConstantExpr::getIntegerCast(
    7948           0 :                   C2, Type::getInt32Ty(C->getContext()), true);
    7949          13 :             C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
    7950             :           } else
    7951           3 :             C = ConstantExpr::getAdd(C, C2);
    7952             :         }
    7953             :         return C;
    7954             :       }
    7955             :       break;
    7956             :     }
    7957             :     case scMulExpr: {
    7958             :       const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
    7959        3604 :       if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
    7960             :         // Don't bother with pointers at all.
    7961        3548 :         if (C->getType()->isPointerTy()) return nullptr;
    7962        1777 :         for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
    7963        3548 :           Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
    7964        1777 :           if (!C2 || C2->getType()->isPointerTy()) return nullptr;
    7965           3 :           C = ConstantExpr::getMul(C, C2);
    7966             :         }
    7967             :         return C;
    7968             :       }
    7969             :       break;
    7970             :     }
    7971             :     case scUDivExpr: {
    7972             :       const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
    7973         276 :       if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
    7974           8 :         if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
    7975           2 :           if (LHS->getType() == RHS->getType())
    7976           2 :             return ConstantExpr::getUDiv(LHS, RHS);
    7977             :       break;
    7978             :     }
    7979             :     case scSMaxExpr:
    7980             :     case scUMaxExpr:
    7981             :       break; // TODO: smax, umax.
    7982             :   }
    7983             :   return nullptr;
    7984             : }
    7985             : 
    7986      231076 : const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
    7987      231076 :   if (isa<SCEVConstant>(V)) return V;
    7988             : 
    7989             :   // If this instruction is evolved from a constant-evolving PHI, compute the
    7990             :   // exit value from the loop without using SCEVs.
    7991       53618 :   if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
    7992             :     if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
    7993       32447 :       const Loop *LI = this->LI[I->getParent()];
    7994       19373 :       if (LI && LI->getParentLoop() == L)  // Looking for loop exit value.
    7995             :         if (PHINode *PN = dyn_cast<PHINode>(I))
    7996         662 :           if (PN->getParent() == LI->getHeader()) {
    7997             :             // Okay, there is no closed form solution for the PHI node.  Check
    7998             :             // to see if the loop that contains it has a known backedge-taken
    7999             :             // count.  If so, we may be able to force computation of the exit
    8000             :             // value.
    8001         263 :             const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
    8002             :             if (const SCEVConstant *BTCC =
    8003             :                   dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
    8004             : 
    8005             :               // This trivial case can show up in some degenerate cases where
    8006             :               // the incoming IR has not yet been fully simplified.
    8007         286 :               if (BTCC->getValue()->isZero()) {
    8008             :                 Value *InitValue = nullptr;
    8009             :                 bool MultipleInitValues = false;
    8010          66 :                 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
    8011          46 :                   if (!LI->contains(PN->getIncomingBlock(i))) {
    8012          26 :                     if (!InitValue)
    8013             :                       InitValue = PN->getIncomingValue(i);
    8014           0 :                     else if (InitValue != PN->getIncomingValue(i)) {
    8015             :                       MultipleInitValues = true;
    8016             :                       break;
    8017             :                     }
    8018             :                   }
    8019          46 :                   if (!MultipleInitValues && InitValue)
    8020          26 :                     return getSCEV(InitValue);
    8021             :                 }
    8022             :               }
    8023             :               // Okay, we know how many times the containing loop executes.  If
    8024             :               // this is a constant evolving PHI node, get the final value at
    8025             :               // the specified iteration number.
    8026             :               Constant *RV =
    8027         117 :                   getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
    8028         117 :               if (RV) return getSCEV(RV);
    8029             :             }
    8030             :           }
    8031             : 
    8032             :       // Okay, this is an expression that we cannot symbolically evaluate
    8033             :       // into a SCEV.  Check to see if it's possible to symbolically evaluate
    8034             :       // the arguments into constants, and if so, try to constant propagate the
    8035             :       // result.  This is particularly useful for computing loop exit values.
    8036       32356 :       if (CanConstantFold(I)) {
    8037             :         SmallVector<Constant *, 4> Operands;
    8038             :         bool MadeImprovement = false;
    8039       49736 :         for (Value *Op : I->operands()) {
    8040       25100 :           if (Constant *C = dyn_cast<Constant>(Op)) {
    8041        1305 :             Operands.push_back(C);
    8042        1305 :             continue;
    8043             :           }
    8044             : 
    8045             :           // If any of the operands is non-constant and if they are
    8046             :           // non-integer and non-pointer, don't even try to analyze them
    8047             :           // with scev techniques.
    8048       22490 :           if (!isSCEVable(Op->getType()))
    8049       22377 :             return V;
    8050             : 
    8051       22352 :           const SCEV *OrigV = getSCEV(Op);
    8052       22352 :           const SCEV *OpV = getSCEVAtScope(OrigV, L);
    8053       22352 :           MadeImprovement |= OrigV != OpV;
    8054             : 
    8055       22352 :           Constant *C = BuildConstantFromSCEV(OpV);
    8056       22352 :           if (!C) return V;
    8057         113 :           if (C->getType() != Op->getType())
    8058          21 :             C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
    8059             :                                                               Op->getType(),
    8060             :                                                               false),
    8061             :                                       C, Op->getType());
    8062         113 :           Operands.push_back(C);
    8063             :         }
    8064             : 
    8065             :         // Check to see if getSCEVAtScope actually made an improvement.
    8066        1073 :         if (MadeImprovement) {
    8067             :           Constant *C = nullptr;
    8068          37 :           const DataLayout &DL = getDataLayout();
    8069             :           if (const CmpInst *CI = dyn_cast<CmpInst>(I))
    8070          26 :             C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
    8071          13 :                                                 Operands[1], DL, &TLI);
    8072             :           else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
    8073          12 :             if (!LI->isVolatile())
    8074          24 :               C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
    8075             :           } else
    8076          24 :             C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
    8077          37 :           if (!C) return V;
    8078          31 :           return getSCEV(C);
    8079             :         }
    8080             :       }
    8081             :     }
    8082             : 
    8083             :     // This is some other type of SCEVUnknown, just return it.
    8084             :     return V;
    8085             :   }
    8086             : 
    8087             :   if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
    8088             :     // Avoid performing the look-up in the common case where the specified
    8089             :     // expression has no loop-variant portions.
    8090      152199 :     for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
    8091      229662 :       const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
    8092      229662 :       if (OpAtScope != Comm->getOperand(i)) {
    8093             :         // Okay, at least one of these operands is loop variant but might be
    8094             :         // foldable.  Build a new instance of the folded commutative expression.
    8095             :         SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
    8096             :                                             Comm->op_begin()+i);
    8097       18391 :         NewOps.push_back(OpAtScope);
    8098             : 
    8099       31314 :         for (++i; i != e; ++i) {
    8100       25846 :           OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
    8101       12923 :           NewOps.push_back(OpAtScope);
    8102             :         }
    8103       18391 :         if (isa<SCEVAddExpr>(Comm))
    8104        4242 :           return getAddExpr(NewOps);
    8105       14149 :         if (isa<SCEVMulExpr>(Comm))
    8106       14142 :           return getMulExpr(NewOps);
    8107           7 :         if (isa<SCEVSMaxExpr>(Comm))
    8108           4 :           return getSMaxExpr(NewOps);
    8109           3 :         if (isa<SCEVUMaxExpr>(Comm))
    8110           3 :           return getUMaxExpr(NewOps);
    8111           0 :         llvm_unreachable("Unknown commutative SCEV type!");
    8112             :       }
    8113             :     }
    8114             :     // If we got here, all operands are loop invariant.
    8115             :     return Comm;
    8116             :   }
    8117             : 
    8118             :   if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
    8119        2156 :     const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
    8120        2156 :     const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
    8121        2156 :     if (LHS == Div->getLHS() && RHS == Div->getRHS())
    8122             :       return Div;   // must be loop invariant
    8123           8 :     return getUDivExpr(LHS, RHS);
    8124             :   }
    8125             : 
    8126             :   // If this is a loop recurrence for a loop that does not contain L, then we
    8127             :   // are dealing with the final value computed by the loop.
    8128             :   if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
    8129             :     // First, attempt to evaluate each operand.
    8130             :     // Avoid performing the look-up in the common case where the specified
    8131             :     // expression has no loop-variant portions.
    8132      132852 :     for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
    8133      180026 :       const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
    8134      180026 :       if (OpAtScope == AddRec->getOperand(i))
    8135       86633 :         continue;
    8136             : 
    8137             :       // Okay, at least one of these operands is loop variant but might be
    8138             :       // foldable.  Build a new instance of the folded commutative expression.
    8139             :       SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
    8140             :                                           AddRec->op_begin()+i);
    8141        3380 :       NewOps.push_back(OpAtScope);
    8142       10232 :       for (++i; i != e; ++i)
    8143       13704 :         NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
    8144             : 
    8145             :       const SCEV *FoldedRec =
    8146        6760 :         getAddRecExpr(NewOps, AddRec->getLoop(),
    8147        3380 :                       AddRec->getNoWrapFlags(SCEV::FlagNW));
    8148             :       AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
    8149             :       // The addrec may be folded to a nonrecurrence, for example, if the
    8150             :       // induction variable is multiplied by zero after constant folding. Go
    8151             :       // ahead and return the folded value.
    8152             :       if (!AddRec)
    8153             :         return FoldedRec;
    8154             :       break;
    8155             :     }
    8156             : 
    8157             :     // If the scope is outside the addrec's loop, evaluate it by using the
    8158             :     // loop exit value of the addrec.
    8159       90418 :     if (!AddRec->getLoop()->contains(L)) {
    8160             :       // To evaluate this recurrence, we need to know how many times the AddRec
    8161             :       // loop iterates.  Compute this now.
    8162        4425 :       const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
    8163        4425 :       if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
    8164             : 
    8165             :       // Then, evaluate the AddRec.
    8166        3918 :       return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
    8167             :     }
    8168             : 
    8169             :     return AddRec;
    8170             :   }
    8171             : 
    8172             :   if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
    8173        2014 :     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
    8174        2014 :     if (Op == Cast->getOperand())
    8175             :       return Cast;  // must be loop invariant
    8176          18 :     return getZeroExtendExpr(Op, Cast->getType());
    8177             :   }
    8178             : 
    8179             :   if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
    8180        1893 :     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
    8181        1893 :     if (Op == Cast->getOperand())
    8182             :       return Cast;  // must be loop invariant
    8183          43 :     return getSignExtendExpr(Op, Cast->getType());
    8184             :   }
    8185             : 
    8186             :   if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
    8187        1383 :     const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
    8188        1383 :     if (Op == Cast->getOperand())
    8189             :       return Cast;  // must be loop invariant
    8190           9 :     return getTruncateExpr(Op, Cast->getType());
    8191             :   }
    8192             : 
    8193           0 :   llvm_unreachable("Unknown SCEV type!");
    8194             : }
    8195             : 
    8196      210328 : const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
    8197      210328 :   return getSCEVAtScope(getSCEV(V), L);
    8198             : }
    8199             : 
    8200        9138 : const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
    8201             :   if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
    8202          47 :     return stripInjectiveFunctions(ZExt->getOperand());
    8203             :   if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
    8204           0 :     return stripInjectiveFunctions(SExt->getOperand());
    8205             :   return S;
    8206             : }
    8207             : 
    8208             : /// Finds the minimum unsigned root of the following equation:
    8209             : ///
    8210             : ///     A * X = B (mod N)
    8211             : ///
    8212             : /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
    8213             : /// A and B isn't important.
    8214             : ///
    8215             : /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
    8216        1698 : static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
    8217             :                                                ScalarEvolution &SE) {
    8218        1698 :   uint32_t BW = A.getBitWidth();
    8219             :   assert(BW == SE.getTypeSizeInBits(B->getType()));
    8220             :   assert(A != 0 && "A must be non-zero.");
    8221             : 
    8222             :   // 1. D = gcd(A, N)
    8223             :   //
    8224             :   // The gcd of A and N may have only one prime factor: 2. The number of
    8225             :   // trailing zeros in A is its multiplicity
    8226        1698 :   uint32_t Mult2 = A.countTrailingZeros();
    8227             :   // D = 2^Mult2
    8228             : 
    8229             :   // 2. Check if B is divisible by D.
    8230             :   //
    8231             :   // B is divisible by D if and only if the multiplicity of prime factor 2 for B
    8232             :   // is not less than multiplicity of this prime factor for D.
    8233        1698 :   if (SE.GetMinTrailingZeros(B) < Mult2)
    8234        1525 :     return SE.getCouldNotCompute();
    8235             : 
    8236             :   // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
    8237             :   // modulo (N / D).
    8238             :   //
    8239             :   // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
    8240             :   // (N / D) in general. The inverse itself always fits into BW bits, though,
    8241             :   // so we immediately truncate it.
    8242         346 :   APInt AD = A.lshr(Mult2).zext(BW + 1);  // AD = A / D
    8243             :   APInt Mod(BW + 1, 0);
    8244         173 :   Mod.setBit(BW - Mult2);  // Mod = N / D
    8245         346 :   APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
    8246             : 
    8247             :   // 4. Compute the minimum unsigned root of the equation:
    8248             :   // I * (B / D) mod (N / D)
    8249             :   // To simplify the computation, we factor out the divide by D:
    8250             :   // (I * B mod N) / D
    8251         346 :   const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
    8252         173 :   return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
    8253             : }
    8254             : 
    8255             : /// Find the roots of the quadratic equation for the given quadratic chrec
    8256             : /// {L,+,M,+,N}.  This returns either the two roots (which might be the same) or
    8257             : /// two SCEVCouldNotCompute objects.
    8258             : static Optional<std::pair<const SCEVConstant *,const SCEVConstant *>>
    8259          24 : SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
    8260             :   assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
    8261          24 :   const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
    8262             :   const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
    8263             :   const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
    8264             : 
    8265             :   // We currently can only solve this if the coefficients are constants.
    8266          24 :   if (!LC || !MC || !NC)
    8267             :     return None;
    8268             : 
    8269          24 :   uint32_t BitWidth = LC->getAPInt().getBitWidth();
    8270             :   const APInt &L = LC->getAPInt();
    8271             :   const APInt &M = MC->getAPInt();
    8272             :   const APInt &N = NC->getAPInt();
    8273             :   APInt Two(BitWidth, 2);
    8274             : 
    8275             :   // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
    8276             : 
    8277             :   // The A coefficient is N/2
    8278          24 :   APInt A = N.sdiv(Two);
    8279             : 
    8280             :   // The B coefficient is M-N/2
    8281             :   APInt B = M;
    8282          24 :   B -= A; // A is the same as N/2.
    8283             : 
    8284             :   // The C coefficient is L.
    8285             :   const APInt& C = L;
    8286             : 
    8287             :   // Compute the B^2-4ac term.
    8288             :   APInt SqrtTerm = B;
    8289          24 :   SqrtTerm *= B;
    8290          96 :   SqrtTerm -= 4 * (A * C);
    8291             : 
    8292          48 :   if (SqrtTerm.isNegative()) {
    8293             :     // The loop is provably infinite.
    8294             :     return None;
    8295             :   }
    8296             : 
    8297             :   // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
    8298             :   // integer value or else APInt::sqrt() will assert.
    8299          21 :   APInt SqrtVal = SqrtTerm.sqrt();
    8300             : 
    8301             :   // Compute the two solutions for the quadratic formula.
    8302             :   // The divisions must be performed as signed divisions.
    8303          21 :   APInt NegB = -std::move(B);
    8304             :   APInt TwoA = std::move(A);
    8305          21 :   TwoA <<= 1;
    8306          21 :   if (TwoA.isNullValue())
    8307             :     return None;
    8308             : 
    8309          12 :   LLVMContext &Context = SE.getContext();
    8310             : 
    8311             :   ConstantInt *Solution1 =
    8312          48 :     ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
    8313             :   ConstantInt *Solution2 =
    8314          48 :     ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
    8315             : 
    8316          12 :   return std::make_pair(cast<SCEVConstant>(SE.getConstant(Solution1)),
    8317          12 :                         cast<SCEVConstant>(SE.getConstant(Solution2)));
    8318             : }
    8319             : 
    8320             : ScalarEvolution::ExitLimit
    8321        9152 : ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
    8322             :                               bool AllowPredicates) {
    8323             : 
    8324             :   // This is only used for loops with a "x != y" exit test. The exit condition
    8325             :   // is now expressed as a single expression, V = x-y. So the exit test is
    8326             :   // effectively V != 0.  We know and take advantage of the fact that this
    8327             :   // expression only being used in a comparison by zero context.
    8328             : 
    8329             :   SmallPtrSet<const SCEVPredicate *, 4> Predicates;
    8330             :   // If the value is a constant
    8331             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
    8332             :     // If the value is already zero, the branch will execute zero times.
    8333          28 :     if (C->getValue()->isZero()) return C;
    8334           0 :     return getCouldNotCompute();  // Otherwise it will loop infinitely.
    8335             :   }
    8336             : 
    8337             :   const SCEVAddRecExpr *AddRec =
    8338        9138 :       dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
    8339             : 
    8340        9138 :   if (!AddRec && AllowPredicates)
    8341             :     // Try to make this an AddRec using runtime tests, in the first X
    8342             :     // iterations of this loop, where X is the SCEV expression found by the
    8343             :     // algorithm below.
    8344         422 :     AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
    8345             : 
    8346        9138 :   if (!AddRec || AddRec->getLoop() != L)
    8347        3431 :     return getCouldNotCompute();
    8348             : 
    8349             :   // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
    8350             :   // the quadratic equation to solve it.
    8351        5716 :   if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
    8352           9 :     if (auto Roots = SolveQuadraticEquation(AddRec, *this)) {
    8353           3 :       const SCEVConstant *R1 = Roots->first;
    8354           3 :       const SCEVConstant *R2 = Roots->second;
    8355             :       // Pick the smallest positive root value.
    8356           3 :       if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
    8357           3 :               CmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
    8358           3 :         if (!CB->getZExtValue())
    8359             :           std::swap(R1, R2); // R1 is the minimum root now.
    8360             : 
    8361             :         // We can only use this value if the chrec ends up with an exact zero
    8362             :         // value at this index.  When solving for "X*X != 5", for example, we
    8363             :         // should not accept a root of 2.
    8364           3 :         const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
    8365           3 :         if (Val->isZero())
    8366             :           // We found a quadratic root!
    8367           0 :           return ExitLimit(R1, R1, false, Predicates);
    8368             :       }
    8369             :     }
    8370           9 :     return getCouldNotCompute();
    8371             :   }
    8372             : 
    8373             :   // Otherwise we can only handle this if it is affine.
    8374        5698 :   if (!AddRec->isAffine())
    8375           0 :     return getCouldNotCompute();
    8376             : 
    8377             :   // If this is an affine expression, the execution count of this branch is
    8378             :   // the minimum unsigned root of the following equation:
    8379             :   //
    8380             :   //     Start + Step*N = 0 (mod 2^BW)
    8381             :   //
    8382             :   // equivalent to:
    8383             :   //
    8384             :   //             Step*N = -Start (mod 2^BW)
    8385             :   //
    8386             :   // where BW is the common bit width of Start and Step.
    8387             : 
    8388             :   // Get the initial value for the loop.
    8389       11396 :   const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
    8390       11396 :   const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
    8391             : 
    8392             :   // For now we handle only constant steps.
    8393             :   //
    8394             :   // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
    8395             :   // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
    8396             :   // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
    8397             :   // We have not yet seen any such cases.
    8398             :   const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
    8399       11338 :   if (!StepC || StepC->getValue()->isZero())
    8400          32 :     return getCouldNotCompute();
    8401             : 
    8402             :   // For positive steps (counting up until unsigned overflow):
    8403             :   //   N = -Start/Step (as unsigned)
    8404             :   // For negative steps (counting down to zero):
    8405             :   //   N = Start/-Step
    8406             :   // First compute the unsigned distance from zero in the direction of Step.
    8407        5666 :   bool CountDown = StepC->getAPInt().isNegative();
    8408        5666 :   const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
    8409             : 
    8410             :   // Handle unitary steps, which cannot wraparound.
    8411             :   // 1*N = -Start; -1*N = Start (mod 2^BW), so:
    8412             :   //   N = Distance (as unsigned)
    8413       14278 :   if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
    8414             :     APInt MaxBECount = getUnsignedRangeMax(Distance);
    8415             : 
    8416             :     // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
    8417             :     // we end up with a loop whose backedge-taken count is n - 1.  Detect this
    8418             :     // case, and see if we can improve the bound.
    8419             :     //
    8420             :     // Explicitly handling this here is necessary because getUnsignedRange
    8421             :     // isn't context-sensitive; it doesn't know that we only care about the
    8422             :     // range inside the loop.
    8423        3471 :     const SCEV *Zero = getZero(Distance->getType());
    8424        3471 :     const SCEV *One = getOne(Distance->getType());
    8425        3471 :     const SCEV *DistancePlusOne = getAddExpr(Distance, One);
    8426        3471 :     if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
    8427             :       // If Distance + 1 doesn't overflow, we can compute the maximum distance
    8428             :       // as "unsigned_max(Distance + 1) - 1".
    8429        2189 :       ConstantRange CR = getUnsignedRange(DistancePlusOne);
    8430        8756 :       MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
    8431             :     }
    8432        3471 :     return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
    8433             :   }
    8434             : 
    8435             :   // If the condition controls loop exit (the loop exits only if the expression
    8436             :   // is true) and the addition is no-wrap we can use unsigned divide to
    8437             :   // compute the backedge count.  In this case, the step may not divide the
    8438             :   // distance, but we don't care because if the condition is "missed" the loop
    8439             :   // will have undefined behavior due to wrapping.
    8440        5528 :   if (ControlsExit && AddRec->hasNoSelfWrap() &&
    8441        1366 :       loopHasNoAbnormalExits(AddRec->getLoop())) {
    8442             :     const SCEV *Exact =
    8443         497 :         getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
    8444             :     const SCEV *Max =
    8445         497 :         Exact == getCouldNotCompute()
    8446         994 :             ? Exact
    8447         497 :             : getConstant(getUnsignedRangeMax(Exact));
    8448         497 :     return ExitLimit(Exact, Max, false, Predicates);
    8449             :   }
    8450             : 
    8451             :   // Solve the general equation.
    8452        1698 :   const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
    8453        1698 :                                                getNegativeSCEV(Start), *this);
    8454        1698 :   const SCEV *M = E == getCouldNotCompute()
    8455        1871 :                       ? E
    8456        1698 :                       : getConstant(getUnsignedRangeMax(E));
    8457        1698 :   return ExitLimit(E, M, false, Predicates);
    8458             : }
    8459             : 
    8460             : ScalarEvolution::ExitLimit
    8461        1204 : ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
    8462             :   // Loops that look like: while (X == 0) are very strange indeed.  We don't
    8463             :   // handle them yet except for the trivial case.  This could be expanded in the
    8464             :   // future as needed.
    8465             : 
    8466             :   // If the value is a constant, check to see if it is known to be non-zero
    8467             :   // already.  If so, the backedge will execute zero times.
    8468             :   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
    8469          44 :     if (!C->getValue()->isZero())
    8470           0 :       return getZero(C->getType());
    8471          22 :     return getCouldNotCompute();  // Otherwise it will loop infinitely.
    8472             :   }
    8473             : 
    8474             :   // We could implement others, but I really doubt anyone writes loops like
    8475             :   // this, and if they did, they would already be constant folded.
    8476        1182 :   return getCouldNotCompute();
    8477             : }
    8478             : 
    8479             : std::pair<BasicBlock *, BasicBlock *>
    8480       48321 : ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
    8481             :   // If the block has a unique predecessor, then there is no path from the
    8482             :   // predecessor to the block that does not go through the direct edge
    8483             :   // from the predecessor to the block.
    8484       48321 :   if (BasicBlock *Pred = BB->getSinglePredecessor())
    8485       24409 :     return {Pred, BB};
    8486             : 
    8487             :   // A loop's header is defined to be a block that dominates the loop.
    8488             :   // If the header has a unique predecessor outside the loop, it must be
    8489             :   // a block that has exactly one successor that can reach the loop.
    8490       32302 :   if (Loop *L = LI.getLoopFor(BB))
    8491       16780 :     return {L->getLoopPredecessor(), L->getHeader()};
    8492             : 
    8493       15522 :   return {nullptr, nullptr};
    8494             : }
    8495             : 
    8496             : /// SCEV structural equivalence is usually sufficient for testing whether two
    8497             : /// expressions are equal, however for the purposes of looking for a condition
    8498             : /// guarding a loop, it can be useful to be a little more general, since a
    8499             : /// front-end may have replicated the controlling expression.
    8500      485085 : static bool HasSameValue(const SCEV *A, const SCEV *B) {
    8501             :   // Quick check to see if they are the same SCEV.
    8502      485085 :   if (A == B) return true;
    8503             : 
    8504        6188 :   auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
    8505             :     // Not all instructions that are "identical" compute the same value.  For
    8506             :     // instance, two distinct alloca instructions allocating the same type are
    8507             :     // identical and do not read memory; but compute distinct values.
    8508        6263 :     return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
    8509        6188 :   };
    8510             : 
    8511             :   // Otherwise, if they're both SCEVUnknown, it's possible that they hold
    8512             :   // two different instructions with the same value. Check for this case.
    8513       70104 :   if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
    8514       10842 :     if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
    8515             :       if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
    8516             :         if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
    8517        6188 :           if (ComputesEqualValues(AI, BI))
    8518             :             return true;
    8519             : 
    8520             :   // Otherwise assume they may have a different value.
    8521             :   return false;
    8522             : }
    8523             : 
    8524      258614 : bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
    8525             :                                            const SCEV *&LHS, const SCEV *&RHS,
    8526             :                                            unsigned Depth) {
    8527             :   bool Changed = false;
    8528             : 
    8529             :   // If we hit the max recursion limit bail out.
    8530      258614 :   if (Depth >= 3)
    8531             :     return false;
    8532             : 
    8533             :   // Canonicalize a constant to the right side.
    8534      258614 :   if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
    8535             :     // Check for both operands constant.
    8536       24256 :     if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
    8537       19678 :       if (ConstantExpr::getICmp(Pred,
    8538        9839 :                                 LHSC->getValue(),
    8539       19678 :                                 RHSC->getValue())->isNullValue())
    8540             :         goto trivially_false;
    8541             :       else
    8542             :         goto trivially_true;
    8543             :     }
    8544             :     // Otherwise swap the operands to put the constant on the right.
    8545             :     std::swap(LHS, RHS);
    8546       14417 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    8547             :     Changed = true;
    8548             :   }
    8549             : 
    8550             :   // If we're comparing an addrec with a value which is loop-invariant in the
    8551             :   // addrec's loop, put the addrec on the left. Also make a dominance check,
    8552             :   // as both operands could be addrecs loop-invariant in each other's loop.
    8553      248775 :   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
    8554        1434 :     const Loop *L = AR->getLoop();
    8555        1638 :     if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
    8556             :       std::swap(LHS, RHS);
    8557         204 :       Pred = ICmpInst::getSwappedPredicate(Pred);
    8558             :       Changed = true;
    8559             :     }
    8560             :   }
    8561             : 
    8562             :   // If there's a constant operand, canonicalize comparisons with boundary
    8563             :   // cases, and canonicalize *-or-equal comparisons to regular comparisons.
    8564      248775 :   if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
    8565             :     const APInt &RA = RC->getAPInt();
    8566             : 
    8567             :     bool SimplifiedByConstantRange = false;
    8568             : 
    8569      398108 :     if (!ICmpInst::isEquality(Pred)) {
    8570      251690 :       ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
    8571      125911 :       if (ExactCR.isFullSet())
    8572             :         goto trivially_true;
    8573      125902 :       else if (ExactCR.isEmptySet())
    8574             :         goto trivially_false;
    8575             : 
    8576             :       APInt NewRHS;
    8577             :       CmpInst::Predicate NewPred;
    8578      251558 :       if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
    8579      125779 :           ICmpInst::isEquality(NewPred)) {
    8580             :         // We were able to convert an inequality to an equality.
    8581       22553 :         Pred = NewPred;
    8582       22553 :         RHS = getConstant(NewRHS);
    8583             :         Changed = SimplifiedByConstantRange = true;
    8584             :       }
    8585             :     }
    8586             : 
    8587      198922 :     if (!SimplifiedByConstantRange) {
    8588      176369 :       switch (Pred) {
    8589             :       default:
    8590             :         break;
    8591             :       case ICmpInst::ICMP_EQ:
    8592             :       case ICmpInst::ICMP_NE:
    8593             :         // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
    8594       73143 :         if (!RA)
    8595       30919 :           if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
    8596             :             if (const SCEVMulExpr *ME =
    8597        4491 :                     dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
    8598        1308 :               if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
    8599        1208 :                   ME->getOperand(0)->isAllOnesValue()) {
    8600        1042 :                 RHS = AE->getOperand(1);
    8601        1042 :                 LHS = ME->getOperand(1);
    8602             :                 Changed = true;
    8603             :               }
    8604             :         break;
    8605             : 
    8606             : 
    8607             :         // The "Should have been caught earlier!" messages refer to the fact
    8608             :         // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
    8609             :         // should have fired on the corresponding cases, and canonicalized the
    8610             :         // check to trivially_true or trivially_false.
    8611             : 
    8612        4010 :       case ICmpInst::ICMP_UGE:
    8613             :         assert(!RA.isMinValue() && "Should have been caught earlier!");
    8614        4010 :         Pred = ICmpInst::ICMP_UGT;
    8615       12030 :         RHS = getConstant(RA - 1);
    8616             :         Changed = true;
    8617        4010 :         break;
    8618        2386 :       case ICmpInst::ICMP_ULE:
    8619             :         assert(!RA.isMaxValue() && "Should have been caught earlier!");
    8620        2386 :         Pred = ICmpInst::ICMP_ULT;
    8621        7158 :         RHS = getConstant(RA + 1);
    8622             :         Changed = true;
    8623        2386 :         break;
    8624        9255 :       case ICmpInst::ICMP_SGE:
    8625             :         assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
    8626        9255 :         Pred = ICmpInst::ICMP_SGT;
    8627       27765 :         RHS = getConstant(RA - 1);
    8628             :         Changed = true;
    8629        9255 :         break;
    8630        5157 :       case ICmpInst::ICMP_SLE:
    8631             :         assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
    8632        5157 :         Pred = ICmpInst::ICMP_SLT;
    8633       15471 :         RHS = getConstant(RA + 1);
    8634             :         Changed = true;
    8635        5157 :         break;
    8636             :       }
    8637             :     }
    8638             :   }
    8639             : 
    8640             :   // Check for obvious equality.
    8641      248643 :   if (HasSameValue(LHS, RHS)) {
    8642         226 :     if (ICmpInst::isTrueWhenEqual(Pred))
    8643             :       goto trivially_true;
    8644          28 :     if (ICmpInst::isFalseWhenEqual(Pred))
    8645             :       goto trivially_false;
    8646             :   }
    8647             : 
    8648             :   // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
    8649             :   // adding or subtracting 1 from one of the operands.
    8650      248417 :   switch (Pred) {
    8651        1775 :   case ICmpInst::ICMP_SLE:
    8652        5325 :     if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
    8653         430 :       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
    8654             :                        SCEV::FlagNSW);
    8655         430 :       Pred = ICmpInst::ICMP_SLT;
    8656             :       Changed = true;
    8657        4035 :     } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
    8658          78 :       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
    8659             :                        SCEV::FlagNSW);
    8660          78 :       Pred = ICmpInst::ICMP_SLT;
    8661             :       Changed = true;
    8662             :     }
    8663             :     break;
    8664        2718 :   case ICmpInst::ICMP_SGE:
    8665        8154 :     if (!getSignedRangeMin(RHS).isMinSignedValue()) {
    8666         398 :       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
    8667             :                        SCEV::FlagNSW);
    8668         398 :       Pred = ICmpInst::ICMP_SGT;
    8669             :       Changed = true;
    8670        6960 :     } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
    8671         162 :       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
    8672             :                        SCEV::FlagNSW);
    8673         162 :       Pred = ICmpInst::ICMP_SGT;
    8674             :       Changed = true;
    8675             :     }
    8676             :     break;
    8677        1305 :   case ICmpInst::ICMP_ULE:
    8678        2610 :     if (!getUnsignedRangeMax(RHS).isMaxValue()) {
    8679         484 :       RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
    8680             :                        SCEV::FlagNUW);
    8681         484 :       Pred = ICmpInst::ICMP_ULT;
    8682             :       Changed = true;
    8683        1642 :     } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
    8684          34 :       LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
    8685          34 :       Pred = ICmpInst::ICMP_ULT;
    8686             :       Changed = true;
    8687             :     }
    8688             :     break;
    8689        2792 :   case ICmpInst::ICMP_UGE:
    8690        5584 :     if (!getUnsignedRangeMin(RHS).isMinValue()) {
    8691          87 :       RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
    8692          87 :       Pred = ICmpInst::ICMP_UGT;
    8693             :       Changed = true;
    8694        5410 :     } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
    8695         898 :       LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
    8696             :                        SCEV::FlagNUW);
    8697         898 :       Pred = ICmpInst::ICMP_UGT;
    8698             :       Changed = true;
    8699             :     }
    8700             :     break;
    8701             :   default:
    8702             :     break;
    8703             :   }
    8704             : 
    8705             :   // TODO: More simplifications are possible here.
    8706             : 
    8707             :   // Recursively simplify until we either hit a recursion limit or nothing
    8708             :   // changes.
    8709      245846 :   if (Changed)
    8710       53394 :     return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
    8711             : 
    8712             :   return Changed;
    8713             : 
    8714        2123 : trivially_true:
    8715             :   // Return 0 == 0.
    8716        4264 :   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
    8717        2132 :   Pred = ICmpInst::ICMP_EQ;
    8718        2132 :   return true;
    8719             : 
    8720        7942 : trivially_false:
    8721             :   // Return 0 != 0.
    8722       16130 :   LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
    8723        8065 :   Pred = ICmpInst::ICMP_NE;
    8724        8065 :   return true;
    8725             : }
    8726             : 
    8727       33608 : bool ScalarEvolution::isKnownNegative(const SCEV *S) {
    8728       67216 :   return getSignedRangeMax(S).isNegative();
    8729             : }
    8730             : 
    8731       53108 : bool ScalarEvolution::isKnownPositive(const SCEV *S) {
    8732      106216 :   return getSignedRangeMin(S).isStrictlyPositive();
    8733             : }
    8734             : 
    8735     1421053 : bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
    8736     4263159 :   return !getSignedRangeMin(S).isNegative();
    8737             : }
    8738             : 
    8739      135121 : bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
    8740      270242 :   return !getSignedRangeMax(S).isStrictlyPositive();
    8741             : }
    8742             : 
    8743       17899 : bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
    8744       17899 :   return isKnownNegative(S) || isKnownPositive(S);
    8745             : }
    8746             : 
    8747             : std::pair<const SCEV *, const SCEV *>
    8748       26020 : ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
    8749             :   // Compute SCEV on entry of loop L.
    8750       26020 :   const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
    8751       26020 :   if (Start == getCouldNotCompute())
    8752        1051 :     return { Start, Start };
    8753             :   // Compute post increment SCEV for loop L.
    8754       24969 :   const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
    8755             :   assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
    8756       24969 :   return { Start, PostInc };
    8757             : }
    8758             : 
    8759       29497 : bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
    8760             :                                           const SCEV *LHS, const SCEV *RHS) {
    8761             :   // First collect all loops.
    8762             :   SmallPtrSet<const Loop *, 8> LoopsUsed;
    8763       29497 :   getUsedLoops(LHS, LoopsUsed);
    8764       29497 :   getUsedLoops(RHS, LoopsUsed);
    8765             : 
    8766       29497 :   if (LoopsUsed.empty())
    8767             :     return false;
    8768             : 
    8769             :   // Domination relationship must be a linear order on collected loops.
    8770             : #ifndef NDEBUG
    8771             :   for (auto *L1 : LoopsUsed)
    8772             :     for (auto *L2 : LoopsUsed)
    8773             :       assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
    8774             :               DT.dominates(L2->getHeader(), L1->getHeader())) &&
    8775             :              "Domination relationship is not a linear order");
    8776             : #endif
    8777             : 
    8778             :   const Loop *MDL =
    8779       13104 :       *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
    8780             :                         [&](const Loop *L1, const Loop *L2) {
    8781         335 :          return DT.properlyDominates(L1->getHeader(), L2->getHeader());
    8782       13439 :        });
    8783             : 
    8784             :   // Get init and post increment value for LHS.
    8785       13104 :   auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
    8786             :   // if LHS contains unknown non-invariant SCEV then bail out.
    8787       13104 :   if (SplitLHS.first == getCouldNotCompute())
    8788             :     return false;
    8789             :   assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
    8790             :   // Get init and post increment value for RHS.
    8791       12916 :   auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
    8792             :   // if RHS contains unknown non-invariant SCEV then bail out.
    8793       12916 :   if (SplitRHS.first == getCouldNotCompute())
    8794             :     return false;
    8795             :   assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
    8796             :   // It is possible that init SCEV contains an invariant load but it does
    8797             :   // not dominate MDL and is not available at MDL loop entry, so we should
    8798             :   // check it here.
    8799       24106 :   if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
    8800       12053 :       !isAvailableAtLoopEntry(SplitRHS.first, MDL))
    8801             :     return false;
    8802             : 
    8803       17498 :   return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
    8804        5445 :          isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
    8805             :                                      SplitRHS.second);
    8806             : }
    8807             : 
    8808       29497 : bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
    8809             :                                        const SCEV *LHS, const SCEV *RHS) {
    8810             :   // Canonicalize the inputs first.
    8811       29497 :   (void)SimplifyICmpOperands(Pred, LHS, RHS);
    8812             : 
    8813       29497 :   if (isKnownViaInduction(Pred, LHS, RHS))
    8814             :     return true;
    8815             : 
    8816       27647 :   if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
    8817             :     return true;
    8818             : 
    8819             :   // Otherwise see what can be done with some simple reasoning.
    8820       27629 :   return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
    8821             : }
    8822             : 
    8823        9642 : bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
    8824             :                                               const SCEVAddRecExpr *LHS,
    8825             :                                               const SCEV *RHS) {
    8826        9642 :   const Loop *L = LHS->getLoop();
    8827       23772 :   return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
    8828       14130 :          isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
    8829             : }
    8830             : 
    8831         762 : bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
    8832             :                                            ICmpInst::Predicate Pred,
    8833             :                                            bool &Increasing) {
    8834         762 :   bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
    8835             : 
    8836             : #ifndef NDEBUG
    8837             :   // Verify an invariant: inverting the predicate should turn a monotonically
    8838             :   // increasing change to a monotonically decreasing one, and vice versa.
    8839             :   bool IncreasingSwapped;
    8840             :   bool ResultSwapped = isMonotonicPredicateImpl(
    8841             :       LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
    8842             : 
    8843             :   assert(Result == ResultSwapped && "should be able to analyze both!");
    8844             :   if (ResultSwapped)
    8845             :     assert(Increasing == !IncreasingSwapped &&
    8846             :            "monotonicity should flip as we flip the predicate");
    8847             : #endif
    8848             : 
    8849         762 :   return Result;
    8850             : }
    8851             : 
    8852         762 : bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
    8853             :                                                ICmpInst::Predicate Pred,
    8854             :                                                bool &Increasing) {
    8855             : 
    8856             :   // A zero step value for LHS means the induction variable is essentially a
    8857             :   // loop invariant value. We don't really depend on the predicate actually
    8858             :   // flipping from false to true (for increasing predicates, and the other way
    8859             :   // around for decreasing predicates), all we care about is that *if* the
    8860             :   // predicate changes then it only changes from false to true.
    8861             :   //
    8862             :   // A zero step value in itself is not very useful, but there may be places
    8863             :   // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
    8864             :   // as general as possible.
    8865             : 
    8866         762 :   switch (Pred) {
    8867             :   default:
    8868             :     return false; // Conservative answer
    8869             : 
    8870         261 :   case ICmpInst::ICMP_UGT:
    8871             :   case ICmpInst::ICMP_UGE:
    8872             :   case ICmpInst::ICMP_ULT:
    8873             :   case ICmpInst::ICMP_ULE:
    8874         261 :     if (!LHS->hasNoUnsignedWrap())
    8875             :       return false;
    8876             : 
    8877         153 :     Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
    8878         153 :     return true;
    8879             : 
    8880         243 :   case ICmpInst::ICMP_SGT:
    8881             :   case ICmpInst::ICMP_SGE:
    8882             :   case ICmpInst::ICMP_SLT:
    8883             :   case ICmpInst::ICMP_SLE: {
    8884         243 :     if (!LHS->hasNoSignedWrap())
    8885             :       return false;
    8886             : 
    8887         230 :     const SCEV *Step = LHS->getStepRecurrence(*this);
    8888             : 
    8889         230 :     if (isKnownNonNegative(Step)) {
    8890          76 :       Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
    8891          76 :       return true;
    8892             :     }
    8893             : 
    8894         154 :     if (isKnownNonPositive(Step)) {
    8895         152 :       Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
    8896         152 :       return true;
    8897             :     }
    8898             : 
    8899             :     return false;
    8900             :   }
    8901             : 
    8902             :   }
    8903             : 
    8904             :   llvm_unreachable("switch has default clause!");
    8905             : }
    8906             : 
    8907        1270 : bool ScalarEvolution::isLoopInvariantPredicate(
    8908             :     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
    8909             :     ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
    8910             :     const SCEV *&InvariantRHS) {
    8911             : 
    8912             :   // If there is a loop-invariant, force it into the RHS, otherwise bail out.
    8913        1270 :   if (!isLoopInvariant(RHS, L)) {
    8914         400 :     if (!isLoopInvariant(LHS, L))
    8915             :       return false;
    8916             : 
    8917             :     std::swap(LHS, RHS);
    8918           1 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    8919             :   }
    8920             : 
    8921             :   const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
    8922         684 :   if (!ArLHS || ArLHS->getLoop() != L)
    8923             :     return false;
    8924             : 
    8925             :   bool Increasing;
    8926         684 :   if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
    8927             :     return false;
    8928             : 
    8929             :   // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
    8930             :   // true as the loop iterates, and the backedge is control dependent on
    8931             :   // "ArLHS `Pred` RHS" == true then we can reason as follows:
    8932             :   //
    8933             :   //   * if the predicate was false in the first iteration then the predicate
    8934             :   //     is never evaluated again, since the loop exits without taking the
    8935             :   //     backedge.
    8936             :   //   * if the predicate was true in the first iteration then it will
    8937             :   //     continue to be true for all future iterations since it is
    8938             :   //     monotonically increasing.
    8939             :   //
    8940             :   // For both the above possibilities, we can replace the loop varying
    8941             :   // predicate with its value on the first iteration of the loop (which is
    8942             :   // loop invariant).
    8943             :   //
    8944             :   // A similar reasoning applies for a monotonically decreasing predicate, by
    8945             :   // replacing true with false and false with true in the above two bullets.
    8946             : 
    8947         367 :   auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
    8948             : 
    8949         367 :   if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
    8950             :     return false;
    8951             : 
    8952          11 :   InvariantPred = Pred;
    8953          22 :   InvariantLHS = ArLHS->getStart();
    8954          11 :   InvariantRHS = RHS;
    8955          11 :   return true;
    8956             : }
    8957             : 
    8958      209931 : bool ScalarEvolution::isKnownPredicateViaConstantRanges(
    8959             :     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
    8960      209931 :   if (HasSameValue(LHS, RHS))
    8961       16592 :     return ICmpInst::isTrueWhenEqual(Pred);
    8962             : 
    8963             :   // This code is split out from isKnownPredicate because it is called from
    8964             :   // within isLoopEntryGuardedByCond.
    8965             : 
    8966             :   auto CheckRanges =
    8967      207658 :       [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
    8968      415316 :     return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
    8969             :         .contains(RangeLHS);
    8970      608655 :   };
    8971             : 
    8972             :   // The check at the top of the function catches the case where the values are
    8973             :   // known to be equal.
    8974      193339 :   if (Pred == CmpInst::ICMP_EQ)
    8975             :     return false;
    8976             : 
    8977      189694 :   if (Pred == CmpInst::ICMP_NE)
    8978       59612 :     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
    8979       56649 :            CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
    8980       17861 :            isKnownNonZero(getMinusSCEV(LHS, RHS));
    8981             : 
    8982      168870 :   if (CmpInst::isSigned(Pred))
    8983       83549 :     return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
    8984             : 
    8985       85321 :   return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
    8986             : }
    8987             : 
    8988      160362 : bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
    8989             :                                                     const SCEV *LHS,
    8990             :                                                     const SCEV *RHS) {
    8991             :   // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
    8992             :   // Return Y via OutY.
    8993             :   auto MatchBinaryAddToConst =
    8994             :       [this](const SCEV *Result, const SCEV *X, APInt &OutY,
    8995      138879 :              SCEV::NoWrapFlags ExpectedFlags) {
    8996             :     const SCEV *NonConstOp, *ConstOp;
    8997             :     SCEV::NoWrapFlags FlagsPresent;
    8998             : 
    8999      160627 :     if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
    9000      157591 :         !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
    9001             :       return false;
    9002             : 
    9003         950 :     OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
    9004         950 :     return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
    9005      160362 :   };
    9006             : 
    9007             :   APInt C;
    9008             : 
    9009      160362 :   switch (Pred) {
    9010             :   default:
    9011             :     break;
    9012             : 
    9013             :   case ICmpInst::ICMP_SGE:
    9014             :     std::swap(LHS, RHS);
    9015             :     LLVM_FALLTHROUGH;
    9016       35890 :   case ICmpInst::ICMP_SLE:
    9017             :     // X s<= (X + C)<nsw> if C >= 0
    9018       36055 :     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
    9019             :       return true;
    9020             : 
    9021             :     // (X + C)<nsw> s<= X if C <= 0
    9022       35907 :     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
    9023         112 :         !C.isStrictlyPositive())
    9024             :       return true;
    9025             :     break;
    9026             : 
    9027             :   case ICmpInst::ICMP_SGT:
    9028             :     std::swap(LHS, RHS);
    9029             :     LLVM_FALLTHROUGH;
    9030       33598 :   case ICmpInst::ICMP_SLT:
    9031             :     // X s< (X + C)<nsw> if C > 0
    9032       33600 :     if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
    9033           2 :         C.isStrictlyPositive())
    9034             :       return true;
    9035             : 
    9036             :     // (X + C)<nsw> s< X if C < 0
    9037       33596 :     if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
    9038             :       return true;
    9039             :     break;
    9040             :   }
    9041             : 
    9042             :   return false;
    9043             : }
    9044             : 
    9045       27647 : bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
    9046             :                                                    const SCEV *LHS,
    9047             :                                                    const SCEV *RHS) {
    9048       27647 :   if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
    9049             :     return false;
    9050             : 
    9051             :   // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
    9052             :   // the stack can result in exponential time complexity.
    9053        2111 :   SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
    9054             : 
    9055             :   // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
    9056             :   //
    9057             :   // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
    9058             :   // isKnownPredicate.  isKnownPredicate is more powerful, but also more
    9059             :   // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
    9060             :   // interesting cases seen in practice.  We can consider "upgrading" L >= 0 to
    9061             :   // use isKnownPredicate later if needed.
    9062        3584 :   return isKnownNonNegative(RHS) &&
    9063        4904 :          isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
    9064        1320 :          isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
    9065             : }
    9066             : 
    9067      143463 : bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
    9068             :                                         ICmpInst::Predicate Pred,
    9069             :                                         const SCEV *LHS, const SCEV *RHS) {
    9070             :   // No need to even try if we know the module has no guards.
    9071      143463 :   if (!HasGuards)
    9072             :     return false;
    9073             : 
    9074        5277 :   return any_of(*BB, [&](Instruction &I) {
    9075             :     using namespace llvm::PatternMatch;
    9076             : 
    9077             :     Value *Condition;
    9078        3712 :     return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
    9079        3858 :                          m_Value(Condition))) &&
    9080        3858 :            isImpliedCond(Pred, LHS, RHS, Condition, false);
    9081        1565 :   });
    9082             : }
    9083             : 
    9084             : /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
    9085             : /// protected by a conditional between LHS and RHS.  This is used to
    9086             : /// to eliminate casts.
    9087             : bool
    9088       30429 : ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
    9089             :                                              ICmpInst::Predicate Pred,
    9090             :                                              const SCEV *LHS, const SCEV *RHS) {
    9091             :   // Interpret a null as meaning no loop, where there is obviously no guard
    9092             :   // (interprocedural conditions notwithstanding).
    9093       30429 :   if (!L) return true;
    9094             : 
    9095       30429 :   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
    9096             :     return true;
    9097             : 
    9098       18865 :   BasicBlock *Latch = L->getLoopLatch();
    9099       18865 :   if (!Latch)
    9100             :     return false;
    9101             : 
    9102             :   BranchInst *LoopContinuePredicate =
    9103             :     dyn_cast<BranchInst>(Latch->getTerminator());
    9104       36171 :   if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
    9105       34658 :       isImpliedCond(Pred, LHS, RHS,
    9106             :                     LoopContinuePredicate->getCondition(),
    9107             :                     LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
    9108             :     return true;
    9109             : 
    9110             :   // We don't want more than one activation of the following loops on the stack
    9111             :   // -- that can lead to O(n!) time complexity.
    9112       17929 :   if (WalkingBEDominatingConds)
    9113             :     return false;
    9114             : 
    9115       16345 :   SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
    9116             : 
    9117             :   // See if we can exploit a trip count to prove the predicate.
    9118       16345 :   const auto &BETakenInfo = getBackedgeTakenInfo(L);
    9119       16345 :   const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
    9120       16345 :   if (LatchBECount != getCouldNotCompute()) {
    9121             :     // We know that Latch branches back to the loop header exactly
    9122             :     // LatchBECount times.  This means the backdege condition at Latch is
    9123             :     // equivalent to  "{0,+,1} u< LatchBECount".
    9124       13970 :     Type *Ty = LatchBECount->getType();
    9125             :     auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
    9126             :     const SCEV *LoopCounter =
    9127       13970 :       getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
    9128       13970 :     if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
    9129             :                       LatchBECount))
    9130             :       return true;
    9131             :   }
    9132             : 
    9133             :   // Check conditions due to any @llvm.assume intrinsics.
    9134       39588 :   for (auto &AssumeVH : AC.assumptions()) {
    9135        3479 :     if (!AssumeVH)
    9136           0 :       continue;
    9137             :     auto *CI = cast<CallInst>(AssumeVH);
    9138        6958 :     if (!DT.dominates(CI, Latch->getTerminator()))
    9139           0 :       continue;
    9140             : 
    9141        6958 :     if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
    9142             :       return true;
    9143             :   }
    9144             : 
    9145             :   // If the loop is not reachable from the entry block, we risk running into an
    9146             :   // infinite loop as we walk up into the dom tree.  These loops do not matter
    9147             :   // anyway, so we just return a conservative answer when we see them.
    9148       32630 :   if (!DT.isReachableFromEntry(L->getHeader()))
    9149             :     return false;
    9150             : 
    9151       16315 :   if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
    9152             :     return true;
    9153             : 
    9154       53815 :   for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
    9155       37513 :        DTN != HeaderDTN; DTN = DTN->getIDom()) {
    9156             :     assert(DTN && "should reach the loop header before reaching the root!");
    9157             : 
    9158       21256 :     BasicBlock *BB = DTN->getBlock();
    9159       21256 :     if (isImpliedViaGuard(BB, Pred, LHS, RHS))
    9160          45 :       return true;
    9161             : 
    9162             :     BasicBlock *PBB = BB->getSinglePredecessor();
    9163       21256 :     if (!PBB)
    9164       27424 :       continue;
    9165             : 
    9166             :     BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
    9167       11376 :     if (!ContinuePredicate || !ContinuePredicate->isConditional())
    9168        5586 :       continue;
    9169             : 
    9170             :     Value *Condition = ContinuePredicate->getCondition();
    9171             : 
    9172             :     // If we have an edge `E` within the loop body that dominates the only
    9173             :     // latch, the condition guarding `E` also guards the backedge.  This
    9174             :     // reasoning works only for loops with a single latch.
    9175             : 
    9176             :     BasicBlockEdge DominatingEdge(PBB, BB);
    9177        4751 :     if (DominatingEdge.isSingleEdge()) {
    9178             :       // We're constructively (and conservatively) enumerating edges within the
    9179             :       // loop body that dominate the latch.  The dominator tree better agree
    9180             :       // with us on this:
    9181             :       assert(DT.dominates(DominatingEdge, Latch) && "should be!");
    9182             : 
    9183        4751 :       if (isImpliedCond(Pred, LHS, RHS, Condition,
    9184             :                         BB != ContinuePredicate->getSuccessor(0)))
    9185             :         return true;
    9186             :     }
    9187             :   }
    9188             : 
    9189             :   return false;
    9190             : }
    9191             : 
    9192             : bool
    9193       29772 : ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
    9194             :                                           ICmpInst::Predicate Pred,
    9195             :                                           const SCEV *LHS, const SCEV *RHS) {
    9196             :   // Interpret a null as meaning no loop, where there is obviously no guard
    9197             :   // (interprocedural conditions notwithstanding).
    9198       29772 :   if (!L) return false;
    9199             : 
    9200             :   // Both LHS and RHS must be available at loop entry.
    9201             :   assert(isAvailableAtLoopEntry(LHS, L) &&
    9202             :          "LHS is not available at Loop Entry");
    9203             :   assert(isAvailableAtLoopEntry(RHS, L) &&
    9204             :          "RHS is not available at Loop Entry");
    9205             : 
    9206       29772 :   if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
    9207             :     return true;
    9208             : 
    9209             :   // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
    9210             :   // the facts (a >= b && a != b) separately. A typical situation is when the
    9211             :   // non-strict comparison is known from ranges and non-equality is known from
    9212             :   // dominating predicates. If we are proving strict comparison, we always try
    9213             :   // to prove non-equality and non-strict comparison separately.
    9214       19779 :   auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
    9215       19779 :   const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
    9216       19779 :   bool ProvedNonStrictComparison = false;
    9217       19779 :   bool ProvedNonEquality = false;
    9218             : 
    9219       19779 :   if (ProvingStrictComparison) {
    9220       13484 :     ProvedNonStrictComparison =
    9221       13484 :         isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
    9222       13484 :     ProvedNonEquality =
    9223       13484 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
    9224       13484 :     if (ProvedNonStrictComparison && ProvedNonEquality)
    9225             :       return true;
    9226             :   }
    9227             : 
    9228             :   // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
    9229       52570 :   auto ProveViaGuard = [&](BasicBlock *Block) {
    9230      159214 :     if (isImpliedViaGuard(Block, Pred, LHS, RHS))
    9231             :       return true;
    9232       52554 :     if (ProvingStrictComparison) {
    9233       75878 :       if (!ProvedNonStrictComparison)
    9234       21287 :         ProvedNonStrictComparison =
    9235       42574 :             isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
    9236       54597 :       if (!ProvedNonEquality)
    9237       32035 :         ProvedNonEquality =
    9238       64070 :             isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
    9239       54597 :       if (ProvedNonStrictComparison && ProvedNonEquality)
    9240             :         return true;
    9241             :     }
    9242             :     return false;
    9243       19775 :   };
    9244             : 
    9245             :   // Try to prove (Pred, LHS, RHS) using isImpliedCond.
    9246       22444 :   auto ProveViaCond = [&](Value *Condition, bool Inverse) {
    9247       61252 :     if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
    9248             :       return true;
    9249       18267 :     if (ProvingStrictComparison) {
    9250       27388 :       if (!ProvedNonStrictComparison)
    9251        7666 :         ProvedNonStrictComparison =
    9252       15332 :             isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
    9253       20235 :       if (!ProvedNonEquality)
    9254       11738 :         ProvedNonEquality =
    9255       23476 :             isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
    9256       20235 :       if (ProvedNonStrictComparison && ProvedNonEquality)
    9257             :         return true;
    9258             :     }
    9259             :     return false;
    9260       19775 :   };
    9261             : 
    9262             :   // Starting at the loop predecessor, climb up the predecessor chain, as long
    9263             :   // as there are predecessors that can be found that have unique successors
    9264             :   // leading to the original header.
    9265       48321 :   for (std::pair<BasicBlock *, BasicBlock *>
    9266       19775 :          Pair(L->getLoopPredecessor(), L->getHeader());
    9267       68096 :        Pair.first;
    9268       96642 :        Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
    9269             : 
    9270       52570 :     if (ProveViaGuard(Pair.first))
    9271             :       return true;
    9272             : 
    9273             :     BranchInst *LoopEntryPredicate =
    9274             :       dyn_cast<BranchInst>(Pair.first->getTerminator());
    9275       79765 :     if (!LoopEntryPredicate ||
    9276             :         LoopEntryPredicate->isUnconditional())
    9277       30151 :       continue;
    9278             : 
    9279       44806 :     if (ProveViaCond(LoopEntryPredicate->getCondition(),
    9280             :                      LoopEntryPredicate->getSuccessor(0) != Pair.second))
    9281             :       return true;
    9282             :   }
    9283             : 
    9284             :   // Check conditions due to any @llvm.assume intrinsics.
    9285       50622 :   for (auto &AssumeVH : AC.assumptions()) {
    9286        9794 :     if (!AssumeVH)
    9287           0 :       continue;
    9288             :     auto *CI = cast<CallInst>(AssumeVH);
    9289       19588 :     if (!DT.dominates(CI, L->getHeader()))
    9290        9753 :       continue;
    9291             : 
    9292          82 :     if (ProveViaCond(CI->getArgOperand(0), false))
    9293             :       return true;
    9294             :   }
    9295             : 
    9296             :   return false;
    9297             : }
    9298             : 
    9299       68871 : bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
    9300             :                                     const SCEV *LHS, const SCEV *RHS,
    9301             :                                     Value *FoundCondValue,
    9302             :                                     bool Inverse) {
    9303       68871 :   if (!PendingLoopPredicates.insert(FoundCondValue).second)
    9304             :     return false;
    9305             : 
    9306             :   auto ClearOnExit =
    9307       66363 :       make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
    9308             : 
    9309             :   // Recursively handle And and Or conditions.
    9310             :   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
    9311        1042 :     if (BO->getOpcode() == Instruction::And) {
    9312         709 :       if (!Inverse)
    9313        1112 :         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
    9314         518 :                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
    9315         333 :     } else if (BO->getOpcode() == Instruction::Or) {
    9316         295 :       if (Inverse)
    9317         206 :         return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
    9318         100 :                isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
    9319             :     }
    9320             :   }
    9321             : 
    9322             :   ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
    9323             :   if (!ICI) return false;
    9324             : 
    9325             :   // Now that we found a conditional branch that dominates the loop or controls
    9326             :   // the loop latch. Check to see if it is the comparison we are looking for.
    9327             :   ICmpInst::Predicate FoundPred;
    9328       62963 :   if (Inverse)
    9329             :     FoundPred = ICI->getInversePredicate();
    9330             :   else
    9331             :     FoundPred = ICI->getPredicate();
    9332             : 
    9333       62963 :   const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
    9334       62963 :   const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
    9335             : 
    9336       62963 :   return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
    9337             : }
    9338             : 
    9339       76933 : bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
    9340             :                                     const SCEV *RHS,
    9341             :                                     ICmpInst::Predicate FoundPred,
    9342             :                                     const SCEV *FoundLHS,
    9343             :                                     const SCEV *FoundRHS) {
    9344             :   // Balance the types.
    9345      153866 :   if (getTypeSizeInBits(LHS->getType()) <
    9346       76933 :       getTypeSizeInBits(FoundLHS->getType())) {
    9347       10647 :     if (CmpInst::isSigned(Pred)) {
    9348        1489 :       LHS = getSignExtendExpr(LHS, FoundLHS->getType());
    9349        1489 :       RHS = getSignExtendExpr(RHS, FoundLHS->getType());
    9350             :     } else {
    9351        9158 :       LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
    9352        9158 :       RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
    9353             :     }
    9354      132572 :   } else if (getTypeSizeInBits(LHS->getType()) >
    9355       66286 :       getTypeSizeInBits(FoundLHS->getType())) {
    9356        7276 :     if (CmpInst::isSigned(FoundPred)) {
    9357        3329 :       FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
    9358        3329 :       FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
    9359             :     } else {
    9360        3947 :       FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
    9361        3947 :       FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
    9362             :     }
    9363             :   }
    9364             : 
    9365             :   // Canonicalize the query to match the way instcombine will have
    9366             :   // canonicalized the comparison.
    9367       76933 :   if (SimplifyICmpOperands(Pred, LHS, RHS))
    9368        3532 :     if (LHS == RHS)
    9369        3532 :       return CmpInst::isTrueWhenEqual(Pred);
    9370       73401 :   if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
    9371          47 :     if (FoundLHS == FoundRHS)
    9372          47 :       return CmpInst::isFalseWhenEqual(FoundPred);
    9373             : 
    9374             :   // Check to see if we can make the LHS or RHS match.
    9375       73354 :   if (LHS == FoundRHS || RHS == FoundLHS) {
    9376        1452 :     if (isa<SCEVConstant>(RHS)) {
    9377             :       std::swap(FoundLHS, FoundRHS);
    9378         409 :       FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
    9379             :     } else {
    9380             :       std::swap(LHS, RHS);
    9381         317 :       Pred = ICmpInst::getSwappedPredicate(Pred);
    9382             :     }
    9383             :   }
    9384             : 
    9385             :   // Check whether the found predicate is the same as the desired predicate.
    9386       73354 :   if (FoundPred == Pred)
    9387       22262 :     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
    9388             : 
    9389             :   // Check whether swapping the found predicate makes it the same as the
    9390             :   // desired predicate.
    9391       51092 :   if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
    9392        8842 :     if (isa<SCEVConstant>(RHS))
    9393        4112 :       return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
    9394             :     else
    9395         309 :       return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
    9396         309 :                                    RHS, LHS, FoundLHS, FoundRHS);
    9397             :   }
    9398             : 
    9399             :   // Unsigned comparison is the same as signed comparison when both the operands
    9400             :   // are non-negative.
    9401       67537 :   if (CmpInst::isUnsigned(FoundPred) &&
    9402       25206 :       CmpInst::getSignedPredicate(FoundPred) == Pred &&
    9403       54397 :       isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
    9404        2872 :     return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
    9405             : 
    9406             :   // Check if we can make progress by sharpening ranges.
    9407       55083 :   if (FoundPred == ICmpInst::ICMP_NE &&
    9408       33852 :       (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
    9409             : 
    9410             :     const SCEVConstant *C = nullptr;
    9411             :     const SCEV *V = nullptr;
    9412             : 
    9413        8628 :     if (isa<SCEVConstant>(FoundLHS)) {
    9414             :       C = cast<SCEVConstant>(FoundLHS);
    9415           0 :       V = FoundRHS;
    9416             :     } else {
    9417        8628 :       C = cast<SCEVConstant>(FoundRHS);
    9418             :       V = FoundLHS;
    9419             :     }
    9420             : 
    9421             :     // The guarding predicate tells us that C != V. If the known range
    9422             :     // of V is [C, t), we can sharpen the range to [C + 1, t).  The
    9423             :     // range we consider has to correspond to same signedness as the
    9424             :     // predicate we're interested in folding.
    9425             : 
    9426        8628 :     APInt Min = ICmpInst::isSigned(Pred) ?
    9427        8628 :         getSignedRangeMin(V) : getUnsignedRangeMin(V);
    9428             : 
    9429        8628 :     if (Min == C->getAPInt()) {
    9430             :       // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
    9431             :       // This is true even if (Min + 1) wraps around -- in case of
    9432             :       // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
    9433             : 
    9434        2802 :       APInt SharperMin = Min + 1;
    9435             : 
    9436        2802 :       switch (Pred) {
    9437          33 :         case ICmpInst::ICMP_SGE:
    9438             :         case ICmpInst::ICMP_UGE:
    9439             :           // We know V `Pred` SharperMin.  If this implies LHS `Pred`
    9440             :           // RHS, we're done.
    9441          33 :           if (isImpliedCondOperands(Pred, LHS, RHS, V,
    9442             :                                     getConstant(SharperMin)))
    9443             :             return true;
    9444             :           LLVM_FALLTHROUGH;
    9445             : 
    9446             :         case ICmpInst::ICMP_SGT:
    9447             :         case ICmpInst::ICMP_UGT:
    9448             :           // We know from the range information that (V `Pred` Min ||
    9449             :           // V == Min).  We know from the guarding condition that !(V
    9450             :           // == Min).  This gives us
    9451             :           //
    9452             :           //       V `Pred` Min || V == Min && !(V == Min)
    9453             :           //   =>  V `Pred` Min
    9454             :           //
    9455             :           // If V `Pred` Min implies LHS `Pred` RHS, we're done.
    9456             : 
    9457        1009 :           if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
    9458             :             return true;
    9459             :           LLVM_FALLTHROUGH;
    9460             : 
    9461             :         default:
    9462             :           // No change
    9463             :           break;
    9464             :       }
    9465             :     }
    9466             :   }
    9467             : 
    9468             :   // Check whether the actual condition is beyond sufficient.
    9469       43727 :   if (FoundPred == ICmpInst::ICMP_EQ)
    9470        5220 :     if (ICmpInst::isTrueWhenEqual(Pred))
    9471           6 :       if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
    9472             :         return true;
    9473       43727 :   if (Pred == ICmpInst::ICMP_NE)
    9474       24161 :     if (!ICmpInst::isTrueWhenEqual(FoundPred))
    9475       20031 :       if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
    9476             :         return true;
    9477             : 
    9478             :   // Otherwise assume the worst.
    9479             :   return false;
    9480             : }
    9481             : 
    9482      204961 : bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
    9483             :                                      const SCEV *&L, const SCEV *&R,
    9484             :                                      SCEV::NoWrapFlags &Flags) {
    9485             :   const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
    9486       46045 :   if (!AE || AE->getNumOperands() != 2)
    9487             :     return false;
    9488             : 
    9489       78346 :   L = AE->getOperand(0);
    9490       39173 :   R = AE->getOperand(1);
    9491       78346 :   Flags = AE->getNoWrapFlags();
    9492       39173 :   return true;
    9493             : }
    9494             : 
    9495       60631 : Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
    9496             :                                                            const SCEV *Less) {
    9497             :   // We avoid subtracting expressions here because this function is usually
    9498             :   // fairly deep in the call stack (i.e. is called many times).
    9499             : 
    9500       89892 :   if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
    9501             :     const auto *LAR = cast<SCEVAddRecExpr>(Less);
    9502             :     const auto *MAR = cast<SCEVAddRecExpr>(More);
    9503             : 
    9504       26557 :     if (LAR->getLoop() != MAR->getLoop())
    9505             :       return None;
    9506             : 
    9507             :     // We look at affine expressions only; not for correctness but to keep
    9508             :     // getStepRecurrence cheap.
    9509       52944 :     if (!LAR->isAffine() || !MAR->isAffine())
    9510             :       return None;
    9511             : 
    9512       26450 :     if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
    9513             :       return None;
    9514             : 
    9515       21219 :     Less = LAR->getStart();
    9516       21219 :     More = MAR->getStart();
    9517             : 
    9518             :     // fall through
    9519             :   }
    9520             : 
    9521       81349 :   if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
    9522             :     const auto &M = cast<SCEVConstant>(More)->getAPInt();
    9523             :     const auto &L = cast<SCEVConstant>(Less)->getAPInt();
    9524       21962 :     return M - L;
    9525             :   }
    9526             : 
    9527             :   SCEV::NoWrapFlags Flags;
    9528       33331 :   const SCEV *LLess = nullptr, *RLess = nullptr;
    9529       33331 :   const SCEV *LMore = nullptr, *RMore = nullptr;
    9530             :   const SCEVConstant *C1 = nullptr, *C2 = nullptr;
    9531             :   // Compare (X + C1) vs X.
    9532       33331 :   if (splitBinaryAdd(Less, LLess, RLess, Flags))
    9533        7946 :     if ((C1 = dyn_cast<SCEVConstant>(LLess)))
    9534        6569 :       if (RLess == More)
    9535         580 :         return -(C1->getAPInt());
    9536             : 
    9537             :   // Compare X vs (X + C2).
    9538       32751 :   if (splitBinaryAdd(More, LMore, RMore, Flags))
    9539        9479 :     if ((C2 = dyn_cast<SCEVConstant>(LMore)))
    9540        8954 :       if (RMore == Less)
    9541             :         return C2->getAPInt();
    9542             : 
    9543             :   // Compare (X + C1) vs (X + C2).
    9544       30576 :   if (C1 && C2 && RLess == RMore)
    9545        1751 :     return C2->getAPInt() - C1->getAPInt();
    9546             : 
    9547             :   return None;
    9548             : }
    9549             : 
    9550       49257 : bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
    9551             :     ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
    9552             :     const SCEV *FoundLHS, const SCEV *FoundRHS) {
    9553       49257 :   if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
    9554             :     return false;
    9555             : 
    9556             :   const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
    9557             :   if (!AddRecLHS)
    9558             :     return false;
    9559             : 
    9560             :   const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
    9561             :   if (!AddRecFoundLHS)
    9562             :     return false;
    9563             : 
    9564             :   // We'd like to let SCEV reason about control dependencies, so we constrain
    9565             :   // both the inequalities to be about add recurrences on the same loop.  This
    9566             :   // way we can use isLoopEntryGuardedByCond later.
    9567             : 
    9568       15761 :   const Loop *L = AddRecFoundLHS->getLoop();
    9569       15761 :   if (L != AddRecLHS->getLoop())
    9570             :     return false;
    9571             : 
    9572             :   //  FoundLHS u< FoundRHS u< -C =>  (FoundLHS + C) u< (FoundRHS + C) ... (1)
    9573             :   //
    9574             :   //  FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
    9575             :   //                                                                  ... (2)
    9576             :   //
    9577             :   // Informal proof for (2), assuming (1) [*]:
    9578             :   //
    9579             :   // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
    9580             :   //
    9581             :   // Then
    9582             :   //
    9583             :   //       FoundLHS s< FoundRHS s< INT_MIN - C
    9584             :   // <=>  (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C   [ using (3) ]
    9585             :   // <=>  (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
    9586             :   // <=>  (FoundLHS + INT_MIN + C + INT_MIN) s<
    9587             :   //                        (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
    9588             :   // <=>  FoundLHS + C s< FoundRHS + C
    9589             :   //
    9590             :   // [*]: (1) can be proved by ruling out overflow.
    9591             :   //
    9592             :   // [**]: This can be proved by analyzing all the four possibilities:
    9593             :   //    (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
    9594             :   //    (A s>= 0, B s>= 0).
    9595             :   //
    9596             :   // Note:
    9597             :   // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
    9598             :   // will not sign underflow.  For instance, say FoundLHS = (i8 -128), FoundRHS
    9599             :   // = (i8 -127) and C = (i8 -100).  Then INT_MIN - C = (i8 -28), and FoundRHS
    9600             :   // s< (INT_MIN - C).  Lack of sign overflow / underflow in "FoundRHS + C" is
    9601             :   // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
    9602             :   // C)".
    9603             : 
    9604       15325 :   Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
    9605       15325 :   Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
    9606       20560 :   if (!LDiff || !RDiff || *LDiff != *RDiff)
    9607             :     return false;
    9608             : 
    9609          20 :   if (LDiff->isMinValue())
    9610             :     return true;
    9611             : 
    9612             :   APInt FoundRHSLimit;
    9613             : 
    9614          12 :   if (Pred == CmpInst::ICMP_ULT) {
    9615           7 :     FoundRHSLimit = -(*RDiff);
    9616             :   } else {
    9617             :     assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
    9618          10 :     FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
    9619             :   }
    9620             : 
    9621             :   // Try to prove (1) or (2), as needed.
    9622          22 :   return isAvailableAtLoopEntry(FoundRHS, L) &&
    9623          10 :          isLoopEntryGuardedByCond(L, Pred, FoundRHS,
    9624             :                                   getConstant(FoundRHSLimit));
    9625             : }
    9626             : 
    9627       30004 : bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
    9628             :                                         const SCEV *LHS, const SCEV *RHS,
    9629             :                                         const SCEV *FoundLHS,
    9630             :                                         const SCEV *FoundRHS, unsigned Depth) {
    9631       30004 :   const PHINode *LPhi = nullptr, *RPhi = nullptr;
    9632             : 
    9633       30004 :   auto ClearOnExit = make_scope_exit([&]() {
    9634       30004 :     if (LPhi) {
    9635         414 :       bool Erased = PendingMerges.erase(LPhi);
    9636             :       assert(Erased && "Failed to erase LPhi!");
    9637             :       (void)Erased;
    9638             :     }
    9639       30004 :     if (RPhi) {
    9640             :       bool Erased = PendingMerges.erase(RPhi);
    9641             :       assert(Erased && "Failed to erase RPhi!");
    9642             :       (void)Erased;
    9643             :     }
    9644       30004 :   });
    9645             : 
    9646             :   // Find respective Phis and check that they are not being pending.
    9647        3564 :   if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
    9648             :     if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
    9649         336 :       if (!PendingMerges.insert(Phi).second)
    9650             :         return false;
    9651         336 :       LPhi = Phi;
    9652             :     }
    9653        1156 :   if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
    9654             :     if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
    9655             :       // If we detect a loop of Phi nodes being processed by this method, for
    9656             :       // example:
    9657             :       //
    9658             :       //   %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
    9659             :       //   %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
    9660             :       //
    9661             :       // we don't want to deal with a case that complex, so return conservative
    9662             :       // answer false.
    9663          78 :       if (!PendingMerges.insert(Phi).second)
    9664             :         return false;
    9665          78 :       RPhi = Phi;
    9666             :     }
    9667             : 
    9668             :   // If none of LHS, RHS is a Phi, nothing to do here.
    9669       30004 :   if (!LPhi && !RPhi)
    9670             :     return false;
    9671             : 
    9672             :   // If there is a SCEVUnknown Phi we are interested in, make it left.
    9673         394 :   if (!LPhi) {
    9674             :     std::swap(LHS, RHS);
    9675             :     std::swap(FoundLHS, FoundRHS);
    9676             :     std::swap(LPhi, RPhi);
    9677          58 :     Pred = ICmpInst::getSwappedPredicate(Pred);
    9678             :   }
    9679             : 
    9680             :   assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
    9681         394 :   const BasicBlock *LBB = LPhi->getParent();
    9682             :   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
    9683             : 
    9684         439 :   auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
    9685        2004 :     return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
    9686        2348 :            isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
    9687        1484 :            isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
    9688         833 :   };
    9689             : 
    9690         394 :   if (RPhi && RPhi->getParent() == LBB) {
    9691             :     // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
    9692             :     // If we compare two Phis from the same block, and for each entry block
    9693             :     // the predicate is true for incoming values from this block, then the
    9694             :     // predicate is also true for the Phis.
    9695          40 :     for (const BasicBlock *IncBB : predecessors(LBB)) {
    9696          20 :       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
    9697          20 :       const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
    9698          20 :       if (!ProvedEasily(L, R))
    9699          20 :         return false;
    9700             :     }
    9701         390 :   } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
    9702             :     // Case two: RHS is also a Phi from the same basic block, and it is an
    9703             :     // AddRec. It means that there is a loop which has both AddRec and Unknown
    9704             :     // PHIs, for it we can compare incoming values of AddRec from above the loop
    9705             :     // and latch with their respective incoming values of LPhi.
    9706             :     // TODO: Generalize to handle loops with many inputs in a header.
    9707           8 :     if (LPhi->getNumIncomingValues() != 2) return false;
    9708             : 
    9709             :     auto *RLoop = RAR->getLoop();
    9710           0 :     auto *Predecessor = RLoop->getLoopPredecessor();
    9711             :     assert(Predecessor && "Loop with AddRec with no predecessor?");
    9712           0 :     const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
    9713           0 :     if (!ProvedEasily(L1, RAR->getStart()))
    9714             :       return false;
    9715           0 :     auto *Latch = RLoop->getLoopLatch();
    9716             :     assert(Latch && "Loop with AddRec with no latch?");
    9717           0 :     const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
    9718           0 :     if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
    9719             :       return false;
    9720             :   } else {
    9721             :     // In all other cases go over inputs of LHS and compare each of them to RHS,
    9722             :     // the predicate is true for (LHS, RHS) if it is true for all such pairs.
    9723             :     // At this point RHS is either a non-Phi, or it is a Phi from some block
    9724             :     // different from LBB.
    9725         804 :     for (const BasicBlock *IncBB : predecessors(LBB)) {
    9726             :       // Check that RHS is available in this block.
    9727         419 :       if (!dominates(RHS, IncBB))
    9728         347 :         return false;
    9729         419 :       const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
    9730         419 :       if (!ProvedEasily(L, RHS))
    9731             :         return false;
    9732             :     }
    9733             :   }
    9734             :   return true;
    9735             : }
    9736             : 
    9737       50634 : bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
    9738             :                                             const SCEV *LHS, const SCEV *RHS,
    9739             :                                             const SCEV *FoundLHS,
    9740             :                                             const SCEV *FoundRHS) {
    9741       50634 :   if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
    9742             :     return true;
    9743             : 
    9744       49257 :   if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
    9745             :     return true;
    9746             : 
    9747       49242 :   return isImpliedCondOperandsHelper(Pred, LHS, RHS,
    9748       94055 :                                      FoundLHS, FoundRHS) ||
    9749             :          // ~x < ~y --> x > y
    9750       44813 :          isImpliedCondOperandsHelper(Pred, LHS, RHS,
    9751             :                                      getNotSCEV(FoundRHS),
    9752             :                                      getNotSCEV(FoundLHS));
    9753             : }
    9754             : 
    9755             : /// If Expr computes ~A, return A else return nullptr
    9756       81845 : static const SCEV *MatchNotExpr(const SCEV *Expr) {
    9757             :   const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
    9758       21599 :   if (!Add || Add->getNumOperands() != 2 ||
    9759       19348 :       !Add->getOperand(0)->isAllOnesValue())
    9760             :     return nullptr;
    9761             : 
    9762        4102 :   const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
    9763        5130 :   if (!AddRHS || AddRHS->getNumOperands() != 2 ||
    9764        5112 :       !AddRHS->getOperand(0)->isAllOnesValue())
    9765             :     return nullptr;
    9766             : 
    9767        4906 :   return AddRHS->getOperand(1);
    9768             : }
    9769             : 
    9770             : /// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
    9771             : template<typename MaxExprType>
    9772       84282 : static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
    9773             :                               const SCEV *Candidate) {
    9774             :   const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
    9775             :   if (!MaxExpr) return false;
    9776             : 
    9777         462 :   return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
    9778             : }
    9779             : 
    9780             : /// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
    9781             : template<typename MaxExprType>
    9782       81845 : static bool IsMinConsistingOf(ScalarEvolution &SE,
    9783             :                               const SCEV *MaybeMinExpr,
    9784             :                               const SCEV *Candidate) {
    9785       81845 :   const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
    9786       81845 :   if (!MaybeMaxExpr)
    9787             :     return false;
    9788             : 
    9789        2453 :   return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
    9790             : }
    9791             : 
    9792      160642 : static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
    9793             :                                            ICmpInst::Predicate Pred,
    9794             :                                            const SCEV *LHS, const SCEV *RHS) {
    9795             :   // If both sides are affine addrecs for the same loop, with equal
    9796             :   // steps, and we know the recurrences don't wrap, then we only
    9797             :   // need to check the predicate on the starting values.
    9798             : 
    9799      160642 :   if (!ICmpInst::isRelational(Pred))
    9800             :     return false;
    9801             : 
    9802             :   const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
    9803             :   if (!LAR)
    9804             :     return false;
    9805             :   const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
    9806             :   if (!RAR)
    9807             :     return false;
    9808       16037 :   if (LAR->getLoop() != RAR->getLoop())
    9809             :     return false;
    9810       30681 :   if (!LAR->isAffine() || !RAR->isAffine())
    9811             :     return false;
    9812             : 
    9813       15335 :   if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
    9814             :     return false;
    9815             : 
    9816       10526 :   SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
    9817             :                          SCEV::FlagNSW : SCEV::FlagNUW;
    9818       22503 :   if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
    9819             :     return false;
    9820             : 
    9821        4113 :   return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
    9822             : }
    9823             : 
    9824             : /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
    9825             : /// expression?
    9826      160674 : static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
    9827             :                                         ICmpInst::Predicate Pred,
    9828             :                                         const SCEV *LHS, const SCEV *RHS) {
    9829      160674 :   switch (Pred) {
    9830             :   default:
    9831             :     return false;
    9832             : 
    9833             :   case ICmpInst::ICMP_SGE:
    9834             :     std::swap(LHS, RHS);
    9835             :     LLVM_FALLTHROUGH;
    9836       35947 :   case ICmpInst::ICMP_SLE:
    9837             :     return
    9838             :       // min(A, ...) <= A
    9839       71886 :       IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
    9840             :       // A <= max(A, ...)
    9841       35939 :       IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
    9842             : 
    9843             :   case ICmpInst::ICMP_UGE:
    9844             :     std::swap(LHS, RHS);
    9845             :     LLVM_FALLTHROUGH;
    9846       45898 :   case ICmpInst::ICMP_ULE:
    9847             :     return
    9848             :       // min(A, ...) <= A
    9849       91788 :       IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
    9850             :       // A <= max(A, ...)
    9851       45890 :       IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
    9852             :   }
    9853             : 
    9854             :   llvm_unreachable("covered switch fell through?!");
    9855             : }
    9856             : 
    9857       96443 : bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
    9858             :                                              const SCEV *LHS, const SCEV *RHS,
    9859             :                                              const SCEV *FoundLHS,
    9860             :                                              const SCEV *FoundRHS,
    9861             :                                              unsigned Depth) {
    9862             :   assert(getTypeSizeInBits(LHS->getType()) ==
    9863             :              getTypeSizeInBits(RHS->getType()) &&
    9864             :          "LHS and RHS have different sizes?");
    9865             :   assert(getTypeSizeInBits(FoundLHS->getType()) ==
    9866             :              getTypeSizeInBits(FoundRHS->getType()) &&
    9867             :          "FoundLHS and FoundRHS have different sizes?");
    9868             :   // We want to avoid hurting the compile time with analysis of too big trees.
    9869       96443 :   if (Depth > MaxSCEVOperationsImplicationDepth)
    9870             :     return false;
    9871             :   // We only want to work with ICMP_SGT comparison so far.
    9872             :   // TODO: Extend to ICMP_UGT?
    9873       96355 :   if (Pred == ICmpInst::ICMP_SLT) {
    9874             :     Pred = ICmpInst::ICMP_SGT;
    9875             :     std::swap(LHS, RHS);
    9876             :     std::swap(FoundLHS, FoundRHS);
    9877             :   }
    9878       96355 :   if (Pred != ICmpInst::ICMP_SGT)
    9879             :     return false;
    9880             : 
    9881             :   auto GetOpFromSExt = [&](const SCEV *S) {
    9882             :     if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
    9883        5583 :       return Ext->getOperand();
    9884             :     // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
    9885             :     // the constant in some cases.
    9886             :     return S;
    9887             :   };
    9888             : 
    9889             :   // Acquire values from extensions.
    9890             :   auto *OrigLHS = LHS;
    9891       35223 :   auto *OrigFoundLHS = FoundLHS;
    9892             :   LHS = GetOpFromSExt(LHS);
    9893             :   FoundLHS = GetOpFromSExt(FoundLHS);
    9894             : 
    9895             :   // Is the SGT predicate can be proved trivially or using the found context.
    9896        9800 :   auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
    9897       16207 :     return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
    9898       12814 :            isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
    9899       12814 :                                   FoundRHS, Depth + 1);
    9900       45023 :   };
    9901             : 
    9902             :   if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
    9903             :     // We want to avoid creation of any new non-constant SCEV. Since we are
    9904             :     // going to compare the operands to RHS, we should be certain that we don't
    9905             :     // need any size extensions for this. So let's decline all cases when the
    9906             :     // sizes of types of LHS and RHS do not match.
    9907             :     // TODO: Maybe try to get RHS from sext to catch more cases?
    9908        7977 :     if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
    9909        4828 :       return false;
    9910             : 
    9911             :     // Should not overflow.
    9912        7879 :     if (!LHSAddExpr->hasNoSignedWrap())
    9913             :       return false;
    9914             : 
    9915        3169 :     auto *LL = LHSAddExpr->getOperand(0);
    9916             :     auto *LR = LHSAddExpr->getOperand(1);
    9917        6338 :     auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
    9918             : 
    9919             :     // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
    9920        6322 :     auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
    9921        6322 :       return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
    9922        9491 :     };
    9923             :     // Try to prove the following rule:
    9924             :     // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
    9925             :     // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
    9926        3169 :     if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
    9927             :       return true;
    9928        4665 :   } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
    9929             :     Value *LL, *LR;
    9930             :     // FIXME: Once we have SDiv implemented, we can get rid of this matching.
    9931             : 
    9932             :     using namespace llvm::PatternMatch;
    9933             : 
    9934        9330 :     if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
    9935             :       // Rules for division.
    9936             :       // We are going to perform some comparisons with Denominator and its
    9937             :       // derivative expressions. In general case, creating a SCEV for it may
    9938             :       // lead to a complex analysis of the entire graph, and in particular it
    9939             :       // can request trip count recalculation for the same loop. This would
    9940             :       // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
    9941             :       // this, we only want to create SCEVs that are constants in this section.
    9942             :       // So we bail if Denominator is not a constant.
    9943         894 :       if (!isa<ConstantInt>(LR))
    9944         391 :         return false;
    9945             : 
    9946         447 :       auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
    9947             : 
    9948             :       // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
    9949             :       // then a SCEV for the numerator already exists and matches with FoundLHS.
    9950         447 :       auto *Numerator = getExistingSCEV(LL);
    9951         447 :       if (!Numerator || Numerator->getType() != FoundLHS->getType())
    9952             :         return false;
    9953             : 
    9954             :       // Make sure that the numerator matches with FoundLHS and the denominator
    9955             :       // is positive.
    9956         431 :       if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
    9957             :         return false;
    9958             : 
    9959          86 :       auto *DTy = Denominator->getType();
    9960          86 :       auto *FRHSTy = FoundRHS->getType();
    9961          86 :       if (DTy->isPointerTy() != FRHSTy->isPointerTy())
    9962             :         // One of types is a pointer and another one is not. We cannot extend
    9963             :         // them properly to a wider type, so let us just reject this case.
    9964             :         // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
    9965             :         // to avoid this check.
    9966             :         return false;
    9967             : 
    9968             :       // Given that:
    9969             :       // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
    9970          86 :       auto *WTy = getWiderType(DTy, FRHSTy);
    9971          86 :       auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
    9972          86 :       auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
    9973             : 
    9974             :       // Try to prove the following rule:
    9975             :       // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
    9976             :       // For example, given that FoundLHS > 2. It means that FoundLHS is at
    9977             :       // least 3. If we divide it by Denominator < 4, we will have at least 1.
    9978          86 :       auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
    9979         154 :       if (isKnownNonPositive(RHS) &&
    9980          68 :           IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
    9981             :         return true;
    9982             : 
    9983             :       // Try to prove the following rule:
    9984             :       // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
    9985             :       // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
    9986             :       // If we divide it by Denominator > 2, then:
    9987             :       // 1. If FoundLHS is negative, then the result is 0.
    9988             :       // 2. If FoundLHS is non-negative, then the result is non-negative.
    9989             :       // Anyways, the result is non-negative.
    9990          73 :       auto *MinusOne = getNegativeSCEV(getOne(WTy));
    9991          73 :       auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
    9992         114 :       if (isKnownNegative(RHS) &&
    9993          41 :           IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
    9994             :         return true;
    9995             :     }
    9996             :   }
    9997             : 
    9998             :   // If our expression contained SCEVUnknown Phis, and we split it down and now
    9999             :   // need to prove something for them, try to prove the predicate for every
   10000             :   // possible incoming values of those Phis.
   10001       30004 :   if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
   10002             :     return true;
   10003             : 
   10004       29985 :   return false;
   10005             : }
   10006             : 
   10007             : bool
   10008      209931 : ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
   10009             :                                            const SCEV *LHS, const SCEV *RHS) {
   10010      370605 :   return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
   10011      321316 :          IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
   10012      530935 :          IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
   10013      370293 :          isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
   10014             : }
   10015             : 
   10016             : bool
   10017       94055 : ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
   10018             :                                              const SCEV *LHS, const SCEV *RHS,
   10019             :                                              const SCEV *FoundLHS,
   10020             :                                              const SCEV *FoundRHS) {
   10021       94055 :   switch (Pred) {
   10022           0 :   default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
   10023       23141 :   case ICmpInst::ICMP_EQ:
   10024             :   case ICmpInst::ICMP_NE:
   10025       23141 :     if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
   10026             :       return true;
   10027             :     break;
   10028       13239 :   case ICmpInst::ICMP_SLT:
   10029             :   case ICmpInst::ICMP_SLE:
   10030       13887 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
   10031         648 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
   10032             :       return true;
   10033             :     break;
   10034       17791 :   case ICmpInst::ICMP_SGT:
   10035             :   case ICmpInst::ICMP_SGE:
   10036       21805 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
   10037        4014 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
   10038             :       return true;
   10039             :     break;
   10040       33150 :   case ICmpInst::ICMP_ULT:
   10041             :   case ICmpInst::ICMP_ULE:
   10042       39878 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
   10043        6728 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
   10044             :       return true;
   10045             :     break;
   10046        6734 :   case ICmpInst::ICMP_UGT:
   10047             :   case ICmpInst::ICMP_UGE:
   10048        7128 :     if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
   10049         394 :         isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
   10050             :       return true;
   10051             :     break;
   10052             :   }
   10053             : 
   10054             :   // Maybe it can be proved via operations?
   10055       89665 :   if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
   10056             :     return true;
   10057             : 
   10058       89626 :   return false;
   10059             : }
   10060             : 
   10061       51032 : bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,